Course contents 01 / 17

01 / 17 · Reading Tables

Tables and the first query

Read a table as named, typed columns and meaningful rows, then obtain a result with SELECT, FROM and WHERE. A small order-line example exposes identity, repeated values and the need to request an order.

On this page 10

A shop has recorded six order lines. Which lines contain at least two units, and how much does each of those lines cost? Before writing a query, we need to know what one row records. Otherwise a syntactically valid answer can measure the wrong thing.

What does one row mean?#

An order may contain several products. We store one product position of one order in each row of order_lines. The six rows below are a toy dataset; all later results are calculated from these values.

order_idline_noproductquantityunit_price_cents
1011tea2350
1012coffee1600
1021tea1350
1031coffee2600
1032tea1350
1041cocoa3400

The first row says that position 1 of order 101 contains two units of tea, each priced at 350 cents. Prices use a single currency throughout the example. A cent is its minor unit, so the line amount is 700 cents. Keeping the amount in integer cents lets us check the arithmetic without rounding a fractional currency amount.

Orders 101 and 103 each occupy two rows. There are six order lines and four orders. Counting the displayed rows would answer a question about positions; it would give the wrong number of orders. This difference is the grain of the data: the precise kind of observation represented by one row. The column names alone do not establish the grain. A table named sales could contain orders, individual positions, payments or daily totals. Its meaning has to be stated.

Figure

One row records one order line

Columns, types and six order linesA five-column table. The first two rows belong to order 101 and differ by line number. Quantities and prices are integers.order_idintegerline_nointegerproducttextquantityintegerunit_price_centsinteger1011tea23501012coffee16001021tea13501031coffee26001032tea13501041cocoa3400101/1 and 101/2: one order, two linesThe display position is not a field of the data.The first order line and its schemaThe first row contains order_id 101, line_no 1, product tea, quantity 2 and unit_price_cents 350. Each field has a type. The source table contains six rows.First row: order line 101/1order_idinteger101line_nointeger1producttextteaquantityinteger2unit_price_centsinteger350101/2 is another line of order 101Full table: 6 rows × 5 columnsDisplay position does not identify a row.
Six order lines, five columns. Order 101 occupies two rows. The pair order_id and line_no distinguishes the lines in this example; product repeats. The narrow version separates the values and types of the first row.

The pair order_id, line_no distinguishes the six positions in this dataset. order_id alone cannot do so because it repeats. The product cannot identify a position either: tea occurs in three positions. We will later declare constraints that make the database enforce identities; for now, the uniqueness of the pair is a property of these six example rows.

What does the schema describe?#

A column is a named field whose values have a specified type. quantity and unit_price_cents contain integers; product contains text. A row supplies values for the same columns as every other row of the table. The schema describes that structure, while the current rows are its contents (Pavlo, 2025, §§3–4; PostgreSQL 18, §2.2).

The schema stays meaningful when there are no rows. An empty order_lines table still has five named columns. We can see which fields a row contains and which operations their types support before any order has been recorded. Conversely, an extra row adds an observation without adding another field. These are different changes, even if a spreadsheet makes both look like edits to a grid.

A declared type constrains representation; it does not supply every business rule. An integer quantity can represent 2, but it can also represent a negative integer. The table definition used below does not declare that quantities must be positive. Such rules need explicit constraints or application logic. It is useful to separate “this value has the declared type” from “this value is allowed by the model.”

The word database refers to the stored collection of data. A database management system, or DBMS, is the software that manages it. PostgreSQL is the DBMS used for the SQL examples. A client, such as the psql command-line program or a Python application, sends a query in SQL (Structured Query Language). Row numbers and borders added by the client belong to the display.

A reproducible table#

The examples use PostgreSQL 18 documentation and its SQL dialect. The following setup creates a temporary table and inserts the six rows. A temporary table belongs to the current database session and is removed when that session ends (PostgreSQL 18, CREATE TABLE). It makes the example self-contained without changing an existing application table.

CREATE TEMP TABLE order_lines (
    order_id integer,
    line_no integer,
    product text,
    quantity integer,
    unit_price_cents integer
);

INSERT INTO order_lines VALUES
    (101, 1, 'tea',    2, 350),
    (101, 2, 'coffee', 1, 600),
    (102, 1, 'tea',    1, 350),
    (103, 1, 'coffee', 2, 600),
    (103, 2, 'tea',    1, 350),
    (104, 1, 'cocoa',  3, 400);

The names after CREATE TEMP TABLE describe the columns in order. Each parenthesized group after VALUES supplies one row in that same column order. Single quotes mark text literals such as 'tea'. The unquoted quantity in a query is a column name. A semicolon terminates a statement, so the setup consists of two statements even though it spans many lines.

The setup is intended for a fresh session and is run once before the queries. Running the INSERT again would append another six rows. Reading data and creating or modifying it are separate operations; the queries below only read the prepared table.

What does SELECT return?#

We can request the five fields explicitly:

SELECT order_id, line_no, product, quantity, unit_price_cents
FROM order_lines
ORDER BY order_id, line_no;

FROM order_lines names the input. The list after SELECT names the output columns and their order. ORDER BY requests the row order used in the displayed table above. The statement returns six rows and five columns. SELECT * is a shorthand for selecting all input columns, but an explicit list also says which output the reader or application expects (PostgreSQL 18, §2.5).

A query result has a schema and rows of its own. It can be displayed, consumed by a program or used inside another query. Executing this SELECT does not create a permanent table named after the result, nor does it change order_lines. If a row changes between separate executions, a later query can return a different answer; persistence and the visibility of concurrent changes will be developed with transactions.

This separation of a requested answer from its physical access method is physical data independence. The query names fields and a table without naming a disk file, a byte offset or an index. Codd’s relational model made independence from storage representation a central design requirement (Codd, 1970, §§1.2–1.3). How a DBMS finds an efficient execution strategy belongs to the databases course. Here we determine which answers satisfy the query.

Keeping the matching rows#

The question asks for positions containing at least two units. That gives us a condition on quantity:

SELECT order_id, line_no, product
FROM order_lines
WHERE quantity >= 2
ORDER BY order_id, line_no;
order_idline_noproduct
1011tea
1031coffee
1041cocoa

WHERE retains a row when its condition evaluates to true. For the six quantities, the comparisons are 2 >= 2, 1 >= 2, 1 >= 2, 2 >= 2, 1 >= 2 and 3 >= 2. The first, fourth and sixth comparisons are true, which accounts for all three output rows. Every quantity in this dataset is known; missing values will require the additional rules of NULL.

Figure

WHERE keeps rows whose condition is true

Evaluate the condition for each order lineThe quantities are 2, 1, 1, 2, 1 and 3. At least two is true for the first, fourth and sixth order line.line · quantityquantity >= 2retained order lines101/1 · 2TRUE101/1101/2 · 1FALSE102/1 · 1FALSE103/1 · 2TRUE103/1103/2 · 1FALSE104/1 · 3TRUE104/16 source rows → 3 result rowsEvaluate the condition for each order lineThe quantities are 2, 1, 1, 2, 1 and 3. At least two is true for the first, fourth and sixth order line.line · quantityquantity >= 2101/1 · 2TRUE101/2 · 1FALSE102/1 · 1FALSE103/1 · 2TRUE103/2 · 1FALSE104/1 · 3TRUEKeep 3 order lines:101/1103/1104/1
Evaluate quantity >= 2 for each of the six lines. Lines 101/1, 103/1 and 104/1 survive. Every quantity in this example is known; the source rows stay unchanged.

The condition uses quantity, although that column is absent from the result. Input fields can determine whether a row qualifies without being returned. The output list and the filter answer separate questions: what to report and which input observations qualify. Keeping an identity in the result makes the answer traceable to the original position even when other fields are omitted.

There is also an important boundary in the question. This query selects individual positions with at least two units. Order 101 contains three units in total, but its one-unit coffee position is excluded. To select whole orders by their total quantity, we must combine several rows belonging to each order. Grouping and aggregation introduce that operation later.

Computing an output field#

The first question also asks for the amount of each retained line. The input already contains both factors, so an output column can be an expression:

SELECT order_id, line_no,
       quantity * unit_price_cents AS line_total_cents
FROM order_lines
WHERE quantity >= 2
ORDER BY order_id, line_no;
order_idline_noline_total_cents
1011700
10311200
10411200

For position 101/1, multiplying 2 by 350 gives 700. Position 103/1 gives 2 times 600, or 1200. Position 104/1 gives 3 times 400, also 1200. Equal amounts can describe different observations. Retaining the two identity fields lets us distinguish them.

AS line_total_cents gives the expression an output name. It changes the result schema and leaves the source schema unchanged. The input table still contains quantity and unit_price_cents; it has not gained a stored line_total_cents column. We can request a different expression in a later query without rewriting the source data.

Each multiplication is performed for one input observation that satisfies the filter. There is no sum across rows in this query. Reading the result as three order totals would be a grain error: order 101 also contains a coffee line whose amount is absent here.

Why do repeated values survive?#

Selecting fewer columns can hide the information that distinguished observations:

SELECT product
FROM order_lines
ORDER BY order_id, line_no;

The output is tea, coffee, tea, coffee, tea, cocoa: six rows with one column each. tea occurs three times because three input positions contain tea. Choosing one field does not instruct SQL to combine or remove observations. A plain SELECT keeps such repetitions; deduplication is an additional requested operation (PostgreSQL 18, SELECT, “DISTINCT Clause”).

Figure

One output column still contains six rows

Selecting product without removing duplicatesSix distinct order lines produce tea, coffee, tea, coffee, tea and cocoa. Equal values are not merged.source lineproduct101/1tea101/2coffee102/1tea103/1coffee103/2tea104/1cocoa6 lines → 6 rows, including 3 tea valuesSelecting product without removing duplicatesSix distinct order lines produce tea, coffee, tea, coffee, tea and cocoa. Equal values are not merged.source lineproduct101/1tea101/2coffee102/1tea103/1coffee103/2tea104/1cocoa6 lines → 6 rows, including 3 tea values
SELECT product emits one value per source line. The three tea values remain three rows. The left-hand side shows source-line identities that the output on the right no longer contains.

The mathematical relational model treats a relation as a set of tuples. SQL query results can contain repeated rows, so the two are not interchangeable without accounting for duplicates. For now the operational rule is enough: the one-column result has six rows. A later query that counts them would count six observations, even though only three distinct product names appear.

Where does row order come from?#

Without ORDER BY, the query specifies which rows to return but leaves their presentation order unspecified. The result may happen to follow insertion order on one run. Repeating that observation does not turn it into a guarantee. A different way of finding the same qualifying rows can produce a different order (PostgreSQL 18, SELECT, “ORDER BY Clause”).

Figure

Result order is a separate requirement

Two permitted orders and one explicitly requested orderWithout sorting, 101/1, 103/1, 104/1 and 104/1, 101/1, 103/1 are both permitted. Ordering by order and line number requires the first order.Without ORDER BY: A or BA101/1103/1104/1B104/1101/1103/1Requested order101/1103/1104/1ORDER BY order_id, line_noThe same rows, with a different presentation order.Two permitted orders and one explicitly requested orderWithout sorting, 101/1, 103/1, 104/1 and 104/1, 101/1, 103/1 are both permitted. Ordering by order and line number requires the first order.Without ORDER BY: A or BA101/1103/1104/1B104/1101/1103/1Requested order101/1103/1104/1ORDER BY order_id, line_noThe query specifies presentation order.
For quantity >= 2, both orders A and B are permitted without ORDER BY. ORDER BY order_id, line_no gives order A. Those pairs are distinct in this example, so they determine the full order.

ORDER BY order_id, line_no compares order numbers first and uses the line number when they tie. The pairs are distinct in the prepared data, so every selected row has a defined position. Ordering by order_id alone would leave the relative order of lines 101/1 and 101/2 unspecified when both are returned. A predictable result order requires enough fields to resolve the ties that matter to its consumer.

Ordering changes presentation and preserves the selected rows. The output columns still follow the SELECT list. These are independent choices: a column needed for sorting can be omitted from a plain query’s output, as in the product example. Rules for sorting, duplicates and limiting results will be developed together, because requesting only the first few rows makes an unspecified order consequential.

An answer can contain no rows#

If the condition becomes quantity >= 4, none of the six positions qualifies. The query still succeeds and its result still has the requested order_id, line_no and product columns. It contains zero rows. This differs from referring to a nonexistent table or misspelling a column name, which prevents PostgreSQL from resolving the statement.

An empty answer has a precise meaning only relative to the prepared input and the written condition. It says that no recorded position passes that condition. It does not establish that the shop has no orders or that a loading process supplied every sale. The query’s logic and the completeness of its input are separate requirements.

What to remember#

  • State what one input row represents before counting or calculating.
  • A table has named, typed columns; the current rows can change.
  • FROM names the input, WHERE chooses rows and SELECT forms output fields.
  • A plain SELECT can retain repeated output rows; request an order explicitly when it matters.
  • A result has its own schema, including when it contains zero rows.

Next#

A single comparison selects the right positions here. More detailed questions need several conditions, calculated fields and names that remain unambiguous. The same order lines let us see how grouping two conditions changes the answer. Expressions and filtering

If the input arrives as CSV or JSON, Python provides the means to read it. Files and exceptions

References#

  1. E. F. Codd. A Relational Model of Data for Large Shared Data Banks. Communications of the ACM 13(6), 377–387, 1970. §§1.2–1.3: data independence and the relational representation; §2.1.2: projection in the set-based model.
  2. Andy Pavlo. Relational Model & Algebra. CMU 15-445/645, Fall 2025, lecture 1. §§1, 3–4: database, DBMS, schema and declarative access.
  3. PostgreSQL Global Development Group. PostgreSQL 18 documentation: The SQL Language, 2025. §2.2: tables and types; §2.5: simple queries; SELECT: output expressions, repeated rows and ordering; CREATE TABLE: temporary-table lifetime.