Course contents 02 / 17

02 / 17 · Reading Tables

Expressions and filtering

Build conditions from comparisons, check what happens at interval boundaries, and see which parts of a query can use a computed column name.

On this page 6

We need the positions containing at least two units of tea or coffee. The six rows from the first query include a position with one unit of tea. A filter that admits it is answering a different question, even if every comparison in the filter is valid.

Expressions and predicates#

An expression produces a value. A column reference reads the value in the current row, and a literal supplies a value written in the query. On line 101/1, the references quantity and unit_price_cents give 2 and 350. The expression quantity * unit_price_cents combines them to give 700 cents. A comparison such as quantity >= 2 gives the Boolean value TRUE for that row. These are examples of value expressions in PostgreSQL. PostgreSQL 18, §4.2

Suppose a fee of 50 cents can be charged once per order line or once per unit. Each policy gives an expression over the same inputs. The WHERE condition below chooses line 101/1 so we can compare the results on a single row.

SELECT quantity * unit_price_cents + 50 AS with_line_fee_cents,
       quantity * (unit_price_cents + 50) AS with_unit_fee_cents
FROM order_lines
WHERE order_id = 101 AND line_no = 1;

Multiplication binds more tightly than addition. The first expression multiplies 2 by 350 and adds 50, giving 750 cents. The parentheses in the second expression add 50 to the unit price before the multiplication, giving 800 cents. Both policies charge the same amount when quantity is 1. The two-unit line is the one that distinguishes them. PostgreSQL 18, §4.1.6

A predicate is an expression used as a condition. WHERE keeps the rows for which the predicate is true. The list after SELECT gives the fields of each resulting row. These are separate operations in the logical description. Selection restricts the rows, while projection forms the output fields from them. The same input column can participate in a predicate and be absent from the output. Pavlo, 2025, §6

Combining conditions#

For the shop’s request, one test checks the quantity and another checks the product. The quantity must reach the threshold in either product case.

SELECT order_id, line_no, product, quantity
FROM order_lines
WHERE quantity >= 2 AND (product = 'tea' OR product = 'coffee')
ORDER BY order_id, line_no;
order_idline_noproductquantity
1011tea2
1031coffee2

In this dataset every value used by the comparisons is present. Let PP and QQ stand for any two comparisons with results TRUE or FALSE. AND requires both, OR requires at least one, and NOT reverses one result. OR also accepts the case where both operands are true. PostgreSQL 18, §9.1

PPQQP AND QP OR QNOT P
TRUETRUETRUETRUEFALSE
TRUEFALSEFALSETRUEFALSE
FALSETRUEFALSETRUETRUE
FALSEFALSEFALSEFALSETRUE

Line 104/1 contains three units of cocoa. The quantity test passes and the product test fails, so the AND excludes it. On line 101/1, the quantity test passes and one product comparison is enough to make the product test true.

How parentheses change the result#

Putting the product tests first and dropping the parentheses changes the grouping. The following is valid SQL.

SELECT order_id, line_no, product, quantity
FROM order_lines
WHERE product = 'tea' OR product = 'coffee' AND quantity >= 2
ORDER BY order_id, line_no;

Comparisons bind more tightly than the Boolean operators. Among the Boolean operators, NOT binds most tightly, followed by AND and then OR. These rules are called operator precedence. The ungrouped filter means product = 'tea' OR (product = 'coffee' AND quantity >= 2). For line 102/1 the first part is true because its product is tea. The whole OR is therefore true, although quantity >= 2 is false. The same reasoning admits line 103/2. PostgreSQL 18, §4.1.6

Figure

Parentheses apply the quantity limit to both products

Comparison of two groupings of the conditionsThe grouped condition keeps 101/1 and 103/1. The ungrouped condition also keeps 102/1 and 103/2.LineProductUnitsGroupedUngrouped101/1tea2YesYes101/2coffee1NoNo102/1tea1NoYes103/1coffee2YesYes103/2tea1NoYes104/1cocoa3NoNo2 rows4 rowsComparison of two groupings of the conditionsThe grouped condition keeps 101/1 and 103/1. The ungrouped condition also keeps 102/1 and 103/2.LineProductUnitsGroupedUngrouped101/1tea2YesYes101/2coffee1NoNo102/1tea1NoYes103/1coffee2YesYes103/2tea1NoYes104/1cocoa3NoNo2 rows4 rows
The filter asks for tea or coffee in quantities of at least two. Without parentheses the threshold applies only to coffee. Lines 102/1 and 103/2, each with one unit of tea, enter the result.

Read parentheses as part of the question. To find positions with at least two units of a product outside the tea and coffee selection, put NOT around the whole product test.

SELECT order_id, line_no, product, quantity
FROM order_lines
WHERE quantity >= 2 AND NOT (product = 'tea' OR product = 'coffee')
ORDER BY order_id, line_no;

Only line 104/1 remains. Cocoa makes both product comparisons false, so negating their OR gives true. The quantity still has to pass its own test. The expression inside the parentheses is the operand of NOT, which makes its scope explicit.

Precedence gives the structure of a predicate. PostgreSQL can evaluate or transform its parts in an order chosen by the engine. Use parentheses to express the Boolean meaning, and leave the order of work to the engine. PostgreSQL 18, §4.2.14

Which boundaries are included?#

Now the request is about the amount of a position. We want amounts of at least 700 cents and less than 1200 cents. Let vv denote quantity * unit_price_cents for a row. The requested interval is 700≤v<1200700 \le v < 1200, written [700,1200)[700, 1200).

SELECT order_id, line_no,
       quantity * unit_price_cents AS line_total_cents
FROM order_lines
WHERE quantity * unit_price_cents >= 700
  AND quantity * unit_price_cents < 1200
ORDER BY line_total_cents, order_id, line_no;
order_idline_noline_total_cents
1011700

Line 101/1 reaches the lower bound exactly and passes both tests. Lines 103/1 and 104/1 each cost 1200 cents. They pass the first test and fail the second. All other lines cost less than 700 cents, so there is only one result.

Figure

The interval includes the lower boundary

A half-open amount intervalA filled dot marks the included boundary at 700 and an open dot marks the excluded boundary at 1200.Line amount in cents7001200IncludedExcluded101/1103/1, 104/1A half-open amount intervalA filled dot marks the included boundary at 700 and an open dot marks the excluded boundary at 1200.Line amount in cents7001200IncludedExcluded101/1103/1, 104/1
The interval from 700 inclusive to 1200 exclusive keeps line 101/1. Lines 103/1 and 104/1 cost exactly 1200 cents and lie on the excluded boundary.

BETWEEN 700 AND 1200 includes both boundaries. With that predicate, lines 103/1 and 104/1 enter the result, giving three rows instead of one. The two comparisons express which boundary to include. This is useful when amounts fall into adjacent bands. A line priced at 1200 cents belongs to a band starting at 1200 and does not also belong to [700,1200)[700, 1200). PostgreSQL 18, §9.2

Where is an output name visible?#

It is tempting to replace the calculation in WHERE with the name written after AS.

SELECT order_id, line_no,
       quantity * unit_price_cents AS line_total_cents
FROM order_lines
WHERE line_total_cents >= 700;

PostgreSQL reports column "line_total_cents" does not exist. The WHERE of this query resolves column names against its input. The table has quantity and unit_price_cents. The name line_total_cents is an output alias assigned with AS. In the working interval query above, WHERE uses the expression over input fields. ORDER BY line_total_cents can refer to the output alias directly. PostgreSQL 18, SELECT list and ORDER BY

If the input table also had a stored column called line_total_cents, the same WHERE would use that stored column. The query would then filter by the stored amount and display a newly computed amount.

We can trace the meaning of that interval query in four steps.

  1. FROM supplies the columns of order_lines.
  2. WHERE applies the two boundary tests to each row.
  3. SELECT forms the three output fields and names the computed amount.
  4. ORDER BY requests a result order using the amount and the position identifiers.
Figure

Where the output column name appears

Name scopes in the queryFROM supplies input, WHERE filters rows, SELECT names the output, and ORDER BY can use that name.FROMorder_lines1WHEREFilter by amount2SELECTline_total_cents3ORDER BYName from SELECT4Name scopes in the queryFROM supplies input, WHERE filters rows, SELECT names the output, and ORDER BY can use that name.FROMorder_lines1WHEREFilter by amount2SELECTline_total_cents3ORDER BYName from SELECT4
The WHERE condition uses input names and the amount expression. SELECT assigns line_total_cents, which can then name the sort key.

This is the logical processing order for interpreting the query. The database chooses a physical strategy to implement it. For a condition on a suitable indexed column, an engine can find matching candidates through an index or read the table and test the condition. The selection defines the same result for either access path. Selinger et al., 1979, §§2–4

Make the output an input#

When repeating a calculation makes the filter hard to read, put the calculation in a query inside FROM. Its result becomes the input of the outer query.

SELECT order_id, line_no, line_total_cents
FROM (
    SELECT order_id, line_no,
           quantity * unit_price_cents AS line_total_cents
    FROM order_lines
) AS priced
WHERE line_total_cents >= 700 AND line_total_cents < 1200
ORDER BY line_total_cents, order_id, line_no;

The inner query supplies a table with order_id, line_no and line_total_cents. The outer WHERE can now find line_total_cents in that input. The result is again line 101/1 with an amount of 700 cents. The nesting gives the expression a name at the appropriate level. PostgreSQL retains responsibility for how to execute the combined query. PostgreSQL 18, FROM and SELECT list

Next#

Every quantity and price here is a known integer. A missing price raises a new question about the result of multiplication and comparison. Types and NULL develops those rules and explains which expressions can be compared.

References#

  1. PostgreSQL Global Development Group. PostgreSQL 18 documentation, 2025. §4.1.6 gives precedence. §4.2 describes value expressions and their evaluation. §9.1 and §9.2 define logic and comparisons. SELECT specifies output names, the input of a query and ordering.
  2. Andy Pavlo. Relational Model & Algebra. CMU 15-445/645, Fall 2025, lecture 1, §6. Selection and projection are operations with distinct roles.
  3. Patricia G. Selinger, Morton M. Astrahan, Donald D. Chamberlin, Raymond A. Lorie and Thomas G. Price. Access Path Selection in a Relational Database Management System. Proceedings of ACM SIGMOD, 23–34, 1979. §§2–4 describe how a query block becomes an access strategy in System R.