A report can run without an error and still count the wrong things. Before investigating harder reports, check that you can explain a small result without depending on the database to tell you the answer.
Use the printed tables below. You need no PostgreSQL installation, account or running database for this lesson. The SQL blocks are paper examples over these tables, not a setup script. Predict their effects; do not execute the UPDATE or CREATE TABLE examples against an existing database. The next lessons supply and identify the owned practice environment.
This course starts from joins, grouped queries, basic nulls, table definitions and awareness of data-changing statements. It teaches PostgreSQL tools and the advanced reasoning from there. A difficult window frame is expected new work; an unexplained two-table join is a prerequisite gap to resolve first.
Know what one row represents
Harbor Supply is a fictional distributor. In this small example, an order is one purchase record; a line item is one charge within an order. A table's grain is what one row represents. Several line items may belong to one order.
orders has one row per order:
| order_id | org_id | status | sales_channel |
|---|---|---|---|
| 101 | 1 | paid | web |
| 102 | 1 | open | NULL |
| 103 | 2 | open | store |
line_items has one row per line item:
| line_id | order_id | amount |
|---|---|---|
| 11 | 101 | 40.00 |
| 12 | 101 | 60.00 |
| 13 | 102 | 30.00 |
Amounts are already extended line amounts in a single fictional currency unit;
do not multiply them by a quantity. NULL denotes a missing value, not the text
'NULL', an empty string or zero. Order 103 has no line item in this example.
Consider this complete paper query:
SELECT o.order_id, li.line_id, li.amount
FROM orders AS o
LEFT JOIN line_items AS li ON li.order_id = o.order_id
ORDER BY o.order_id, li.line_id;
o and li are aliases: short names for the two table references. The ON
condition pairs a line with its order. The selected columns identify each pair;
the ordering makes the displayed sequence explicit.
For 101, there are two matching lines, so there are two output rows. For 102, there is one. The left join retains order 103 and supplies nulls for its missing line. The derived result is:
| order_id | line_id | amount |
|---|---|---|
| 101 | 11 | 40.00 |
| 101 | 12 | 60.00 |
| 102 | 13 | 30.00 |
| 103 | NULL | NULL |
The result has four rows, although there are only three orders. Its grain is an order–line pair, plus a retained order with no line. An inner join would omit that last row. Follow each order through the matches rather than guessing that a join must preserve the left table's row count.
Guided check: count, total, filter and change
Write your predictions before opening the explanation.
- For each order, predict
joined_rows,linesandgrossbelow. Why do the two counts differ for 103? - Which order does
WHERE sales_channel IS NULLselect? What does the ordinary comparisonsales_channel = NULLfail to establish? - Which order IDs would the paper UPDATE affect? How would removing its WHERE clause change the scope?
- If the grouped query adds
HAVING SUM(li.amount) > 40after GROUP BY, which order group remains? How does that differ from filtering individual line rows before grouping?
SELECT o.order_id,
COUNT(*) AS joined_rows,
COUNT(li.line_id) AS lines,
SUM(li.amount) AS gross
FROM orders AS o
LEFT JOIN line_items AS li ON li.order_id = o.order_id
GROUP BY o.order_id
ORDER BY o.order_id;
The join supplies the input rows already shown. GROUP BY puts rows with the
same order ID together. Each aggregate then measures that group's inputs;
ORDER BY controls presentation. AS names each result column.
-- Paper example only: predict affected IDs; do not execute it.
UPDATE orders
SET status = 'held'
WHERE status = 'open';
SET describes the proposed new status. WHERE chooses which existing rows
qualify. Matching a predicate is not proof that you are connected to an owned
database or authorized to modify it.
Answer and reasoning
| order_id | joined_rows | lines | gross |
|---|---|---|---|
| 101 | 2 | 2 | 100.00 |
| 102 | 1 | 1 | 30.00 |
| 103 | 1 | 0 | NULL |
For 103 the left join contributed one retained row. COUNT(*) counts that
input row; COUNT(li.line_id) has no non-null line ID to count. SUM(li.amount)
has no non-null amount and returns null here. Deciding to display zero instead
is a reporting decision, not evidence that a line worth zero exists.
The missing channel belongs to 102. IS NULL tests absence. An ordinary
comparison with null yields unknown, so sales_channel = NULL does not identify
the missing channel. A WHERE filter retains true results, not unknown ones.
The proposed UPDATE qualifies 102 and 103. Without WHERE it qualifies all three
orders, including paid order 101. The assignment 'held' is the new value; it
does not restrict the old rows. These are predicted effects, not executed changes.
The HAVING condition retains only group 101: its total is 100.00. It filters a group after aggregation. Filtering individual line amounts first could instead discard facts used to calculate a total; for example, the 40.00 line would not pass a strict line-level greater-than-40 filter.
Read the relationship before trusting the query
This paper definition describes the line-item columns used above:
-- Paper definition; assumes the shown orders key already exists.
CREATE TABLE line_items (
line_id bigint PRIMARY KEY,
order_id bigint NOT NULL REFERENCES orders(order_id),
amount numeric(10, 2) NOT NULL
);
bigint is an integer type. The primary key identifies a line uniquely.
order_id is required and must reference an existing order key. It is not
itself unique, so both lines 11 and 12 may reference 101. The amount is a
required decimal value with ten total digits, two after the decimal point.
Later lessons examine precision and rounding decisions more deeply.
A foreign key does not require every order to have a line. That is why order 103 is consistent with this relationship. A required amount on an existing line also does not stop an outer join from producing nulls for an absent line.
If the definition is hard to read, first bridge the difference between a row's own key, a reference to another row and a required value. Do not infer the relationship merely from similar column names.
Independent variation
Treat this as a separate printed dataset, replacing the earlier rows.
| order_id | org_id | status | sales_channel |
|---|---|---|---|
| 201 | 7 | open | partner |
| 202 | 7 | paid | NULL |
| 203 | 8 | open | web |
| line_id | order_id | amount |
|---|---|---|
| 21 | 201 | 25.00 |
| 22 | 201 | 25.00 |
| 23 | 203 | 50.00 |
Without running SQL:
- List the ordered result of the first left-join query.
- Predict the grouped query's three measurements for each order.
- Identify the missing-channel order and the IDs affected by the same proposed open-to-held UPDATE. Explain the no-WHERE case separately.
- Explain whether the two equal amounts are duplicates to remove, and whether both line rows can reference 201 under the displayed definition.
Hint 1: Trace one order at a time. An order with no child still has one left-join output row.
Hint 2: Count line identifiers separately from output rows. Line identity and equal monetary value answer different questions.
Answer and reasoning
The ordered join rows are (201, 21, 25.00), (201, 22, 25.00),
(202, NULL, NULL) and (203, 23, 50.00).
| order_id | joined_rows | lines | gross |
|---|---|---|---|
| 201 | 2 | 2 | 50.00 |
| 202 | 1 | 0 | NULL |
| 203 | 1 | 1 | 50.00 |
Order 202 has the missing channel. The proposed filtered UPDATE qualifies 201 and 203; the unrestricted version qualifies all three. Lines 21 and 22 have different keys and are both legitimate facts here. Removing one because its amount equals another's would lose 25.00. Both may reference 201 because the foreign-key column is not declared unique.
A focused bridge for each difficulty
| Difficulty | Reconstruct before continuing |
|---|---|
| “A join returns three rows because there are three orders” | Write the matching child IDs beside each parent. Then retain the unmatched parent for a left join. |
| “COUNT(*) and COUNT(line_id) are interchangeable” | Mark which retained rows have a real line ID. Count rows and known IDs separately. |
| “Missing means zero” | Separate an absent observation from an observed amount of zero. State which the question requires. |
| “SET chooses the old rows” | Read the WHERE predicate against the old table first; then apply the proposed assignment to those rows. |
| “A foreign key makes the child reference unique” | Find the child's own primary key and check whether the reference column also has a uniqueness rule. |
For file readiness, use an ordinary text editor in a new empty folder you
own. Save a file named readiness-note.sql containing only
-- My readiness note, choosing UTF-8 plain text. The two hyphens begin a SQL
comment; there is no statement to execute. Reopen the file from that folder,
confirm the filename did not become .sql.txt, and locate the folder from your
terminal using the navigation skills you already know. If you cannot do that,
practice saving plain-text files and navigating folders before the setup lesson.
Remove only this note and its newly created empty folder when finished; do not
remove an existing workspace. No database cleanup is required for this lesson.
Decide what to do next
You are ready for setup when you can explain the independent rows, totals, null case, relationship and affected-row scope, and can save/find the small plain-text input. This is a self-check, not an automatically graded result. If one bridge resolves a mistake, retry that question on changed values. If the same prerequisite remains unclear, study it before the dependent lessons.
You do not need to understand execution plans, window frames, row policies or transaction retries yet. Those are taught later. The important starting habit is to explain why the selected rows are right before trusting a successful execution or reading-progress indicator.
References
These first-party references support the SQL rules; the tables and questions above are original course examples.