Advanced SQL with PostgreSQL / Readiness and an owned local lab

Check your SQL starting skills

Lesson 1 of 51. Open to read. No account needed.

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_idorg_idstatussales_channel
1011paidweb
1021openNULL
1032openstore

line_items has one row per line item:

line_idorder_idamount
1110140.00
1210160.00
1310230.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_idline_idamount
1011140.00
1011260.00
1021330.00
103NULLNULL

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.

  1. For each order, predict joined_rows, lines and gross below. Why do the two counts differ for 103?
  2. Which order does WHERE sales_channel IS NULL select? What does the ordinary comparison sales_channel = NULL fail to establish?
  3. Which order IDs would the paper UPDATE affect? How would removing its WHERE clause change the scope?
  4. If the grouped query adds HAVING SUM(li.amount) > 40 after 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_idjoined_rowslinesgross
10122100.00
1021130.00
10310NULL

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_idorg_idstatussales_channel
2017openpartner
2027paidNULL
2038openweb
line_idorder_idamount
2120125.00
2220125.00
2320350.00

Without running SQL:

  1. List the ordered result of the first left-join query.
  2. Predict the grouped query's three measurements for each order.
  3. Identify the missing-channel order and the IDs affected by the same proposed open-to-held UPDATE. Explain the no-WHERE case separately.
  4. 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_idjoined_rowslinesgross
2012250.00
20210NULL
2031150.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

DifficultyReconstruct 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.

46 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 149 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy