Skip to content

SQL Querying Fundamentals: Relations, NULL, Joins, GROUP BY & HAVING, Subqueries, Set Operations, CTEs ​

"Future users of large data banks must be protected from having to know how the data is organized in the machine (the internal representation)." — E. F. Codd, A Relational Model of Data for Large Shared Data Banks, Communications of the ACM, 1970

Summary: SQL describes the rows you want, not the steps to get them; it works on relations (sets of rows) with three-valued logic, and most "SQL bugs" are a NULL, an outer join or a GROUP BY behaving exactly as the standard says. Focus: The relational model in SQL terms, NULL and three-valued logic, the logical evaluation order of SELECT, every join kind, semi- and anti-joins, subqueries, GROUP BY and HAVING, set operations, CTEs, sorting and limiting, expressions, INSERT ... RETURNING / UPDATE ... FROM / DELETE ... USING, and the dialect differences between PostgreSQL 18, MySQL 8.4 and SQLite 3. Learning goal: Predict the exact result set of any query on paper before you run it, write anti-joins and aggregates that stay correct when NULLs and empty groups appear, and port a query between PostgreSQL, MySQL and SQLite without silent changes in meaning.

This page is the complete reference for the SQL query language itself: what a query means, independent of how fast it runs. It starts from the relational model (relation, tuple, attribute, domain, and the relational algebra operators SQL is built on), then covers NULL and three-valued logic, the logical order in which a SELECT is evaluated, every join kind (inner, left, right, full outer, cross, natural, USING, self join, semi-join and anti-join), subqueries (scalar, correlated, derived tables, LATERAL), aggregation with GROUP BY and HAVING including the ONLY_FULL_GROUP_BY rule and functional dependence, set operations, common table expressions (including recursive ones and the MATERIALIZED hint), ORDER BY with NULLS FIRST/NULLS LAST, LIMIT/OFFSET/FETCH FIRST, CASE, string and date functions, implicit casts, identifier quoting and case sensitivity, and data-changing statements that return rows. Every result set on the page is real sqlite3 3.54.0 output from one lab script; statements SQLite does not accept are labelled "expected, not run".

Neighbours own the rest. How fast a query runs, EXPLAIN and join algorithms are in Query Planning; worked plan and index examples are in the SQL Queries & Indexes Cheatsheet; which index serves which query is in Indexing. Window functions, FILTER, GROUPING SETS, deep recursive CTEs, LATERAL patterns, upsert and JSON aggregation are in Advanced SQL. Keyset vs offset pagination is in Pagination; normal forms and data types are in Schema Design; transactions are in ACID & Transactions; ORM-generated SQL is in ORM Pitfalls. Product command references live in the PostgreSQL, MySQL and SQLite cheatsheets, and the PostgreSQL overview is PostgreSQL & Database Fundamentals.

Page map ​

If you are looking forGo to
Every rule on one screenEverything in one minute
Why SQL is declarative and set-basedWhy SQL works this way
Codd, SEQUEL, SQL-86 to SQL:2023Where it comes from
The three tables every example usesThe lab schema
Relation, tuple, attribute, domain, relational algebraThe relational model in SQL terms
NULL, UNKNOWN, IS NULL, IS DISTINCT FROM, COALESCE, NULLIFNULL and three-valued logic
Why an alias is unknown in WHEREHow a SELECT is evaluated
Inner, left, right, full, cross, natural, self joinsJoins
EXISTS, IN, NOT IN with NULL, correlated, scalar, derived, LATERALSubqueries, semi-joins and anti-joins
COUNT(*), HAVING, ONLY_FULL_GROUP_BY, functional dependenceAggregation
UNION, UNION ALL, INTERSECT, EXCEPTSet operations
WITH, MATERIALIZED, WITH RECURSIVECommon table expressions
NULLS FIRST, LIMIT, OFFSET, FETCH FIRSTSorting and limiting
CASE, string and date functions, casts, quotingExpressions and types
RETURNING, UPDATE ... FROM, DELETE ... USINGChanging data with queries
PostgreSQL vs MySQL vs SQLite vs the othersDialect differences
Error codes and what the engine does with your queryMechanics
Top-N per group, latest row, missing rows, Go and Laravel codeSolving the classic problems
Which construct for which questionChoosing a construct
Services, replicas, caches, shardingIn architecture
Run every example yourselfLab
Test yourself, wrong beliefs, termsSelf-check, Misconceptions, Cheat sheet, Glossary

Everything in one minute ​

The logical evaluation order of one SELECT (the order the result must match, whatever the planner does).

StepClauseIn plain wordsWhat it can see
1FROM / JOINBuild one big row set from the tablesTable columns
2WHEREKeep rows whose condition is TRUETable columns, no aggregates, no select aliases
3GROUP BYFold rows into groupsTable columns and expressions
4HAVINGKeep groups whose condition is TRUEGrouped columns and aggregates
5SELECTCompute output expressions and aliasesGrouped columns, aggregates, window functions
6DISTINCTRemove duplicate output rowsOutput columns
7UNION / INTERSECT / EXCEPTCombine query blocksOutput columns by position
8ORDER BYSortOutput aliases and (outside set operations) input columns
9LIMIT / OFFSET / FETCH FIRSTCut the sorted resultRow positions

Joins and subquery shapes.

ConstructKeepsTiny example (lab data)Watch out
INNER JOINMatched pairs only8 customer-order rows, Eve missingMultiplies rows per match
LEFT JOINMatched pairs + unmatched left rows with NULLs9 rows, Eve with NULL orderA WHERE on the right table undoes it
RIGHT JOINMatched pairs + unmatched right rowsCoupon SPRING with no orderMySQL docs recommend LEFT JOIN instead
FULL OUTER JOINEverything from both sidesOrders without coupon and coupon without orderNot in MySQL 8.4
CROSS JOINEvery combination (Cartesian product)5 customers × 3 coupons = 15Accidental when the ON is forgotten
Semi-join (EXISTS, IN)Left rows that have a match, onceAnn, Bob, Cy have a paid orderJOIN + DISTINCT is the slow imitation
Anti-join (NOT EXISTS)Left rows with no matchEve has no orderNOT IN with NULL returns nothing
Scalar subqueryOne value per outer rowLast order date per customerMore than one row: error (PostgreSQL, MySQL)
Derived table / CTEA named intermediate resultRevenue per customer, then filterCTE may or may not be materialized

NULL rules.

ExpressionResultWhy
NULL = NULLNULL (UNKNOWN)Unknown compared with unknown is unknown
NULL IS NULLTRUEThe only reliable NULL test
NULL IS NOT DISTINCT FROM NULLTRUENULL-aware equality (MySQL: <=>)
TRUE OR NULL / FALSE AND NULLTRUE / FALSEThe unknown side cannot change the answer
3 NOT IN (1, NULL)NULL3 <> NULL is UNKNOWN
count(col) / count(*)Ignores NULLs / counts rowsAggregates skip NULL inputs
sum(x) over zero rowsNULL, not 0Wrap with COALESCE(sum(x), 0)
GROUP BY, DISTINCT, UNIONAll NULLs form one groupGrouping uses "not distinct", not =
ORDER BY xPostgreSQL: NULLs last ascending; MySQL and SQLite: firstUse NULLS FIRST / NULLS LAST explicitly

Why SQL works this way ​

SQL exists so that an application can ask for data by describing it ("paid orders of German customers, newest first") instead of writing the loops that find it. The database owns the access path: it may scan, use an index, hash, sort or reorder joins, and your query keeps its meaning when the storage changes. That is Codd's 1970 argument in the quote at the top of the page. The price is that you must think in sets and in SQL's precise rules, not in loops: a query that "looks right" can be wrong only on the rows that contain NULL or have no match.

Procedural code (loops over records)Declarative SQL (describe the result)
You pick the access path and the order of stepsThe engine picks them; the result must equal the logical definition
Correctness follows the code you wroteCorrectness follows set semantics and three-valued logic
Easy to reason about one record at a timeEasy to reason about whole sets, harder per row
Changing storage means changing codeIndexes and plans change without touching queries
N+1 round trips are naturalOne statement can join, group and filter on the server

The everyday picture used through the page: a librarian with a card catalogue. You hand over a request slip ("all books by authors born before 1900, grouped by country"); the librarian decides whether to walk the shelves or use the catalogue. A card with a blank "born" field is neither before nor after 1900; it is simply not on your list, unless you asked for blanks explicitly. That blank field is NULL, and most of this page is about what the librarian does with it.

Three common misunderstandings, up front ​

  1. "WHERE x <> 'DE' returns every row that is not DE." It returns rows where the comparison is TRUE; rows with x NULL are UNKNOWN and disappear (lab Q02: Dee is missing).
  2. "A LEFT JOIN always keeps every left row." Only until a WHERE condition on a right-table column throws the NULL-padded rows away again (lab Q08).
  3. "A query without ORDER BY returns rows in insertion or primary-key order." SQL tables are unordered; the PostgreSQL tutorial says SQL "does not guarantee the order of the rows within the table in any way". Order exists only when ORDER BY states it.

Where it comes from ​

The relational model is E. F. Codd's 1970 paper at IBM San Jose (saved: codd.pdf). SQL itself started as SEQUEL; per Wikipedia (secondary source), "SQL was initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce after learning about the relational model from Edgar F. Codd", in the early 1970s, for the System R prototype. The standard is ISO/IEC 9075, maintained by ISO/IEC JTC 1/SC 32.

text
1970  Codd: "A Relational Model of Data for Large Shared Data Banks" (n-ary relations, join, projection)
1973  Chamberlin and Boyce start SEQUEL at the San Jose Research Laboratory (Wikipedia)
1979  Oracle V2, one of the first commercial SQL implementations (Wikipedia)
1986  ANSI standard SQL-86; ISO follows in 1987
1992  SQL-92: ORDER BY may use only output column names or numbers, GROUP BY only input columns (PostgreSQL docs)
1999  SQL:1999 redefines how ORDER BY / GROUP BY expressions are read, "not entirely upward compatible" (PostgreSQL docs)
2008  SQL:2008 adds OFFSET ... FETCH { FIRST | NEXT } (PostgreSQL docs, SELECT compatibility)
2016  SQL:2016
2023  SQL:2023 = ISO/IEC 9075:2023, "the ninth edition", adopted June 2023 (adds SQL/PGQ property graph queries)

What this means for you: the SQL standard defines the core (joins, three-valued logic, GROUP BY, set operations, CTEs), but "virtually no implementations in existence adhere to it fully" (Wikipedia). Every engine adds extensions (LIMIT, RETURNING, <=>, bare columns) and omits parts. This page names the product for every behaviour that is not portable.

The lab schema ​

Every example runs on the shared e-commerce schema of the SQL Queries & Indexes Cheatsheet (customers, orders, order_items), extended for this chapter: customers.name (NOT NULL) plus three nullable columns, customers.country (NULL = unknown), customers.referred_by (a self-reference, NULL = nobody referred them) and orders.coupon_code. Eve has no orders; Dee's country is unknown; Ann and Eve were referred by nobody.

sql
CREATE TABLE customers (
  id          INTEGER PRIMARY KEY,
  email       TEXT NOT NULL UNIQUE,
  name        TEXT NOT NULL,
  country     TEXT,                              -- NULL = unknown
  referred_by INTEGER REFERENCES customers(id),  -- NULL = came on their own
  created_at  TEXT NOT NULL
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  tenant_id   INTEGER NOT NULL,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  status      TEXT NOT NULL CHECK (status IN ('pending','paid','refunded')),
  total       NUMERIC(12,2) NOT NULL,
  coupon_code TEXT,                              -- NULL = no coupon
  created_at  TEXT NOT NULL
);
CREATE TABLE order_items (
  id       INTEGER PRIMARY KEY,
  order_id INTEGER NOT NULL REFERENCES orders(id),
  sku      TEXT NOT NULL,
  qty      INTEGER NOT NULL CHECK (qty > 0),
  price    NUMERIC(12,2) NOT NULL
);
customers.idnamecountryreferred_byorders.idcustomerstatustotalcoupon_code
1AnnDENULL11paid50WELCOME
2BobFR121paid20NULL
3CyDE231refunded15NULL
4DeeNULL142paid99BF26
5EveIRNULL52pending5NULL
63paid40NULL
73paid60BF26
84pending25NULL

On PostgreSQL use bigint GENERATED ALWAYS AS IDENTITY, numeric(12,2) and timestamptz; on MySQL BIGINT AUTO_INCREMENT, DECIMAL(12,2) and DATETIME(6). The full script with seed rows is in the Lab.

The relational model in SQL terms ​

Relation, tuple, attribute, domain Must-know ​

In plain words: a relation is a table, a tuple is a row, an attribute is a named column, and a domain is the set of values a column may hold (its type plus constraints).

Common misunderstanding: "A table is a list of rows in some order, and duplicates are fine." In Codd's model a relation is a set: no order and no duplicate tuples. SQL tables are bags (multisets): duplicates are allowed unless a key forbids them, and order still does not exist. SELECT DISTINCT, UNION and keys are how SQL gets back to set semantics.

Definition: the PostgreSQL tutorial: "Relation is essentially a mathematical term for table." "Each table is a named collection of rows. Each row of a given table has the same set of named columns, and each column is of a specific data type." A relation's heading is its set of attributes; its body is a set of tuples; each attribute takes values from a domain. SQL approximates domains with data types, CHECK, NOT NULL and CREATE DOMAIN (PostgreSQL).

Relational termSQL termLab exampleNotes
RelationTable, view, query resultcustomersA query result is also a relation, which is why queries nest
TupleRow(4, 'dee@x.io', 'Dee', NULL, 1, ...)SQL allows duplicate rows; the model does not
AttributeColumncountryReferenced by name, never by position (except ORDER BY 1)
DomainData type + constraintsstatus IN ('pending','paid','refunded')PostgreSQL CREATE DOMAIN makes a reusable one
Degree / cardinalityNumber of columns / rows6 columns, 5 rows
Candidate key / primary keyPRIMARY KEY, UNIQUE NOT NULLcustomers.id, customers.emailWhat makes functional dependence work in GROUP BY
Foreign keyREFERENCESorders.customer_idJoins usually follow these

Relational algebra: the operators under every query Important ​

In plain words: relational algebra is a small set of operations that take relations and return relations. Every SQL query is a composition of them, which is why the planner can rewrite one shape into another.

Common misunderstanding: "SELECT is selection." In relational algebra, selection (σ) picks rows, which SQL writes as WHERE; projection (π) picks columns, which SQL writes as the SELECT list. The keyword SELECT does the projection.

Algebra operatorSymbolSQL spellingLab example
SelectionσWHERE / HAVINGWHERE status = 'paid'
ProjectionπSELECT col, ... (plus DISTINCT for set semantics)SELECT DISTINCT country
Cartesian product×CROSS JOIN, or FROM a, b without a conditioncustomers × coupons = 15 rows
Theta join / equi-join⋈θJOIN ... ON a.x = b.yorders ⋈ customers
Natural join⋈NATURAL JOIN, JOIN ... USING (col)customers ⋈ country_names
Union, intersection, difference∪ ∩ −UNION, INTERSECT, EXCEPTpaid ∪ pending customers
RenameρAS aliascustomers AS c
Semi-join / anti-join⋉ / ▷EXISTS / NOT EXISTScustomers with / without orders
Grouping and aggregationγGROUP BY + aggregate functionsrevenue per customer

A join is a Cartesian product followed by a selection: FROM a JOIN b ON p means "every pair, keep the ones where p is TRUE". The engine never builds the product when it can avoid it (see Query Planning for nested loop, hash and merge joins), but the meaning is defined that way, and that definition explains outer joins, NULLs in join conditions and row multiplication.

NULL and three-valued logic ​

Three-valued logic: TRUE, FALSE, UNKNOWN (any comparison with NULL)ANDTFUTFUTFUFFFUFUORTFUTFUTTTTFUTUUNOTTFFTUUWHERE, ON, HAVINGkeep TRUE only:U is dropped like F.CHECK keeps U.Why NOT IN with a NULL in the list returns no rows3 NOT IN (1, NULL)3 <> 1 AND 3 <> NULLTRUE AND UNKNOWNUNKNOWN: droppedNOT EXISTS (SELECT 1 FROM customers x WHERE x.referred_by = c.id) is always TRUE or FALSE:a NULL referred_by just fails to match one row; it cannot turn the whole test into UNKNOWN.Lab Q15: NOT IN returns 0 rows, NOT EXISTS returns Cy, Dee, Eve.

NULL and UNKNOWN Must-know ​

In plain words: NULL means "no value here" (unknown, missing or not applicable). Any comparison with NULL gives a third truth value, UNKNOWN, and WHERE, ON and HAVING keep a row only when the condition is TRUE.

Common misunderstanding: "NULL is like an empty string or zero." It is not a value at all. MySQL's manual answers the belief "that NULL is the same thing as an empty string ''" with "This is not the case." Only Oracle Database treats '' as NULL (use-the-index-luke: "the Oracle database treats an empty string as NULL").

Definition: SQL uses three-valued logic: TRUE, FALSE and UNKNOWN (the boolean NULL). AND is FALSE if either side is FALSE, OR is TRUE if either side is TRUE, otherwise UNKNOWN propagates; NOT UNKNOWN is UNKNOWN. Filters (WHERE, ON, HAVING, CASE WHEN) treat UNKNOWN like FALSE; a CHECK constraint treats it like TRUE: PostgreSQL docs, "a check constraint is satisfied if the check expression evaluates to true or the null value."

text
     Expression (lab Q01)                    Result     Rule
1    NULL = NULL                             NULL       unknown vs unknown
2    NULL <> 1                               NULL       unknown vs anything
3    (NULL = 1) OR TRUE                      1 (TRUE)   TRUE wins an OR
4    (NULL = 1) AND FALSE                    0 (FALSE)  FALSE wins an AND
5    NOT (NULL = 1)                          NULL       NOT keeps UNKNOWN
6    SELECT ... WHERE country = NULL         0 rows     no row is ever TRUE
7    SELECT ... WHERE country <> 'DE'        Bob, Eve   Dee (NULL) is UNKNOWN, dropped

Real scenario: a "customers outside Germany" export silently misses every customer whose country was never captured; a fraud rule amount > limit never fires when limit is NULL; a CHECK (discount <= 50) lets a NULL discount in; a dashboard counts count(coupon_code) and reports 3 orders with coupons out of 8 rows, while the business expected count(*).

BehaviourPostgreSQL 18MySQL 8.4SQLite 3.54OracleSQL Server
NULL = NULLNULLNULLNULLNULLNULL: "Starting with SQL Server 2017 (14.x), ANSI_NULLS is always set to ON" (SET ANSI_NULLS OFF is deprecated)
'' is NULLNoNoNoYes (VARCHAR2)No
BooleansReal boolean type, prints t/fComparisons "result in a value of 1 (TRUE), 0 (FALSE), or NULL"1 / 0 / NULL (lab Q01)BOOLEAN type in the Oracle Database 23 SQL Reference—
NULLs in UNIQUE columnDistinct (many NULLs allowed); NULLS NOT DISTINCT optionDistinctDistinct (sqlite nulls table)—"only one null value is allowed per column"

Fix / how to use it: test with IS NULL / IS NOT NULL; compare nullable values with IS [NOT] DISTINCT FROM; decide in the schema which columns may be NULL at all (NOT NULL by default is the cheapest fix of all, see Schema Design).

IS NULL, IS DISTINCT FROM and the NULL-safe operators Must-know ​

In plain words: IS NULL asks "is this missing?"; a IS DISTINCT FROM b is "not equal, where two NULLs count as equal and NULL vs a value counts as different". It always returns TRUE or FALSE.

Common misunderstanding: "WHERE col = $1 works when I pass nil from Go." The driver sends NULL and the comparison is UNKNOWN for every row: zero rows, no error (tested in the Go before package).

Definition: PostgreSQL docs: 1 IS DISTINCT FROM NULL → t (rather than NULL) and NULL IS DISTINCT FROM NULL → f (rather than NULL). MySQL's equivalent is the <=> operator: "This operator performs an equality comparison like the = operator, but returns 1 rather than NULL if both operands are NULL, and 0 rather than NULL if one operand is NULL. The <=> operator is equivalent to the standard SQL IS NOT DISTINCT FROM operator." SQLite has IS / IS NOT and, since 3.39.0, the standard spelling: the 3.39.0 release notes add "IS NOT DISTINCT FROM and IS DISTINCT FROM that are equivalent to IS and IS NOT".

sql
-- lab Q03 (sqlite3 output in comments)
SELECT 1 IS DISTINCT FROM NULL,      -- 1
       NULL IS DISTINCT FROM NULL,   -- 0
       NULL IS NOT DISTINCT FROM NULL; -- 1
SELECT id, name FROM customers WHERE country IS DISTINCT FROM 'DE' ORDER BY id;
-- 2 Bob | 4 Dee | 5 Eve      (Dee is back, compare with Q02's "<> 'DE'")
NeedPostgreSQLMySQL 8.4SQLiteSQL standard
Is missingx IS NULLx IS NULLx IS NULL, x ISNULLIS NULL
NULL-safe equalx IS NOT DISTINCT FROM yx <=> yx IS y or IS NOT DISTINCT FROM (3.39+)IS NOT DISTINCT FROM
NULL-safe not equalx IS DISTINCT FROM yNOT (x <=> y)x IS NOT yIS DISTINCT FROM

COALESCE and NULLIF Must-know ​

In plain words: COALESCE(a, b, c) returns the first argument that is not NULL; NULLIF(a, b) returns NULL when a = b, otherwise a. They are the two everyday tools for turning NULL into a default and a sentinel into NULL.

Common misunderstanding: "COALESCE(sum(x), 0) and sum(COALESCE(x, 0)) are the same." The first fixes the empty-group case (no rows → NULL → 0); the second only replaces NULL inputs, and over zero rows still returns NULL.

Definition: both are standard SQL shorthands for CASE. COALESCE evaluates arguments left to right and stops at the first non-NULL one. NULLIF(a, b) is CASE WHEN a = b THEN NULL ELSE a END. The classic use is a divide-by-zero guard: x / NULLIF(y, 0) returns NULL instead of an error (PostgreSQL SQLSTATE 22012 division_by_zero; MySQL: "For SELECT, division by zero returns NULL", while in INSERT/UPDATE the ERROR_FOR_DIVISION_BY_ZERO mode adds a warning, or an error together with strict mode; SQLite returns NULL, lab Q37).

sql
-- lab Q04
SELECT id, coupon_code,
       COALESCE(coupon_code, '(none)') AS shown,
       NULLIF(coupon_code, 'WELCOME')  AS nullif_welcome
FROM orders ORDER BY id;
-- 1 WELCOME WELCOME NULL
-- 2 NULL    (none)  NULL
-- 4 BF26    BF26    BF26   ...
SELECT 100 / NULLIF(0, 0) AS safe_div;   -- NULL
FunctionPostgreSQLMySQLSQLiteSQL ServerOracle
First non-NULLCOALESCECOALESCE, IFNULL(a,b)COALESCE, IFNULL(a,b)COALESCE, ISNULL(a,b)COALESCE, NVL(a,b)
NULL if equalNULLIFNULLIFNULLIFNULLIFNULLIF

How a SELECT is evaluated ​

Written order vs logical evaluation order of one SELECTWritten: SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT …1 FROM / JOINbuild row set2 WHEREkeep TRUE rows3 GROUP BYrows to groups4 HAVINGkeep TRUE groups5 SELECT listexpressions, aliases6 DISTINCTdrop duplicate rows7 UNION / INTERSECT/ EXCEPT blocks8 ORDER BYmay use aliases9 LIMIT / OFFSETor FETCH FIRST n ROWSAn alias made in step 5 does not exist yet in steps 2 to 4:PostgreSQL rejects WHERE doubled > 100 (42703); SQLite accepts it.Aggregates exist only from step 3: WHERE sum(total) > 0 is an error.The planner may reorder physically; results must match this order.

SELECT evaluation order Must-know ​

In plain words: you write SELECT ... FROM ... WHERE ..., but the query means "take FROM, filter with WHERE, group, filter groups, compute the SELECT list, remove duplicates, sort, cut". Remember the logical sequence FROM WHERE GROUP BY HAVING SELECT ORDER BY LIMIT and most error messages explain themselves.

Common misunderstanding: "The database runs the clauses in that order." It runs whatever plan is cheapest (it may push a WHERE into a join, or stop reading after LIMIT rows). The logical order is a contract about the result, not an execution trace. That is why EXPLAIN belongs to Query Planning and the meaning belongs here.

Definition: the PostgreSQL SELECT reference lists the processing steps in this order: WITH queries, FROM (cross-joining several sources), WHERE ("rows that do not satisfy the condition are eliminated"), GROUP BY and aggregates, HAVING, the output expressions, DISTINCT, UNION/INTERSECT/EXCEPT, ORDER BY, then LIMIT/OFFSET/FETCH. Consequences:

text
     What you write                               Why it fails or works
1    WHERE sum(total) > 10                        aggregates do not exist at step 2
                                                  PostgreSQL 42803 grouping_error, MySQL 1111, SQLite "misuse of aggregate function sum()"
2    SELECT total*2 AS doubled ... WHERE doubled  the alias is made at step 5
                                                  PostgreSQL 42703 undefined_column, MySQL 1054; SQLite ACCEPTS it (lab Q05)
3    ... GROUP BY doubled                         PostgreSQL and MySQL accept output names in GROUP BY (extension)
4    ... HAVING doubled > 100                     MySQL accepts select aliases in HAVING (extension); PostgreSQL does not
5    ... ORDER BY doubled                         fine everywhere: ORDER BY runs after SELECT
6    SELECT DISTINCT a ... ORDER BY b             PostgreSQL rejects it (42P10 invalid_column_reference): b is not in the output

The PostgreSQL reference states the alias rule exactly: "An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead." MySQL's sql_mode page documents the HAVING extension: "The HAVING clause can refer to aliases regardless of whether ONLY_FULL_GROUP_BY is enabled."

Real scenario: an engineer prototypes on SQLite (which accepts WHERE doubled > 100), deploys on PostgreSQL and gets 42703 in production; a report filters on HAVING revenue > 100 and fails after a move from MySQL to PostgreSQL; a LIMIT 10 without ORDER BY returns a different "top 10" after VACUUM or a plan change.

ClauseCan use select aliases? PostgreSQLMySQL 8.4SQLiteSQL standard
WHERENo (42703)No (1054)Yes (extension)No
GROUP BYYes (extension)Yes (extension)YesNo (input columns only)
HAVINGNoYes (extension)YesNo
ORDER BYYesYesYesYes

Fix / how to use it: repeat the expression, or wrap the query in a derived table or CTE and filter the outer level: SELECT * FROM (SELECT total*2 AS doubled FROM orders) t WHERE doubled > 100.

DISTINCT and duplicates Important ​

In plain words: DISTINCT removes duplicate output rows, comparing whole rows after the SELECT list is computed. NULLs count as equal to each other here (lab Q06: one NULL country row).

Common misunderstanding: "SELECT DISTINCT fixes a join that returns too many rows." It hides the symptom and costs a sort or hash over the full result. If you need "customers that have at least one order", that is a semi-join (EXISTS), not a join plus DISTINCT.

Definition: SELECT DISTINCT keeps one row from each set of rows that are not distinct from each other. PostgreSQL also has DISTINCT ON (expr), which keeps the first row of each group according to ORDER BY (a PostgreSQL extension; see Advanced SQL for top-N-per-group patterns). count(DISTINCT col) is the aggregate form.

sql
SELECT DISTINCT country FROM customers ORDER BY country;   -- lab Q06
-- NULL / DE / FR / IR   (SQLite sorts NULL first; PostgreSQL would print it last)

Joins ​

What each join keeps: L = customers, R = orders, match = ON condition is TRUEL without matchmatched pairsR without matchINNER JOINL + R columnsLEFT JOINL + NULLsL + R columnsRIGHT JOINL + R columnsNULLs + RFULL OUTERL + NULLsL + R columnsNULLs + RSEMI (EXISTS)L columns, once per LANTI (NOTEXISTS)L columns only8 rows9 (+Eve)no dupesEveCROSS JOIN = every L with every R (Cartesian product, no ON). NATURAL / USING write the ON for you and show each shared column once.Dashed = dropped. A WHERE test on an R column (o.status = 'paid') removes the NULL-padded rows again.

INNER JOIN Must-know ​

In plain words: pair each row of the left table with each row of the right table where the ON condition is TRUE; drop everything else.

Common misunderstanding: "A join returns one row per left row." It returns one row per matching pair: Ann has three orders, so the inner join gives Ann three times (lab Q07). Aggregating after a one-to-many join multiplies sums (the "fan-out" bug).

Definition: A [INNER] JOIN B ON p = the Cartesian product of A and B filtered by p. JOIN alone means INNER JOIN. MySQL: "In MySQL, JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents (they can replace each other). In standard SQL, they are not equivalent." write the keyword that says what you mean.

sql
SELECT c.name, o.id AS order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY o.id;
-- Ann 1 50 | Ann 2 20 | Ann 3 15 | Bob 4 99 | Bob 5 5 | Cy 6 40 | Cy 7 60 | Dee 8 25    (Eve: no row)

Real scenario: summing orders.total after joining order_items (two items → the order total counted twice); a permissions query joining users to roles that returns a user once per role; a "join to the latest price" that returns every historical price.

LEFT JOIN and RIGHT JOIN Must-know ​

In plain words: a LEFT JOIN keeps every left row; where no right row matches, the right columns are filled with NULL. RIGHT JOIN is the mirror image.

Common misunderstanding: "I can filter the right table in WHERE." The WHERE runs after the join; a condition such as o.status = 'paid' is UNKNOWN on the NULL-padded rows and removes them, turning the outer join back into an inner join. Put conditions on the optional side into ON.

Definition: A LEFT [OUTER] JOIN B ON p = the inner join plus, for each row of A with no match, one row with B's columns set to NULL. The ON condition decides matching; the WHERE condition decides survival.

text
     Query (lab Q08)                                                 Ann Bob Cy  Dee Eve
1    LEFT JOIN orders o ON o.customer_id = c.id AND o.status='paid'   2   1   2   0   0     every customer kept
2    LEFT JOIN orders o ON o.customer_id = c.id WHERE o.status='paid' 2   1   2   -   -     Dee and Eve removed by WHERE
3    LEFT JOIN ... WHERE o.id IS NULL                                  -   -   -   -   Eve  the anti-join idiom

Real scenario: a "customers and their paid order count" admin page that loses every new customer; an "employees and their manager" list that drops the CEO; a product catalogue joined to stock that hides products with no stock row.

ProductLEFT JOINRIGHT JOINNotes
PostgreSQLYesYes
MySQL 8.4YesYesManual: "To keep code portable across databases, it is recommended that you use LEFT JOIN instead of RIGHT JOIN."
SQLiteYesSince 3.39.0 (2022-06-25)Release notes: "Add (long overdue) support for RIGHT and FULL OUTER JOIN"
SQL ServerYesYesFROM reference lists LEFT, RIGHT and FULL [OUTER] JOIN

FULL OUTER JOIN Important ​

In plain words: keep unmatched rows from both sides: matched pairs, left-only rows padded with NULL and right-only rows padded with NULL.

Common misunderstanding: "Every engine has it." MySQL 8.4's join grammar lists INNER, CROSS, STRAIGHT_JOIN, LEFT/RIGHT [OUTER] and NATURAL joins, and no FULL OUTER JOIN. Emulate it with LEFT JOIN ... UNION ALL ... RIGHT JOIN ... WHERE left.key IS NULL.

Definition: A FULL [OUTER] JOIN B ON p = A LEFT JOIN B ON p plus the rows of B with no match, padded with NULL on the A side. Typical use: reconciliation (orders vs payments, two price lists, yesterday's vs today's snapshot).

sql
-- lab Q09: coupons table with WELCOME, BF26 and the unused SPRING
SELECT o.id AS order_id, o.coupon_code, k.code
FROM orders o FULL OUTER JOIN coupons k ON k.code = o.coupon_code
WHERE o.id IS NULL OR o.id IN (1,2,4)
ORDER BY o.id, k.code;
-- NULL NULL    SPRING    <- coupon nobody used
-- 1    WELCOME WELCOME
-- 2    NULL    NULL      <- order without coupon
-- 4    BF26    BF26
sql
-- MySQL 8.4 emulation (expected, not run)
SELECT o.id, k.code FROM orders o LEFT JOIN coupons k ON k.code = o.coupon_code
UNION ALL
SELECT o.id, k.code FROM orders o RIGHT JOIN coupons k ON k.code = o.coupon_code
WHERE o.id IS NULL;

CROSS JOIN and the Cartesian product Important ​

In plain words: every row of the left table paired with every row of the right table; 5 customers and 3 coupons give 15 rows (lab Q10).

Common misunderstanding: "A Cartesian product is always a bug." It is the right tool for generating combinations: every store × every day for a calendar report, every product × every size. The bug is the accidental one: FROM a, b with a forgotten condition, which turns two 10 000-row tables into 100 million rows.

Definition: A CROSS JOIN B = A JOIN B ON TRUE = FROM A, B. The comma form mixes badly with explicit joins: the PostgreSQL docs note that "JOIN binds more tightly than comma", so FROM a, b JOIN c ON c.x = a.x cannot see a in the ON clause.

NATURAL JOIN and USING Important ​

In plain words: JOIN ... USING (country) is shorthand for "join on equal country columns and show the column once". NATURAL JOIN does the same for every column name the two tables share.

Common misunderstanding: "NATURAL JOIN is a convenient default." The PostgreSQL docs warn: "NATURAL is considerably more risky since any schema changes to either relation that cause a new matching column name to be present will cause the join to combine that new column as well." Add a created_at column to both tables and the join silently starts comparing timestamps. "If there are no common column names, NATURAL JOIN behaves like CROSS JOIN."

Definition: USING (a, b) = ON l.a = r.a AND l.b = r.b, with a single coalesced output column per listed name (MySQL: "The USING join selects the coalesced value of corresponding columns, whereas the ON join selects all columns from all tables"). Lab Q11 returns the same four rows for both forms; Dee (NULL country) is missing from both, because NULL = NULL is not TRUE in a join either.

FormJoin conditionOutput columnsSafe after schema changes?
ON l.x = r.xExplicitBoth l.x and r.xYes
USING (x)Equality on the named columnsOne xYes
NATURAL JOINEquality on every shared nameOne per shared nameNo

Self join Important ​

In plain words: a table joined to itself under two aliases, to relate rows of the same table: who referred whom, employee and manager, a flight and its connecting flight.

Common misunderstanding: "A self join needs a special syntax." It is an ordinary join; the aliases are what make the two roles readable. Use a LEFT JOIN when the relationship is optional, or the root rows vanish.

sql
SELECT c.name AS customer, r.name AS referred_by
FROM customers c LEFT JOIN customers r ON r.id = c.referred_by
ORDER BY c.id;                                  -- lab Q12
-- Ann NULL | Bob Ann | Cy Bob | Dee Ann | Eve NULL

For a chain of unknown depth (Cy → Bob → Ann) a self join is not enough; use a recursive CTE.

Subqueries, semi-joins and anti-joins ​

Semi-join with EXISTS and IN Must-know ​

In plain words: "give me each customer who has at least one paid order", once per customer, with only the customer's columns. That is a semi-join, and EXISTS or IN is how SQL spells it.

Common misunderstanding: "JOIN then DISTINCT is the same thing." It returns the same names here, but builds every matching pair first (lab Q13: the join returns Ann and Cy twice), and DISTINCT also collapses legitimate duplicates such as two customers called "Ann".

Definition: EXISTS (subquery) is TRUE if the subquery returns at least one row; its select list is irrelevant (SELECT 1 is the convention). x IN (subquery) is TRUE if some row equals x. The PostgreSQL subquery-expressions chapter defines EXISTS, IN, NOT IN, ANY/SOME and ALL. Planners turn both into a semi-join operator (MySQL calls this the semijoin strategy family; PostgreSQL shows Semi Join nodes); see Query Planning.

sql
SELECT c.name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o
              WHERE o.customer_id = c.id AND o.status = 'paid')
ORDER BY c.id;                                  -- lab Q13: Ann, Bob, Cy

Anti-join with NOT EXISTS, and NOT IN with NULL Must-know ​

In plain words: an anti-join keeps the rows that have no match: customers without orders, products never sold, users who referred nobody. Write it with NOT EXISTS (or LEFT JOIN ... WHERE right.key IS NULL). Never with NOT IN over a column that can be NULL.

Common misunderstanding: "NOT IN (subquery) is the readable form of NOT EXISTS." They differ exactly when the subquery returns a NULL: x NOT IN (1, NULL) expands to x <> 1 AND x <> NULL, which is at best UNKNOWN, so no row qualifies. The PostgreSQL docs: "if there are no equal right-hand values and at least one right-hand row yields null, the result of the NOT IN construct will be null, not true." MySQL: "To comply with the SQL standard, IN() returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL."

Definition: NOT EXISTS (correlated subquery) is TRUE when the subquery returns no row; it is two-valued, so NULLs in the inner table cannot poison it.

text
     "Customers who referred nobody" (lab Q15); referred_by = {NULL, 1, 2, 1, NULL}
1    WHERE id NOT IN (SELECT referred_by FROM customers)                        -> (no rows)
2    WHERE NOT EXISTS (SELECT 1 FROM customers x WHERE x.referred_by = c.id)    -> Cy, Dee, Eve
3    WHERE id NOT IN (SELECT referred_by FROM customers WHERE referred_by IS NOT NULL) -> Cy, Dee, Eve
4    SELECT 3 IN (1, NULL), 3 NOT IN (1, NULL), 1 IN (1, NULL)                  -> NULL, NULL, 1

Real scenario: a nightly "inactive users" job that has been sending zero emails since someone made last_login_device_id nullable; a "products never ordered" report that is empty after one order line without a product; a cleanup DELETE ... WHERE id NOT IN (SELECT parent_id ...) that deletes nothing (lucky) or, inverted as IN, too much.

FormNULL-safeTypical planUse
NOT EXISTS (correlated)YesAnti join (PostgreSQL), antijoin (MySQL 8.0.17+)Default choice
LEFT JOIN ... WHERE r.key IS NULLYes (test a NOT NULL column of r)Anti join or outer join + filterWhen you also need columns of r elsewhere
NOT IN (subquery)NoMySQL 8.0.17+: antijoin, but "cannot in most cases be applied if the expressions being compared are nullable"Only over NOT NULL columns
EXCEPTYes (NULLs compare equal)Set operationComparing whole column lists

Scalar and correlated subqueries Must-know ​

In plain words: a scalar subquery is a subquery in parentheses that returns one value, used where a value is expected. A correlated subquery refers to a column of the outer query, so logically it runs once per outer row.

Common misunderstanding: "A scalar subquery that returns two rows just takes the first." PostgreSQL raises SQLSTATE 21000 (cardinality_violation), MySQL raises error 1242 ER_SUBQUERY_NO_1_ROW ("Subquery returns more than 1 row"). SQLite really does take the first row silently (lab Q36), which hides the bug until you migrate.

Definition: a scalar subquery that returns no row yields NULL. "Correlated" says nothing about speed by itself; planners often decorrelate it into a join or semi-join. It is slow when it cannot be decorrelated and the outer side is large.

sql
-- lab Q16: last order per customer (NULL for Eve), and orders above the customer's own average
SELECT c.name,
       (SELECT max(o.created_at) FROM orders o WHERE o.customer_id = c.id) AS last_order
FROM customers c ORDER BY c.id;
SELECT o.id, o.customer_id, o.total FROM orders o
WHERE o.total > (SELECT avg(o2.total) FROM orders o2 WHERE o2.customer_id = o.customer_id)
ORDER BY o.id;                                   -- 1 (50), 4 (99), 7 (60)

Derived tables Important ​

In plain words: a subquery in FROM acts like a temporary table for the outer query. It is how you filter on an aggregate or an alias at the next level.

Common misunderstanding: "A derived table is always computed in full first." PostgreSQL and MySQL usually merge it into the outer query (MySQL's optimizer chapter is titled "Optimizing Derived Tables, View References, and Common Table Expressions with Merging or Materialization"). Write for clarity; the planner decides.

Definition: FROM (SELECT ...) AS alias. The SQL standard requires an alias; PostgreSQL docs: "In PostgreSQL, this alias may be omitted" (SQLite also accepts none); MySQL requires it (error 1248 ER_DERIVED_MUST_HAVE_ALIAS, "Every derived table must have its own alias").

sql
SELECT t.customer_id, t.revenue
FROM (SELECT customer_id, sum(total) AS revenue
      FROM orders WHERE status = 'paid' GROUP BY customer_id) AS t
WHERE t.revenue > 60 ORDER BY t.customer_id;    -- lab Q17: 1 70 | 2 99 | 3 100

LATERAL Important ​

In plain words: a normal derived table cannot see the other tables in the same FROM; a LATERAL one can, so it can run "per outer row": the latest three orders of this customer.

Common misunderstanding: "LATERAL is a PostgreSQL oddity." It is standard SQL; PostgreSQL, MySQL (8.0.14+, per the Laravel docs: "Lateral joins are currently supported by PostgreSQL, MySQL >= 8.0.14, and SQL Server") and SQL Server (CROSS APPLY / OUTER APPLY) have it. SQLite does not (lab Q34: near "SELECT": syntax error).

Definition: PostgreSQL: "Subqueries appearing in FROM can be preceded by the key word LATERAL. This allows them to reference columns provided by preceding FROM items." MySQL: "A derived table cannot normally refer to (depend on) columns of preceding tables in the same FROM clause. A derived table may be defined as a lateral derived table to specify that such references are permitted."

sql
-- PostgreSQL / MySQL 8.0.14+ (expected, not run): biggest order per customer
SELECT c.name, l.id, l.total
FROM customers c
LEFT JOIN LATERAL (
  SELECT o.id, o.total FROM orders o
  WHERE o.customer_id = c.id
  ORDER BY o.total DESC LIMIT 1
) AS l ON true
ORDER BY c.id;

The SQLite-compatible equivalent is a correlated subquery inside the join condition (lab Q35). Top-N per group with window functions and deeper LATERAL patterns are in Advanced SQL.

Aggregation: GROUP BY and HAVING ​

Aggregate functions: COUNT(*) vs COUNT(col), SUM AVG MIN MAX Must-know ​

In plain words: aggregate functions fold many rows into one value. count(*) counts rows; count(col) counts rows where col is not NULL; count(DISTINCT col) counts different non-NULL values. sum, avg, min and max ignore NULL inputs.

Common misunderstanding: "sum of nothing is 0." The PostgreSQL docs: "except for count, these functions return a null value when no rows are selected. In particular, sum of no rows returns null, not zero as one might expect". MySQL: "Aggregate (group) functions such as COUNT(), MIN(), and SUM() ignore NULL values. The exception to this is COUNT(*), which counts rows and not individual column values."

Definition and lab output (Q18):

sql
SELECT count(*), count(coupon_code), count(DISTINCT coupon_code),
       sum(total), avg(total), min(total), max(total)
FROM orders;
-- 8 | 3 | 2 | 314 | 39.25 | 5 | 99
SELECT count(*), sum(total), avg(total), max(total) FROM orders WHERE status = 'nope';
-- 0 | NULL | NULL | NULL        <- an aggregate without GROUP BY always returns exactly one row
AggregateOver NULL inputsOver zero rowsResult type notes
count(*)Counts the row0bigint in PostgreSQL
count(col)Skips0
count(DISTINCT col)Skips0Sort or hash per group
sum(col)SkipsNULLPostgreSQL: sum(int) → bigint, sum(bigint) → numeric
SQLite total(col)Skips0.0 ("sum() returns NULL but total() returns 0.0")Always a floating-point value
avg(col)Skips (divides by non-NULL count)NULLPostgreSQL avg(int) → numeric; SQLite returns a float
min / maxSkipsNULLWork on text and dates too
string_agg / group_concatSkipsNULLPostgreSQL string_agg, MySQL GROUP_CONCAT, SQLite group_concat / string_agg
bool_and / every, bool_orSkipsNULLPostgreSQL only

Real scenario: "average order value" computed with avg(discount) where most rows are NULL (it averages only discounted orders); "orders with a coupon" off by the NULL rows; a KPI tile that shows blank instead of 0 on the first day of a month.

GROUP BY and HAVING Must-know ​

In plain words: GROUP BY folds rows that share the grouping values into one output row; HAVING filters those groups, the way WHERE filters rows.

Common misunderstanding: "HAVING is just a WHERE that runs later." Conditions that do not use an aggregate belong in WHERE, where they reduce the rows before grouping. The PostgreSQL tutorial: "WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed."

sql
SELECT customer_id, count(*) AS paid_orders, sum(total) AS revenue
FROM orders
WHERE status = 'paid'          -- rows
GROUP BY customer_id
HAVING sum(total) >= 70        -- groups
ORDER BY revenue DESC;         -- lab Q19: 3 2 100 | 2 1 99 | 1 2 70
text
     Step (lab Q19)          Rows / groups
1    FROM orders             8 rows
2    WHERE status='paid'     5 rows: 1,2,4,6,7
3    GROUP BY customer_id    3 groups: {1: 50+20}, {2: 99}, {3: 40+60}
4    HAVING sum >= 70        3 groups kept (70, 99, 100)
5    SELECT, ORDER BY        3 rows, revenue descending

GROUP BY puts all NULLs in one group (lab Q20: one row for country NULL). MySQL: "When using DISTINCT, GROUP BY, or ORDER BY, all NULL values are regarded as equal."

GROUP BY with non-aggregated columns, ONLY_FULL_GROUP_BY and functional dependence Must-know ​

In plain words: after grouping by customer_id, a column like status has several values per group. Which one should the query show? The standard says: none, unless the column is grouped, aggregated, or determined by the grouped columns.

Common misunderstanding: "MySQL lets me select any column with GROUP BY." That was the old default. ONLY_FULL_GROUP_BY is now on "(which it is by default)", and "The default SQL mode in MySQL 8.4 includes these modes: ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, and NO_ENGINE_SUBSTITUTION." SQLite still accepts "bare columns" and picks a value from an arbitrary row of the group (lab Q21 shows status = paid for customer 1, whose group also holds a refunded order).

Definition: a non-aggregated column in the select list, HAVING or ORDER BY must be in the GROUP BY or be functionally dependent on it. PostgreSQL: "A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column." MySQL: "If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them"; MySQL also detects dependence through equalities in WHERE and unique NOT NULL keys, and offers ANY_VALUE(col) when you accept an arbitrary value.

text
     Query                                                          PostgreSQL 18      MySQL 8.4 (default mode)        SQLite
1    SELECT customer_id, status, sum(total) GROUP BY customer_id    42803 grouping_error  1055 ER_WRONG_FIELD_WITH_GROUP  arbitrary status (Q21)
2    SELECT c.id, c.name, count(o.id) ... GROUP BY c.id              OK: name depends on PK  OK: functional dependence    OK
3    SELECT customer_id, ANY_VALUE(status) ... GROUP BY customer_id  PostgreSQL 18 has any_value()  OK  no such function
4    SELECT customer_id, id, max(total) GROUP BY customer_id         42803             1055                            id of the max row (documented)

SQLite documents row 4: "If there is exactly one min() or max() aggregate in the query, then all bare columns in the result set take values from an input row which also contains the minimum or maximum." Lab Q21 returns order 1, 4, 7, 8, the biggest order of each customer. It is convenient and non-portable; the portable form is a window function or DISTINCT ON (see Advanced SQL).

Real scenario: a legacy PHP app that relied on MySQL 5.6 bare columns breaks on upgrade with error 1055; a "latest status per order" report that showed a random status for years; the fix GROUP BY c.id (primary key) that lets you select every customers column without listing them.

Set operations ​

UNION, UNION ALL, INTERSECT, EXCEPT Must-know ​

In plain words: set operations stack the results of two queries with the same number of columns. UNION = rows in either (duplicates removed), UNION ALL = all rows (duplicates kept), INTERSECT = rows in both, EXCEPT = rows in the first but not the second.

Common misunderstanding: "UNION is the normal one." UNION removes duplicates "in the same way as DISTINCT, unless UNION ALL is used" (PostgreSQL docs), which costs a sort or hash and silently merges legitimate duplicates. Use UNION ALL unless you need deduplication.

Definition: columns are matched by position, names come from the first query, types are unified. INTERSECT binds tighter than UNION and EXCEPT (MySQL: "You should be aware that INTERSECT is evaluated before UNION or EXCEPT."; PostgreSQL: "INTERSECT binds more tightly than UNION"). SQLite and Oracle differ: SQLite groups compound selects left to right ("(A op B op C) is processed as ((A op B) op C)"), and Oracle says "All set operators have equal precedence". So SELECT 1 UNION SELECT 2 INTERSECT SELECT 2 returns 1 and 2 on PostgreSQL and MySQL but only 2 on SQLite (lab Q38); add parentheses (not accepted by SQLite) or split into CTEs when you mix operators. Set operations treat NULLs as equal (lab Q22: SELECT NULL UNION SELECT NULL returns one row). ORDER BY and LIMIT apply to the whole result; in PostgreSQL that ORDER BY "can only specify an output column name or number, not an expression".

sql
SELECT customer_id FROM orders WHERE status = 'paid'
INTERSECT
SELECT customer_id FROM orders WHERE status = 'pending'
ORDER BY 1;                                       -- lab Q22: 2 (Bob)
SELECT id FROM customers
EXCEPT
SELECT customer_id FROM orders WHERE status = 'paid'
ORDER BY 1;                                       -- 4 (Dee), 5 (Eve)
OperationPostgreSQLMySQL 8.4SQLiteOracleSQL Server
UNION / UNION ALLYesYesYesYesYes
INTERSECTYes, plus INTERSECT ALLYes: "INTERSECT was added in MySQL 8.0.31."Yes (no ALL)Yes, plus INTERSECT ALL—
EXCEPTYes, plus EXCEPT ALLYes: "EXCEPT was added in MySQL 8.0.31."Yes (no ALL)EXCEPT, EXCEPT ALL, MINUS, MINUS ALL (23 reference)—
Parentheses around blocksYesYesNo (lab Q37: near "(": syntax error)Yes—
PrecedenceINTERSECT firstINTERSECT firstLeft to right: "(A op B op C) is processed as ((A op B) op C)"All equal, left to right—

Common table expressions ​

WITH and the MATERIALIZED hint Must-know ​

In plain words: a CTE (WITH name AS (...)) gives a subquery a name at the top of the statement, so the main query reads like a pipeline of named steps.

Common misunderstanding: "A CTE is always computed once and stored" (or the opposite, "a CTE is just a macro"). Before PostgreSQL 12, CTEs "were never inlined and were always evaluated before the rest of the query" (12.0 release notes); since 12 a non-recursive, side-effect-free CTE can be folded into the main query. The PostgreSQL docs: "By default, this happens if the parent query references the WITH query just once, but not if it references the WITH query more than once. You can override that decision by specifying MATERIALIZED to force separate calculation of the WITH query, or by specifying NOT MATERIALIZED to force it to be merged into the parent query." Two limits: PostgreSQL's SELECT reference says "NOT MATERIALIZED is ignored if it is attached to a WITH query that is recursive or is not side-effect-free", and SQLite says "In spite of its name, the NOT MATERIALIZED phrase does not prohibit the use of materialization".

Definition: MySQL: "A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times." MySQL 8.0+ supports CTEs but not the MATERIALIZED keyword (it chooses merge or materialization itself). SQLite accepts AS MATERIALIZED / AS NOT MATERIALIZED since 3.35.0.

sql
WITH paid AS MATERIALIZED (
  SELECT customer_id, sum(total) AS revenue
  FROM orders WHERE status = 'paid' GROUP BY customer_id
)
SELECT c.name, p.revenue FROM paid p JOIN customers c ON c.id = p.customer_id
ORDER BY p.revenue DESC;                          -- lab Q23: Cy 100 | Bob 99 | Ann 70

PostgreSQL also allows data-modifying statements in WITH (WITH moved AS (DELETE ... RETURNING *) INSERT INTO archive SELECT * FROM moved); MySQL and SQLite do not.

Recursive CTE Important ​

WITH RECURSIVE chain: anchor once, then repeat until an iteration returns no rowsanchor memberWHERE referred_by IS NULLworking tablerows from last steprecursive membercustomers JOIN chain ON …new rows replace itIterations on the lab data (referred_by)depth 0: Ann, Evedepth 1: Bob, Deedepth 2: Cydepth 3: no rows, stopResult = UNION ALL of every iteration (5 rows). UNION instead of UNION ALL discards duplicate rows and stops cyclesonly when whole rows repeat. Guards: a depth counter or a visited-path column, the PostgreSQL CYCLE clause,MySQL cte_max_recursion_depth. SQLite stops only when an iteration is empty (or at a LIMIT).

In plain words: WITH RECURSIVE runs an anchor query once, then repeatedly runs a second query against the rows produced by the previous step, until a step produces nothing. It walks trees and graphs (referral chains, category trees, org charts, bills of materials) and generates series.

Common misunderstanding: "Recursion stops by itself." It stops only when an iteration returns no rows. A cycle in the data (A referred B, B referred A) loops forever with UNION ALL. Guards: a depth limit in the recursive member, a visited-path column, PostgreSQL's CYCLE ... SET is_cycle USING path clause, MySQL's cte_max_recursion_depth ("The server terminates execution of any CTE that recurses more levels than the value of this variable").

Definition: WITH RECURSIVE name(cols) AS (anchor UNION [ALL] recursive_member). MySQL: "The WITH clause must begin with WITH RECURSIVE if any CTE in the WITH clause refers to itself." PostgreSQL requires it the same way; SQLite does not: "for compatibility with SqlServer and Oracle, SQLite does not enforce this rule" (lab Q37 runs a recursive CTE without the keyword). SQL Server and Oracle omit the keyword.

sql
WITH RECURSIVE chain(id, name, depth, path) AS (
  SELECT id, name, 0, name FROM customers WHERE referred_by IS NULL
  UNION ALL
  SELECT c.id, c.name, chain.depth + 1, chain.path || ' > ' || c.name
  FROM customers c JOIN chain ON c.referred_by = chain.id
)
SELECT id, name, depth, path FROM chain ORDER BY path;   -- lab Q24
-- 1 Ann 0 Ann | 2 Bob 1 Ann > Bob | 3 Cy 2 Ann > Bob > Cy | 4 Dee 1 Ann > Dee | 5 Eve 0 Eve
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 5)
SELECT group_concat(i, ',') FROM n;                      -- 1,2,3,4,5

SEARCH DEPTH FIRST / BREADTH FIRST, cycle detection and graph traversal at depth are in Advanced SQL.

Sorting and limiting ​

ORDER BY NULLS FIRST LAST Must-know ​

In plain words: ORDER BY is the only thing that gives a result an order. Where NULLs land differs by engine, so say it explicitly with NULLS FIRST or NULLS LAST.

Common misunderstanding: "NULLs always sort first (or last)." PostgreSQL: "By default, null values sort as if larger than any non-null value; that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise." SQLite: "SQLite considers NULL values to be smaller than any other values for sorting purposes." MySQL: "When using ORDER BY, NULL values are presented first, or last if you specify DESC to sort in descending order." Same query, different first page.

EngineASC defaultDESC defaultNULLS FIRST / NULLS LAST syntax
PostgreSQLNULLs lastNULLs firstYes
MySQL 8.4NULLs firstNULLs lastNo: use ORDER BY col IS NULL, col
SQLiteNULLs firstNULLs lastYes, since 3.30.0
OracleNULLs lastNULLs firstYes ("NULLS LAST is the default for ascending order")
SQL ServerNULLs first ("NULL values are treated as the lowest possible values")NULLs lastNo (not in the ORDER BY syntax)
sql
SELECT id, country FROM customers ORDER BY country NULLS LAST, id;      -- lab Q25: 1 DE, 3 DE, 2 FR, 5 IR, 4 NULL
SELECT id, country FROM customers ORDER BY country DESC NULLS FIRST, id; -- 4 NULL, 5 IR, 2 FR, 1 DE, 3 DE
-- MySQL spelling of NULLS LAST (expected, not run):
SELECT id, country FROM customers ORDER BY country IS NULL, country, id;

Always end an ORDER BY with a unique column (id) when the result feeds pagination: the order of tied rows "is undefined" (SQLite docs) and can change between executions.

LIMIT OFFSET and FETCH FIRST Must-know ​

In plain words: LIMIT n OFFSET m skips m rows of the sorted result and returns the next n. FETCH FIRST n ROWS ONLY is the SQL standard spelling of the same thing.

Common misunderstanding: "OFFSET 100000 jumps straight to the page." The PostgreSQL docs: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." And without ORDER BY, "you will get an unpredictable subset of the query's rows". Keyset pagination is the fix, taught in Pagination.

Definition: PostgreSQL: "The clauses LIMIT and OFFSET are PostgreSQL-specific syntax, also used by MySQL. The SQL:2008 standard has introduced the clauses OFFSET ... FETCH {FIRST|NEXT} ... for the same functionality". FETCH FIRST n ROWS WITH TIES (PostgreSQL syntax: { ONLY | WITH TIES }) also returns rows tied with the last one; SQL Server writes TOP (n) WITH TIES.

EngineLIMIT n OFFSET mOFFSET m ROWS FETCH FIRST n ROWS ONLYOther
PostgreSQLYesYes (WITH TIES too)
MySQL 8.4Yes, also LIMIT m, nNo
SQLiteYes, also LIMIT m, nNo (lab Q26: near "FETCH": syntax error)
SQL ServerNoYes, as part of ORDER BYTOP (n) [WITH TIES]
OracleNoYes (row_limiting_clause)
sql
SELECT id, total FROM orders ORDER BY total DESC, id LIMIT 3 OFFSET 2;   -- lab Q26: 1 50 | 6 40 | 8 25
-- standard form (PostgreSQL, expected, not run):
SELECT id, total FROM orders ORDER BY total DESC, id OFFSET 2 ROWS FETCH FIRST 3 ROWS ONLY;

Expressions and types ​

CASE Must-know ​

In plain words: CASE is SQL's if/else expression: it returns the value of the first WHEN branch whose condition is TRUE, else the ELSE value (NULL if there is no ELSE).

Common misunderstanding: "CASE col WHEN NULL THEN ... catches NULLs." The simple form compares with =, and col = NULL is never TRUE. Use the searched form CASE WHEN col IS NULL THEN ....

sql
SELECT id, total,
       CASE WHEN total >= 50 THEN 'large' WHEN total >= 20 THEN 'medium' ELSE 'small' END AS size,
       CASE status WHEN 'paid' THEN 1 ELSE 0 END AS is_paid
FROM orders ORDER BY id;                                 -- lab Q27
SELECT sum(CASE WHEN status = 'paid' THEN total ELSE 0 END)     AS paid,
       sum(CASE WHEN status = 'refunded' THEN total ELSE 0 END) AS refunded
FROM orders;                                             -- 269 | 15   (conditional aggregation, a pivot)

Conditional aggregation is the portable pivot; PostgreSQL's sum(total) FILTER (WHERE status = 'paid') is the standard shorthand (see Advanced SQL). MySQL also has IF(expr1,expr2,expr3), SQLite has iif(), and SQL Server has IIF(), which "Returns one of two values, depending on whether the Boolean expression evaluates to true or false".

String and date functions Important ​

In plain words: every engine has the basics (upper/lower, length, substring, replace, concatenation, current date, date arithmetic, formatting), but the names and the date model differ more than anything else in SQL.

Common misunderstanding: "|| concatenates strings everywhere." In PostgreSQL and SQLite it does; in MySQL || is logical OR unless PIPES_AS_CONCAT is set ("Treat || as a string concatenation operator (same as CONCAT()) rather than as a synonym for OR"). Use concat() when portability matters; it exists in PostgreSQL, MySQL and SQLite 3.44+.

TaskPostgreSQL 18MySQL 8.4SQLite 3.54
Concatenatea || b, concat(a, b) (ignores NULL)CONCAT(a, b) (NULL if any NULL), CONCAT_WSa || b, concat()
Length in characterslength(s), char_length(s)CHAR_LENGTH(s) (LENGTH is bytes)length(s) (characters for text)
Substringsubstr(s, 1, 3), substring(s from 1 for 3)SUBSTRING(s, 1, 3)substr(s, 1, 3)
Positionstrpos(s, '@'), position('@' in s)LOCATE('@', s), INSTR(s, '@')instr(s, '@')
Case-insensitive matchILIKE, lower(a) = lower(b)LIKE is case-insensitive with the default _ci collationsLIKE is case-insensitive for ASCII
Today / nowcurrent_date, now() (transaction start)CURDATE(), NOW()date('now'), datetime('now') (UTC)
Add a monthd + interval '1 month'DATE_ADD(d, INTERVAL 1 MONTH)date(d, '+1 month')
Truncate to monthdate_trunc('month', ts)DATE_FORMAT(ts, '%Y-%m-01')strftime('%Y-%m-01', ts)
Formatto_char(ts, 'YYYY-MM')DATE_FORMAT(ts, '%Y-%m')strftime('%Y-%m', ts)
Difference in daysd2 - d1 (integer for date)DATEDIFF(d2, d1)julianday(d2) - julianday(d1)
sql
-- lab Q28 (SQLite names)
SELECT upper(name), length(email), substr(email, 1, instr(email, '@') - 1) AS local_part,
       name || ' <' || email || '>' AS display
FROM customers WHERE id <= 2 ORDER BY id;               -- ANN 8 ann Ann <ann@x.io> ...
SELECT date('2026-11-29', '+1 month');                   -- 2026-12-29

SQLite has no date type: dates are TEXT (ISO 8601), REAL (Julian day) or INTEGER (Unix time) and the date functions interpret them. Store UTC; time zones are covered in Schema Design.

Implicit casts and type affinity Important ​

In plain words: when you compare or combine values of different types, the engine may convert one of them. PostgreSQL converts rarely and errors otherwise; MySQL converts eagerly; SQLite converts according to a column's "affinity".

Common misunderstanding: "WHERE phone = 1234 is the same as WHERE phone = '1234'." In MySQL, comparing a string column with a number converts each string to a number, so '1234abc', ' 1234' and '01234' all match, and an index on the string column cannot be used for that comparison. The MySQL manual's type-conversion page describes how strings are compared as floating-point numbers in that case.

Definition and lab output (Q29):

text
     Expression                         SQLite 3.54            PostgreSQL 18                 MySQL 8.4
1    '10' = 10   (two literals)         0 (no affinity)        true ('10' is "unknown" type, resolved to int)  1
2    int_col = '10'                     1 (affinity converts)  true                          1
3    7 / 2                              3                      3 ("division truncates")       decimal result (manual: SELECT 3/5 -> 0.60); DIV is integer
4    '42abc' to a number                CAST AS INTEGER: 42    cast: error 22P02 (expected)  numeric context: '1a' converts to 1 (manual)
5    '9' < '10'                         0 (text comparison)    false (text comparison)       0

PostgreSQL's rule for untyped literals (an untyped '10' takes the type of the other operand) is in its type-conversion overview; SQLite's affinity rules are in "Datatypes In SQLite", and its quirks page calls flexible typing "a feature of SQLite, not a bug". The safe habit everywhere: compare columns with values of the column's own type, and bind parameters with the right Go/PHP type.

Identifier quoting and case sensitivity Important ​

In plain words: identifiers (table and column names) are quoted with double quotes in standard SQL and with backticks in MySQL. Whether Orders and orders are the same name, and whether 'Ann' = 'ann', depends on the engine and on collations.

Common misunderstanding: "PostgreSQL is case-insensitive like MySQL." PostgreSQL folds unquoted names to lower case and makes quoted names exact: "the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other". It also notes this folding "is incompatible with the SQL standard, which says that unquoted names should be folded to upper case."

QuestionPostgreSQLMySQL 8.4SQLite
Identifier quote"Order"`Order`, or "Order" with ANSI_QUOTES"Order" (also ` and [ ])
String quote'text' only'text', "text" (without ANSI_QUOTES)'text'; "text" falls back to a string if no column matches (lab Q30)
Unquoted name caseFolded to lowerColumns never case-sensitive; table names depend on lower_case_table_names (Unix 0, Windows 1, macOS 2)Case-insensitive (lab Q30: "order notes" finds "Order Notes")
Quoted name caseExactSame rules as unquotedCase-insensitive
'Ann' = 'ann'false (deterministic collations)true with the default utf8mb4_0900_ai_ci collationfalse (BINARY); true with COLLATE NOCASE

The last row is a collation question, not a syntax one: Indexing covers what a collation does to indexes. Rule: name everything in snake_case without quotes, and never use reserved words (order, user, group) as names.

Changing data with queries ​

INSERT RETURNING, UPDATE FROM, DELETE USING Important ​

In plain words: data-changing statements can join to other tables and return the rows they changed, so the application does not need a second round trip.

Common misunderstanding: "RETURNING is standard everywhere." PostgreSQL, SQLite (3.35.0+, "The RETURNING syntax has been supported by SQLite since version 3.35.0") and MariaDB ("INSERT ... RETURNING returns a resultset of the inserted rows") have it; MySQL 8.4's INSERT syntax has no RETURNING clause, so applications read LAST_INSERT_ID() instead. SQL Server uses OUTPUT.

Definition:

  • INSERT ... RETURNING (PostgreSQL): "causes INSERT to compute and return value(s) based on each row actually inserted (or updated, if an ON CONFLICT DO UPDATE clause was used)". PostgreSQL 18 adds RETURNING OLD.* / NEW.* (the WITH ( { OLD | NEW } AS output_alias ...) syntax in its INSERT reference).
  • UPDATE ... FROM: PostgreSQL and SQLite ("UPDATE-FROM is supported beginning in SQLite version 3.33.0") join the target to other tables in a FROM clause. MySQL writes a multi-table UPDATE a JOIN b ON ... SET ...; "For multiple-table syntax, ORDER BY and LIMIT cannot be used."
  • DELETE ... USING: PostgreSQL DELETE FROM orders USING customers WHERE ...; MySQL has DELETE t1 FROM t1 JOIN t2 ... and DELETE FROM t1 USING t1 JOIN t2 ...; SQLite has neither (lab Q33: near "USING": syntax error) and uses a subquery.
sql
-- lab Q31-Q33 (sqlite3)
INSERT INTO orders (id, tenant_id, customer_id, status, total, coupon_code, created_at)
VALUES (9, 1, 5, 'pending', 12.50, NULL, '2026-11-29 09:00:00')
RETURNING id, customer_id, status;                -- 9 | 5 | pending
UPDATE orders SET total = s.sum_items
FROM (SELECT order_id, sum(qty * price) AS sum_items FROM order_items GROUP BY order_id) AS s
WHERE s.order_id = orders.id AND orders.total <> s.sum_items
RETURNING orders.id, orders.total;                -- 2 | 24   (order 2 had items worth 2 x 12)
DELETE FROM orders WHERE status = 'pending'
  AND NOT EXISTS (SELECT 1 FROM order_items i WHERE i.order_id = orders.id)
RETURNING id;                                     -- 5, 9
sql
-- PostgreSQL (expected, not run)
DELETE FROM orders o USING customers c
WHERE c.id = o.customer_id AND c.country IS NULL
RETURNING o.id;
-- MySQL 8.4 (expected, not run)
UPDATE orders o JOIN customers c ON c.id = o.customer_id
SET o.tenant_id = 3 WHERE c.country = 'IR';
DELETE o FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.country IS NULL;

Upsert (ON CONFLICT, ON DUPLICATE KEY UPDATE, MERGE) is in Advanced SQL; transaction boundaries around these statements are in ACID & Transactions.

Dialect differences ​

PostgreSQL vs MySQL differences Must-know ​

In plain words: both speak "SQL", but the same text can mean different things: string comparison, ||, GROUP BY permissiveness, NULL sort order, division, quoting.

Common misunderstanding: "If it parses on both, it means the same on both." SELECT 7/2, 'Ann' = 'ann', ORDER BY nullable_col and a || b all parse on both and give different answers.

TopicPostgreSQL 18MySQL 8.4
7 / 23 (integer division truncates)decimal division (3/5 → 0.60); DIV for integer
a || bConcatenationLogical OR (unless PIPES_AS_CONCAT)
'Ann' = 'ann'falsetrue (default _ai_ci collation)
Identifier quote"x"`x` (or "x" with ANSI_QUOTES)
NULL-safe equalIS NOT DISTINCT FROM<=>
NULLs in ORDER BY ASCLastFirst
NULLS FIRST/LASTYesNo
FULL OUTER JOINYesNo
INTERSECT / EXCEPTYes (with ALL)Since 8.0.31
LATERALYesSince 8.0.14
RETURNINGYesNo (LAST_INSERT_ID())
UPDATE ... FROM / DELETE ... USINGYesMulti-table UPDATE ... JOIN / DELETE t FROM ... JOIN
CTE MATERIALIZED hintYesNo
Data-modifying CTEYesNo
Non-aggregated column42803 unless functionally dependent on a PK1055 under ONLY_FULL_GROUP_BY (default); dependence via PK, unique NOT NULL or WHERE equality
FETCH FIRSTYesNo
Boolean resultsboolean (t/f)1 / 0 / NULL
String to number comparisonError or explicit castSilent numeric conversion

SQLite differences Important ​

In plain words: SQLite follows PostgreSQL's syntax more than MySQL's, but it is dynamically typed and more permissive. Code tested only on SQLite can carry bugs that PostgreSQL would reject.

Common misunderstanding: "SQLite is fine for tests because it is the same SQL." Lab Q05 (alias in WHERE), Q21 (bare columns), Q29 (affinity), Q30 (double-quoted string fallback) and Q36 (scalar subquery with several rows) all succeed on SQLite and fail or differ on PostgreSQL. Run integration tests on the production engine (see SQLite in Depth).

TopicSQLite 3.54Since
RIGHT JOIN, FULL OUTER JOINYes3.39.0 (2022-06-25)
IS [NOT] DISTINCT FROMYes (= IS NOT / IS)3.39.0
RETURNINGYes3.35.0 (2021-03-12)
AS [NOT] MATERIALIZEDYes3.35.0
UPDATE ... FROMYes3.33.0 (2020-08-14)
NULLS FIRST / NULLS LASTYes3.30.0 (2019-10-04)
LATERAL, FETCH FIRST, DELETE ... USINGNo
TypingFlexible typing with column affinity; STRICT tables opt out
Select alias in WHERE, GROUP BY, HAVINGAccepted (lab Q05, Q37)
Bare columns in aggregatesAccepted (value from the min/max row)
Double-quoted string literalAccepted when no column matches (a documented quirk)
Scalar subquery with many rowsFirst row, no error

Other products Good to know ​

SQL Server (Microsoft Learn T-SQL reference): TOP (expression) [WITH TIES] and OFFSET ... FETCH inside ORDER BY; CROSS APPLY / OUTER APPLY in FROM for lateral joins; OUTPUT, which "Returns information from, or expressions based on, each row affected by an INSERT, UPDATE, DELETE, or MERGE statement", instead of RETURNING; ISNULL() ("Replaces NULL with the specified replacement value") next to COALESCE; IIF(); and UNIQUE constraints where "only one null value is allowed per column". Oracle Database (23 SQL Reference and use-the-index-luke): treats '' as NULL; NVL ("If expr1 is null, then NVL returns expr2"); MINUS and EXCEPT with equal set-operator precedence; FETCH FIRST through the row_limiting_clause; NULLS LAST as the ascending default; a BOOLEAN data type. CockroachDB, MongoDB and Redis are not compared clause by clause on this page: distributed SQL is covered in Distributed SQL, MongoDB's aggregation pipeline in MongoDB in Depth, and Redis has no SQL dialect (see Redis).

Mechanics ​

From text to result: what the engine does with your query Good to know ​

In plain words: the engine parses your text, resolves names against the catalogue, rewrites the query into an equivalent tree of relational operators, lets the planner choose an execution plan, then runs it. Every rule on this page is enforced in the second step (names, groups, types); every speed question is decided in the fourth.

Common misunderstanding: "Rewriting my NOT IN as NOT EXISTS is only a performance tweak." With nullable columns it changes the meaning. NOT EXISTS is NULL-safe, so planners can turn it into an anti-join; for NOT IN the MySQL manual warns that "Antijoin transformations cannot in most cases be applied if the expressions being compared are nullable", so a nullable NOT IN keeps the slower, NULL-aware evaluation.

text
1  parse        text -> syntax tree          42601 syntax_error, MySQL 1064, SQLite "near ...: syntax error"
2  analyze      resolve names and types      42703 undefined_column, 42803 grouping_error, MySQL 1054 / 1055 / 1052
3  rewrite      views, CTE inlining, simplification: LEFT JOIN + WHERE r.col = x -> INNER JOIN
4  plan         join order, join algorithm, index choice, semi/anti-join transformation   -> /database/query-planning
5  execute      produce rows; runtime errors: 22012 division_by_zero, 21000 cardinality_violation, MySQL 1242

Two rewrites matter for semantics:

  • Outer-join simplification. If a WHERE condition on the nullable side rejects NULLs (o.status = 'paid'), a LEFT JOIN produces the same result as an INNER JOIN, and planners convert it. That is the formal reason behind lab Q08's "Dee and Eve vanish".
  • Subquery to join. EXISTS/IN become semi-joins and NOT EXISTS becomes an anti-join. MySQL: "Beginning with MySQL 8.0.17, the following subqueries are transformed into antijoins", and "any negation of a subquery of the form IN (SELECT ... FROM ...) or EXISTS (SELECT ... FROM ...) is transformed into an antijoin." PostgreSQL shows Hash Semi Join / Hash Anti Join nodes. Reading those nodes is taught in Query Planning and the cheatsheet.

Error codes you will meet Important ​

SituationPostgreSQL SQLSTATEMySQL errorSQLite message (lab)
Syntax error42601 syntax_error1064near "FETCH": syntax error
Unknown column / alias in WHERE42703 undefined_column1054 ER_BAD_FIELD_ERROR "Unknown column '%s' in '%s'"accepted (alias)
Ambiguous column42702 ambiguous_column1052 ER_NON_UNIQ_ERROR "Column '%s' in %s is ambiguous"ambiguous column name: id
Non-aggregated column with GROUP BY42803 grouping_error1055 ER_WRONG_FIELD_WITH_GROUP "'%s' isn't in GROUP BY"accepted (bare column)
Aggregate in WHERE42803 grouping_error1111 ER_INVALID_GROUP_FUNC_USE "Invalid use of group function"misuse of aggregate function sum()
Scalar subquery returns several rows21000 cardinality_violation1242 ER_SUBQUERY_NO_1_ROW "Subquery returns more than 1 row"first row, no error
Derived table without aliasaccepted1248 ER_DERIVED_MUST_HAVE_ALIASaccepted
Division by zero22012 division_by_zeroSELECT: NULL; INSERT/UPDATE: warning or (with strict mode) error under ERROR_FOR_DIVISION_BY_ZERONULL (lab Q37)
Bad text to number cast22P02 invalid_text_representationnumeric context: '1a' converts to 1leading digits used (lab Q29)

The knobs that change query semantics Important ​

KnobProductEffectDefault
sql_mode ONLY_FULL_GROUP_BYMySQLRejects non-dependent bare columnsOn in 8.4
sql_mode ANSI_QUOTESMySQL"x" becomes an identifierOff
sql_mode PIPES_AS_CONCATMySQL|| concatenatesOff
sql_mode STRICT_TRANS_TABLESMySQLBad values error instead of being adjustedOn
lower_case_table_namesMySQLTable-name case sensitivity0 Unix, 1 Windows, 2 macOS
cte_max_recursion_depthMySQLStops runaway recursive CTEs1000 ("By default, cte_max_recursion_depth has a value of 1000"); settable per statement with SET_VAR
transform_null_equalsPostgreSQL"When on, expressions of the form expr = NULL (or NULL = expr) are treated as expr IS NULL"off
standard_conforming_stringsPostgreSQL"ordinary string literals ('...') treat backslashes literally"on (since 9.1)
Collation (COLLATE)AllEquality and sort order of textPer database / column
PRAGMA case_sensitive_likeSQLiteLIKE case sensitivity ("by default 'a' LIKE 'A' is true")off
STRICT tablesSQLiteRigid column types, "as of version 3.37.0 (2021-11-27)"off (per table)

Solving the classic problems ​

ProblemPreferred solutionHowAdvantageCost / limitation
Rows with no match (customers without orders)NOT EXISTSCorrelated anti-joinNULL-safe, becomes an anti-joinNeeds an index on the inner key
Rows with at least one matchEXISTSSemi-joinNo duplicates, stops at first match
Count per parent including zeroLEFT JOIN + filter in ON + count(child.id)Q08Keeps every parentFan-out if you join two child tables
Sum per parent including zeroCOALESCE(sum(x), 0)Q18Numbers instead of NULL
Latest row per groupLATERAL ... ORDER BY ... LIMIT 1 (PostgreSQL, MySQL); correlated subquery in ON (SQLite)Q35One index probe per parentWindow functions for whole sets
Top N per groupROW_NUMBER() window, or LATERAL ... LIMIT nAdvanced SQL
Equality with nullable valuesIS NOT DISTINCT FROM / <=>Q03Two-valuedSpelling differs: MySQL only has <=>
Pivot / conditional totalssum(CASE WHEN ... END), PostgreSQL FILTERQ27PortableOne pass, wide queries get long
Hierarchy of unknown depthWITH RECURSIVE + depth guardQ24One statementCycles need guards
Reconcile two listsFULL OUTER JOIN, or EXCEPT both waysQ09, Q22Shows both sides' gapsMySQL needs UNION ALL emulation
Read generated ids after insertRETURNING (PostgreSQL, SQLite); LAST_INSERT_ID() (MySQL)Q31One round trip
Update from another tableUPDATE ... FROM / MySQL UPDATE ... JOINQ32Set-based, no loopDuplicates in the source make the result arbitrary

Fixing NULL and outer-join bugs in Go ​

The before package compiles, runs and returns wrong answers on the lab data: NOT IN returns nothing, the WHERE filter drops Dee and Eve, country = $1 with a nil pointer matches nothing, and scanning a NULL column into string fails. Its tests assert those wrong results, so the bug is reproducible.

Before ​

go
// Package before shows four reporting queries that compile, run and return
// plausible-looking but wrong answers, because each one ignores how SQL treats
// NULL and outer joins. The tests assert the wrong results on purpose.
package before

import (
	"context"
	"database/sql"
)

// NonReferrers should list customers who referred nobody. NOT IN over a
// column that contains NULL is never TRUE, so this returns no rows at all.
func NonReferrers(ctx context.Context, db *sql.DB) ([]string, error) {
	return names(ctx, db, `
		SELECT name FROM customers
		WHERE id NOT IN (SELECT referred_by FROM customers)
		ORDER BY id`)
}

// PaidOrderCounts should give every customer with their number of paid
// orders. The filter on the outer-joined table sits in WHERE, which removes
// the NULL-extended rows: customers with zero paid orders disappear.
func PaidOrderCounts(ctx context.Context, db *sql.DB) (map[string]int, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT c.name, count(o.id)
		FROM customers c
		LEFT JOIN orders o ON o.customer_id = c.id
		WHERE o.status = 'paid'
		GROUP BY c.id, c.name`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[string]int{}
	for rows.Next() {
		var name string
		var n int
		if err := rows.Scan(&name, &n); err != nil {
			return nil, err
		}
		out[name] = n
	}
	return out, rows.Err()
}

// CustomersInCountry passes a nil *string for "unknown country". The driver
// sends NULL, and country = NULL is UNKNOWN for every row: no match, no error.
func CustomersInCountry(ctx context.Context, db *sql.DB, country *string) ([]string, error) {
	return names(ctx, db, `SELECT name FROM customers WHERE country = $1 ORDER BY id`, country)
}

// Countries scans a nullable column into a plain string. The first NULL row
// makes Scan fail ("converting NULL to string is unsupported").
func Countries(ctx context.Context, db *sql.DB) ([]string, error) {
	return names(ctx, db, `SELECT country FROM customers ORDER BY id`)
}

func names(ctx context.Context, db *sql.DB, query string, args ...any) ([]string, error) {
	rows, err := db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []string
	for rows.Next() {
		var s string
		if err := rows.Scan(&s); err != nil {
			return nil, err
		}
		out = append(out, s)
	}
	return out, rows.Err()
}

After ​

go
// Package after fixes the four queries of package before and adds the
// patterns the chapter recommends: NOT EXISTS for anti-joins, outer-join
// filters in ON, IS NOT DISTINCT FROM for NULL-aware equality, sql.Null[T]
// (Go 1.22) for nullable columns, COALESCE for empty aggregates, a CTE with
// HAVING, and INSERT ... RETURNING. Placeholders are PostgreSQL style ($1);
// the SQLite driver used in the tests binds them positionally as well.
package after

import (
	"context"
	"database/sql"
)

// NonReferrers is an anti-join with NOT EXISTS: a NULL in referred_by can no
// longer poison the result.
func NonReferrers(ctx context.Context, db *sql.DB) ([]string, error) {
	return names(ctx, db, `
		SELECT c.name FROM customers c
		WHERE NOT EXISTS (
			SELECT 1 FROM customers x WHERE x.referred_by = c.id
		)
		ORDER BY c.id`)
}

// PaidOrderCounts keeps every customer: the filter on the optional side of the
// LEFT JOIN is part of ON, and count(o.id) counts only matched rows.
func PaidOrderCounts(ctx context.Context, db *sql.DB) (map[string]int, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT c.name, count(o.id)
		FROM customers c
		LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
		GROUP BY c.id, c.name`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[string]int{}
	for rows.Next() {
		var name string
		var n int
		if err := rows.Scan(&name, &n); err != nil {
			return nil, err
		}
		out[name] = n
	}
	return out, rows.Err()
}

// CustomersInCountry treats a nil country as "unknown" and matches NULL rows.
// IS NOT DISTINCT FROM works on PostgreSQL and SQLite 3.39+; MySQL spells it
// country <=> ?.
func CustomersInCountry(ctx context.Context, db *sql.DB, country *string) ([]string, error) {
	return names(ctx, db, `
		SELECT name FROM customers
		WHERE country IS NOT DISTINCT FROM $1
		ORDER BY id`, country)
}

// Country is one row of Countries. Valid is false when the column was NULL.
type Country struct {
	Name    string
	Country sql.Null[string]
}

// Countries scans the nullable column into sql.Null[string].
func Countries(ctx context.Context, db *sql.DB) ([]Country, error) {
	rows, err := db.QueryContext(ctx, `SELECT name, country FROM customers ORDER BY id`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []Country
	for rows.Next() {
		var c Country
		if err := rows.Scan(&c.Name, &c.Country); err != nil {
			return nil, err
		}
		out = append(out, c)
	}
	return out, rows.Err()
}

// Revenue is paid revenue per customer, in cents, with zero for customers who
// never paid. sum() over no rows is NULL; COALESCE turns it into 0. ROUND
// before CAST: SQLite stores NUMERIC 0.29 as a float, 0.29*100 is
// 28.999..., and CAST alone truncates it to 28. Storing integer cents in the
// schema avoids the conversion altogether.
type Revenue struct {
	Name  string
	Cents int64
}

// RevenueByCustomer returns every customer, best first.
func RevenueByCustomer(ctx context.Context, db *sql.DB) ([]Revenue, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT c.name, CAST(ROUND(COALESCE(sum(o.total), 0) * 100) AS INTEGER) AS cents
		FROM customers c
		LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
		GROUP BY c.id, c.name
		ORDER BY cents DESC, c.id`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []Revenue
	for rows.Next() {
		var r Revenue
		if err := rows.Scan(&r.Name, &r.Cents); err != nil {
			return nil, err
		}
		out = append(out, r)
	}
	return out, rows.Err()
}

// BigSpenders names the customers whose paid revenue reaches minTotal. The
// CTE keeps the aggregate readable; HAVING filters groups, WHERE filters rows.
func BigSpenders(ctx context.Context, db *sql.DB, minTotal float64) ([]string, error) {
	return names(ctx, db, `
		WITH paid AS (
			SELECT customer_id, sum(total) AS revenue
			FROM orders
			WHERE status = 'paid'
			GROUP BY customer_id
			HAVING sum(total) >= $1
		)
		SELECT c.name FROM paid p JOIN customers c ON c.id = p.customer_id
		ORDER BY p.revenue DESC, c.id`, minTotal)
}

// CreateOrder inserts an order and reads the generated id back in the same
// statement with RETURNING (PostgreSQL, SQLite 3.35+, MariaDB). MySQL
// has no RETURNING: use Result.LastInsertId there.
func CreateOrder(ctx context.Context, db *sql.DB, customerID int64, total float64) (int64, error) {
	var id int64
	err := db.QueryRowContext(ctx, `
		INSERT INTO orders (tenant_id, customer_id, status, total, created_at)
		VALUES (1, $1, 'pending', $2, '2026-11-29 09:00:00')
		RETURNING id`, customerID, total).Scan(&id)
	return id, err
}

func names(ctx context.Context, db *sql.DB, query string, args ...any) ([]string, error) {
	rows, err := db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []string
	for rows.Next() {
		var s string
		if err := rows.Scan(&s); err != nil {
			return nil, err
		}
		out = append(out, s)
	}
	return out, rows.Err()
}

The tests run both packages against an in-memory SQLite database (modernc.org/sqlite v1.34.5, pure Go) loaded with the lab schema:

go
// Package schema holds the shared e-commerce schema and seed rows used by the
// chapter's tests. The DDL is portable: it runs unchanged on SQLite, and on
// PostgreSQL and MySQL after swapping INTEGER PRIMARY KEY for an identity or
// AUTO_INCREMENT column.
package schema

import (
	"context"
	"database/sql"
)

// Statements creates the three tables and inserts the seed. Customer 5 (Eve)
// has no orders; customers 1 and 5 have referred_by = NULL; Dee's country is
// NULL. Those three facts drive every NULL and outer-join example.
var Statements = []string{
	`CREATE TABLE customers (
		id          INTEGER PRIMARY KEY,
		email       TEXT NOT NULL UNIQUE,
		name        TEXT NOT NULL,
		country     TEXT,
		referred_by INTEGER REFERENCES customers(id),
		created_at  TEXT NOT NULL
	)`,
	`CREATE TABLE orders (
		id          INTEGER PRIMARY KEY,
		tenant_id   INTEGER NOT NULL,
		customer_id INTEGER NOT NULL REFERENCES customers(id),
		status      TEXT NOT NULL,
		total       NUMERIC(12,2) NOT NULL,
		coupon_code TEXT,
		created_at  TEXT NOT NULL
	)`,
	`CREATE TABLE order_items (
		id       INTEGER PRIMARY KEY,
		order_id INTEGER NOT NULL REFERENCES orders(id),
		sku      TEXT NOT NULL,
		qty      INTEGER NOT NULL,
		price    NUMERIC(12,2) NOT NULL
	)`,
	`INSERT INTO customers VALUES
		(1,'ann@x.io','Ann','DE',NULL,'2026-01-05 10:00:00'),
		(2,'bob@x.io','Bob','FR',1,'2026-02-11 09:30:00'),
		(3,'cy@x.io','Cy','DE',2,'2026-03-20 15:00:00'),
		(4,'dee@x.io','Dee',NULL,1,'2026-06-01 08:00:00'),
		(5,'eve@x.io','Eve','IR',NULL,'2026-11-01 12:00:00')`,
	`INSERT INTO orders VALUES
		(1,1,1,'paid',50.00,'WELCOME','2026-11-01 10:00:00'),
		(2,1,1,'paid',20.00,NULL,'2026-11-10 09:00:00'),
		(3,1,1,'refunded',15.00,NULL,'2026-11-21 08:00:00'),
		(4,1,2,'paid',99.00,'BF26','2026-11-02 11:00:00'),
		(5,1,2,'pending',5.00,NULL,'2026-11-28 16:00:00'),
		(6,2,3,'paid',40.00,NULL,'2026-11-05 10:00:00'),
		(7,2,3,'paid',60.00,'BF26','2026-11-05 15:00:00'),
		(8,2,4,'pending',25.00,NULL,'2026-11-12 10:00:00')`,
	`INSERT INTO order_items VALUES
		(1,1,'A',1,50.00),(2,2,'B',2,12.00),(3,3,'A',1,15.00),(4,4,'C',3,33.00),
		(5,6,'B',4,10.00),(6,7,'A',2,30.00),(7,8,'C',1,25.00)`,
}

// Apply runs every statement in order.
func Apply(ctx context.Context, db *sql.DB) error {
	for _, s := range Statements {
		if _, err := db.ExecContext(ctx, s); err != nil {
			return err
		}
	}
	return nil
}
go
package after

import (
	"context"
	"database/sql"
	"reflect"
	"testing"

	"academy/sql-querying-fundamentals/schema"

	_ "modernc.org/sqlite"
)

func open(t *testing.T) *sql.DB {
	t.Helper()
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		t.Fatal(err)
	}
	db.SetMaxOpenConns(1)
	t.Cleanup(func() { db.Close() })
	if err := schema.Apply(context.Background(), db); err != nil {
		t.Fatal(err)
	}
	return db
}

func TestNonReferrers(t *testing.T) {
	got, err := NonReferrers(context.Background(), open(t))
	if err != nil {
		t.Fatal(err)
	}
	if want := []string{"Cy", "Dee", "Eve"}; !reflect.DeepEqual(got, want) {
		t.Fatalf("got %v, want %v", got, want)
	}
}

func TestPaidOrderCountsKeepsEveryone(t *testing.T) {
	got, err := PaidOrderCounts(context.Background(), open(t))
	if err != nil {
		t.Fatal(err)
	}
	want := map[string]int{"Ann": 2, "Bob": 1, "Cy": 2, "Dee": 0, "Eve": 0}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("got %v, want %v", got, want)
	}
}

func TestCustomersInCountry(t *testing.T) {
	db := open(t)
	ctx := context.Background()
	got, err := CustomersInCountry(ctx, db, nil)
	if err != nil {
		t.Fatal(err)
	}
	if want := []string{"Dee"}; !reflect.DeepEqual(got, want) {
		t.Fatalf("nil: got %v, want %v", got, want)
	}
	de := "DE"
	got, err = CustomersInCountry(ctx, db, &de)
	if err != nil {
		t.Fatal(err)
	}
	if want := []string{"Ann", "Cy"}; !reflect.DeepEqual(got, want) {
		t.Fatalf("DE: got %v, want %v", got, want)
	}
}

func TestCountriesNullable(t *testing.T) {
	got, err := Countries(context.Background(), open(t))
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 5 {
		t.Fatalf("got %d rows, want 5", len(got))
	}
	if got[3].Name != "Dee" || got[3].Country.Valid {
		t.Fatalf("Dee's country should be NULL, got %+v", got[3])
	}
	if !got[0].Country.Valid || got[0].Country.V != "DE" {
		t.Fatalf("Ann's country should be DE, got %+v", got[0])
	}
}

func TestRevenueByCustomer(t *testing.T) {
	got, err := RevenueByCustomer(context.Background(), open(t))
	if err != nil {
		t.Fatal(err)
	}
	want := []Revenue{{"Cy", 10000}, {"Bob", 9900}, {"Ann", 7000}, {"Dee", 0}, {"Eve", 0}}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("got %v, want %v", got, want)
	}
}

func TestRevenueRoundsFractionalCents(t *testing.T) {
	db := open(t)
	ctx := context.Background()
	// 0.29 * 100 is 28.999... in floating point; truncation would give 28.
	if _, err := db.ExecContext(ctx, `INSERT INTO orders (tenant_id, customer_id, status, total, created_at)
		VALUES (1, 5, 'paid', 0.29, '2026-11-29 09:00:00')`); err != nil {
		t.Fatal(err)
	}
	var truncated int64
	if err := db.QueryRowContext(ctx, `SELECT CAST(0.29 * 100 AS INTEGER)`).Scan(&truncated); err != nil {
		t.Fatal(err)
	}
	if truncated != 28 {
		t.Fatalf("expected the truncation trap to give 28, got %d", truncated)
	}
	got, err := RevenueByCustomer(ctx, db)
	if err != nil {
		t.Fatal(err)
	}
	for _, r := range got {
		if r.Name == "Eve" {
			if r.Cents != 29 {
				t.Fatalf("Eve: got %d cents, want 29", r.Cents)
			}
			return
		}
	}
	t.Fatal("Eve missing from revenue")
}

func TestBigSpenders(t *testing.T) {
	got, err := BigSpenders(context.Background(), open(t), 90)
	if err != nil {
		t.Fatal(err)
	}
	if want := []string{"Cy", "Bob"}; !reflect.DeepEqual(got, want) {
		t.Fatalf("got %v, want %v", got, want)
	}
}

func TestCreateOrderReturning(t *testing.T) {
	db := open(t)
	id, err := CreateOrder(context.Background(), db, 5, 12.5)
	if err != nil {
		t.Fatal(err)
	}
	if id != 9 {
		t.Fatalf("got id %d, want 9", id)
	}
	var customer int64
	if err := db.QueryRow(`SELECT customer_id FROM orders WHERE id = $1`, id).Scan(&customer); err != nil {
		t.Fatal(err)
	}
	if customer != 5 {
		t.Fatalf("got customer %d, want 5", customer)
	}
}

The Go angle ​

  • NULL needs a nullable Go type. database/sql cannot scan NULL into string or int64 (the before test checks the error). Use sql.NullString / sql.NullInt64, a pointer (*string), or the generic sql.Null[T], which Go 1.22 added: "The new Null[T] type provide a way to scan nullable columns for any column types" (Go 1.22 release notes). Passing a nil pointer as an argument sends NULL, which is why country = $1 needs IS NOT DISTINCT FROM.
  • Placeholders are driver syntax, not SQL. pgx uses $1 (README example where id=$1); lib/pq: "database/sql does not dictate any specific format for parameter placeholders, and pq uses the PostgreSQL-native ordinal markers ($1, $2, etc.)"; go-sql-driver/mysql uses ? (its README: "placeholders (?)"); SQLite drivers accept both. The test in schema/ proves $1 binds positionally with modernc.org/sqlite.
  • QueryRowContext(...).Scan on INSERT ... RETURNING is the PostgreSQL and SQLite way to get a generated id; with MySQL use ExecContext and Result.LastInsertId().
  • Aggregates come back as driver-specific types. The Go type a driver returns for a numeric/NUMERIC aggregate differs between drivers (the SQLite driver returns float64 or int64); the after package converts to integer cents in SQL with CAST(ROUND(x * 100) AS INTEGER) so the Go type is stable; without ROUND, SQLite turns 0.29 into 28 cents, because 0.29 * 100 is 28.999... as a float and CAST truncates (lab Q38, test TestRevenueRoundsFractionalCents). Money belongs in integer cents or numeric (see Schema Design).
  • Always close rows and check rows.Err(); a query that fails mid-stream reports the error there, not from Next().

Fixing the same bugs in Laravel ​

Before ​

php
<?php

namespace App\Reports;

use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

// Four reports that run without an error and return wrong answers.
final class CustomerReportBefore
{
    // "Customers who referred nobody": NOT IN over a column that contains NULL
    // is never TRUE, so this collection is always empty.
    public function nonReferrers(): Collection
    {
        return DB::table('customers')
            ->whereNotIn('id', function (Builder $query) {
                $query->select('referred_by')->from('customers');
            })
            ->orderBy('id')
            ->pluck('name');
    }

    // "Paid orders per customer": the where() on the left-joined table runs
    // after the join and removes every customer without a paid order.
    public function paidOrderCounts(): Collection
    {
        return DB::table('customers as c')
            ->leftJoin('orders as o', 'o.customer_id', '=', 'c.id')
            ->where('o.status', 'paid')
            ->groupBy('c.id', 'c.name')
            ->selectRaw('c.name, count(o.id) as paid_orders')
            ->get();
    }

    // "Customers in this country (or with no country)": with $country = null
    // the builder writes "country is null", but a raw '=' comparison is a trap.
    public function inCountryRaw(?string $country): Collection
    {
        return DB::table('customers')
            ->whereRaw('country = ?', [$country])
            ->orderBy('id')
            ->pluck('name');
    }

    // Revenue per customer: sum() over no rows is NULL, so customers without
    // paid orders come back with null instead of 0, and the PHP code that
    // formats the number has to guess.
    public function revenue(): Collection
    {
        return DB::table('customers as c')
            ->leftJoin('orders as o', function ($join) {
                $join->on('o.customer_id', '=', 'c.id')->where('o.status', '=', 'paid');
            })
            ->groupBy('c.id', 'c.name')
            ->selectRaw('c.name, sum(o.total) as revenue')
            ->get();
    }
}

After ​

php
<?php

namespace App\Reports;

use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

// The same reports written with the SQL semantics in mind (Laravel 13 query builder).
final class CustomerReport
{
    // Anti-join with NOT EXISTS: NULLs in referred_by cannot hide rows.
    public function nonReferrers(): Collection
    {
        return DB::table('customers as c')
            ->whereNotExists(function (Builder $query) {
                $query->selectRaw('1')
                    ->from('customers as x')
                    ->whereColumn('x.referred_by', 'c.id');
            })
            ->orderBy('c.id')
            ->pluck('c.name');
    }

    // The filter on the optional side belongs to the ON clause.
    public function paidOrderCounts(): Collection
    {
        return DB::table('customers as c')
            ->leftJoin('orders as o', function (JoinClause $join) {
                $join->on('o.customer_id', '=', 'c.id')
                    ->where('o.status', '=', 'paid');
            })
            ->groupBy('c.id', 'c.name')
            ->selectRaw('c.name, count(o.id) as paid_orders')
            ->orderBy('c.id')
            ->get();
    }

    // NULL-safe equality: the grammar emits IS NOT DISTINCT FROM on
    // PostgreSQL (base grammar), IS on SQLite, and <=> on MySQL/MariaDB.
    public function inCountry(?string $country): Collection
    {
        return DB::table('customers')
            ->whereNullSafeEquals('country', $country)
            ->orderBy('id')
            ->pluck('name');
    }

    // COALESCE gives 0 for customers who never paid; the result is a number.
    public function revenue(): Collection
    {
        return DB::table('customers as c')
            ->leftJoin('orders as o', function (JoinClause $join) {
                $join->on('o.customer_id', '=', 'c.id')
                    ->where('o.status', '=', 'paid');
            })
            ->groupBy('c.id', 'c.name')
            ->selectRaw('c.name, coalesce(sum(o.total), 0) as revenue')
            ->orderByDesc('revenue')
            ->get();
    }

    // Groups filtered with HAVING; the threshold is a binding, not a string.
    public function bigSpenders(float $minTotal): Collection
    {
        return DB::table('orders')
            ->where('status', 'paid')
            ->groupBy('customer_id')
            ->havingRaw('sum(total) >= ?', [$minTotal])
            ->selectRaw('customer_id, sum(total) as revenue')
            ->orderByDesc('revenue')
            ->get();
    }

    // Latest order per customer with a lateral join (PostgreSQL, MySQL >= 8.0.14,
    // SQL Server). The correlation lives in whereColumn inside the subquery.
    public function latestOrders(): Collection
    {
        $latest = DB::table('orders')
            ->select('id', 'total', 'created_at')
            ->whereColumn('customer_id', 'customers.id')
            ->orderByDesc('created_at')
            ->limit(1);

        return DB::table('customers')
            ->leftJoinLateral($latest, 'latest')
            ->select('customers.name', 'latest.id as order_id', 'latest.total')
            ->orderBy('customers.id')
            ->get();
    }

    // The query builder has no CTE method: a recursive CTE goes through
    // DB::select with bindings.
    public function referralChain(int $rootId): array
    {
        return DB::select(<<<'SQL'
            WITH RECURSIVE chain (id, name, depth) AS (
                SELECT id, name, 0 FROM customers WHERE id = ?
                UNION ALL
                SELECT c.id, c.name, chain.depth + 1
                FROM customers c JOIN chain ON c.referred_by = chain.id
            )
            SELECT id, name, depth FROM chain ORDER BY depth, id
            SQL, [$rootId]);
    }

    // Paid OR pending customers, duplicates kept on purpose (UNION ALL).
    public function activeCustomerIds(): Collection
    {
        $pending = DB::table('orders')->where('status', 'pending')->select('customer_id');

        return DB::table('orders')
            ->where('status', 'paid')
            ->select('customer_id')
            ->unionAll($pending)
            ->pluck('customer_id');
    }
}

The Laravel angle ​

  • whereNotIn with a closure is NOT IN (subquery) and has the NULL trap; whereNotExists with whereColumn is the anti-join. Both are Laravel 13 query builder methods (Illuminate\Database\Query\Builder).
  • where('country', null) becomes country is null, so the builder protects you; whereRaw('country = ?', [null]) does not. For "equal, NULLs included" Laravel 13 has whereNullSafeEquals: the docs say it compares "while treating two NULL values as equal", and the grammars emit is not distinct from (base grammar, used by PostgreSQL), <=> (MySQL) and is (SQLite).
  • Conditions on a left-joined table go into the join closure (JoinClause::where), exactly like ON ... AND in SQL. The docs: the where methods of the JoinClause "will compare the column against a value".
  • joinLateral / leftJoinLateral build LATERAL joins; "Lateral joins are currently supported by PostgreSQL, MySQL >= 8.0.14, and SQL Server." unionAll keeps duplicates; union removes them.
  • There is no CTE builder method in the documented query builder; use DB::select with bindings (as referralChain does) or a package. Eloquent relationship queries express the same questions: whereDoesntHave adds "query constraints to your doesntHave queries" (the anti-join), and withCount will "count the number of related models for a given relationship without actually loading the models"; ORM Pitfalls covers the SQL they produce and what it costs.

Choosing a construct ​

QuestionUseAvoidReason
"Parents with at least one child"EXISTSJOIN + DISTINCTSemi-join, no fan-out
"Parents with no child"NOT EXISTSNOT IN over nullable columnsNULL makes NOT IN empty
"Every parent, with child data if any"LEFT JOIN, filters in ONFilters on the child in WHEREWHERE undoes the outer join
"One value per row from elsewhere"Scalar subquery or LATERAL ... LIMIT 1Joining a many-side then max() everywhereClearer, no fan-out
"Filter on an aggregate"HAVINGAggregate in WHEREAggregates exist after grouping
"Filter rows before grouping"WHEREHAVING without aggregatesFewer rows reach GROUP BY
"Combine two result lists"UNION ALLUNION by habitDedup costs a sort or hash
"Rows in A not in B, whole rows"EXCEPTLong NOT EXISTS on many columnsNULLs compare equal in set operations
"Readable multi-step query"CTENested derived tables 4 levels deepSame meaning; PostgreSQL inlines single-use CTEs
"Tree of unknown depth"WITH RECURSIVE + guardApplication loop of queriesOne round trip
"Paged list"ORDER BY ... , id + keysetLarge OFFSETOffset rows are still computed
"Equal, NULL included"IS NOT DISTINCT FROM / <=>a = b OR (a IS NULL AND b IS NULL) copiesShorter, same meaning

In architecture: from a single process to a distributed system ​

SQL semantics are defined for one database. As data spreads over services, replicas and caches, the language does not change, but the place where a join or an aggregate can run does.

Monolith: one process, one database ​

All tables live in one database, so every question on this page is one statement: the admin "customers with paid order count" page is a LEFT JOIN + GROUP BY with the filter in ON; the "inactive customers" job is a NOT EXISTS. The simplest correct usage: push joins and aggregates into SQL instead of loading rows into Go or PHP and looping (that loop is the N+1 problem, see ORM Pitfalls), keep nullable columns rare, and test queries against the production engine.

Modular monolith and multiple databases ​

Modules own their tables (orders module: orders, order_items; customers module: customers). A cross-module join still works in one database, but it couples the modules' schemas. Common rule: modules expose views or query services; a report that joins across modules lives in a reporting module that reads documented views. Across two physical databases, a SQL join is no longer available unless you use PostgreSQL postgres_fdw or MySQL FEDERATED, which turn a join into remote calls.

Microservices: the join moves out of SQL ​

With a database per service, "customers without orders" can no longer be NOT EXISTS: customers live in the customer service, orders in the order service.

text
1  order-service     publishes OrderPlaced{order_id, customer_id, total} (outbox -> broker)
2  report-service    consumes it and upserts into its own read model: customer_orders(customer_id, paid_count, revenue)
3  customer-service  publishes CustomerRegistered{customer_id, name, country}
4  report-service    upserts into customers_copy; now the anti-join is local again:
                     SELECT c.name FROM customers_copy c WHERE NOT EXISTS (SELECT 1 FROM customer_orders o WHERE o.customer_id = c.customer_id)
5  API composition alternative: GET /customers + GET /orders?customer_id=... and an in-memory hash anti-join in Go

What survives: the semantics (anti-join, NULL handling, COALESCE for missing counts) now live in the read model's SQL or in the composition code, and the NULL bugs come back as "event not received yet". What does not survive: a single consistent snapshot; the read model is eventually consistent (see Eventual Consistency).

Distributed data: replicas, caches, sharding and distributed SQL ​

  • Read replicas: the same SQL, older data. A "customers without orders" query on a lagging replica reports a customer who ordered a second ago (see Replication).
  • Caches: caching a query result caches its semantics too; a cached count(*) per customer must be invalidated by every write that would change the GROUP BY result.
  • Sharding by customer_id: joins and aggregates within one customer stay local; GROUP BY country across all customers becomes scatter-gather: each shard computes a partial aggregate (sum, count) and the coordinator combines them. avg must be shipped as sum and count, count(DISTINCT) cannot be combined from partial counts, and ORDER BY ... LIMIT 10 needs the top 10 from every shard (see Partitioning & Sharding).
  • Distributed SQL (CockroachDB, YugabyteDB, Spanner): full SQL semantics across nodes, but a join between rows on different nodes costs network round trips; schema design co-locates rows that are joined together (see Distributed SQL).

Scaling path: 1×, 10×, 100× ​

LoadWhat changesSQL technique
1× (thousands of rows)Nothing; correctness is the only concernRight join kind, NOT EXISTS, COALESCE, explicit ORDER BY
10× (millions)Plans matter; indexes on join and filter columnsSame SQL, plus indexes (Indexing), keyset pagination, UNION ALL over UNION
100× (billions, many services)Aggregates precomputed, joins moved to read modelsSummary tables or materialized views refreshed incrementally, sharded scatter-gather aggregates, OLAP engines for GROUP BY over history (OLTP vs OLAP)

Lab ​

Everything below ran with sqlite3 3.54.0 (sqlite3 :memory:); output is pasted from that run. Statements marked "expected, not run" need a PostgreSQL or MySQL server, which this lab does not start. Turn on readable output first, or NULL prints as an empty string:

sql
.headers on
.mode column
.nullvalue NULL

Setup. Paste the three CREATE TABLE statements from The lab schema, then the seed:

sql
INSERT INTO customers VALUES
 (1,'ann@x.io','Ann','DE',NULL,'2026-01-05 10:00:00'),
 (2,'bob@x.io','Bob','FR',1,   '2026-02-11 09:30:00'),
 (3,'cy@x.io', 'Cy', 'DE',2,   '2026-03-20 15:00:00'),
 (4,'dee@x.io','Dee',NULL,1,   '2026-06-01 08:00:00'),
 (5,'eve@x.io','Eve','IR',NULL,'2026-11-01 12:00:00');
INSERT INTO orders VALUES
 (1,1,1,'paid',    50.00,'WELCOME','2026-11-01 10:00:00'),
 (2,1,1,'paid',    20.00,NULL,     '2026-11-10 09:00:00'),
 (3,1,1,'refunded',15.00,NULL,     '2026-11-21 08:00:00'),
 (4,1,2,'paid',    99.00,'BF26',   '2026-11-02 11:00:00'),
 (5,1,2,'pending',  5.00,NULL,     '2026-11-28 16:00:00'),
 (6,2,3,'paid',    40.00,NULL,     '2026-11-05 10:00:00'),
 (7,2,3,'paid',    60.00,'BF26',   '2026-11-05 15:00:00'),
 (8,2,4,'pending', 25.00,NULL,     '2026-11-12 10:00:00');
INSERT INTO order_items VALUES
 (1,1,'A',1,50.00),(2,2,'B',2,12.00),(3,3,'A',1,15.00),(4,4,'C',3,33.00),
 (5,6,'B',4,10.00),(6,7,'A',2,30.00),(7,8,'C',1,25.00);
CREATE TABLE coupons (code TEXT PRIMARY KEY, pct INTEGER NOT NULL);
INSERT INTO coupons VALUES ('WELCOME',10),('BF26',25),('SPRING',15);

Experiment 1: three-valued logic. Predict, then run:

sql
SELECT NULL = NULL AS eq, NULL <> 1 AS ne, NULL IS NULL AS is_null,
       (NULL = 1) OR TRUE AS u_or_t, (NULL = 1) AND FALSE AS u_and_f, NOT (NULL = 1) AS not_u;
-- eq    ne    is_null  u_or_t  u_and_f  not_u
-- NULL  NULL        1       1        0  NULL
SELECT id, name FROM customers WHERE country <> 'DE' ORDER BY id;           -- 2 Bob, 5 Eve
SELECT id, name FROM customers WHERE country IS DISTINCT FROM 'DE' ORDER BY id; -- 2 Bob, 4 Dee, 5 Eve

Experiment 2: the outer join that turns inner. Run both and count rows:

sql
SELECT c.name, count(o.id) AS paid_orders
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
GROUP BY c.id, c.name ORDER BY c.id;
-- Ann 2 | Bob 1 | Cy 2 | Dee 0 | Eve 0
SELECT c.name, count(o.id) AS paid_orders
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'paid'
GROUP BY c.id, c.name ORDER BY c.id;
-- Ann 2 | Bob 1 | Cy 2

Experiment 3: NOT IN with NULL.

sql
SELECT name FROM customers WHERE id NOT IN (SELECT referred_by FROM customers) ORDER BY id;
-- (no rows)
SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM customers x WHERE x.referred_by = c.id) ORDER BY c.id;
-- Cy | Dee | Eve
SELECT 3 IN (1, NULL) AS in_u, 3 NOT IN (1, NULL) AS not_in_u, 1 IN (1, NULL) AS in_t;
-- NULL | NULL | 1

Experiment 4: aggregates over NULLs and empty sets.

sql
SELECT count(*), count(coupon_code), count(DISTINCT coupon_code), sum(total), avg(total) FROM orders;
-- 8 | 3 | 2 | 314 | 39.25
SELECT count(*), sum(total) FROM orders WHERE status = 'nope';
-- 0 | NULL
SELECT customer_id, status, sum(total) FROM orders GROUP BY customer_id ORDER BY customer_id;
-- 1 paid 85 | 2 paid 104 | 3 paid 100 | 4 pending 25   <- SQLite bare column; PostgreSQL: 42803, MySQL: 1055

Experiment 5: set operations and a recursive CTE.

sql
SELECT customer_id FROM orders WHERE status = 'paid'
UNION ALL
SELECT customer_id FROM orders WHERE status = 'pending'
ORDER BY 1;                                       -- 1 1 2 2 3 3 4   (UNION gives 1 2 3 4)
WITH RECURSIVE chain(id, name, depth, path) AS (
  SELECT id, name, 0, name FROM customers WHERE referred_by IS NULL
  UNION ALL
  SELECT c.id, c.name, chain.depth + 1, chain.path || ' > ' || c.name
  FROM customers c JOIN chain ON c.referred_by = chain.id
)
SELECT id, name, depth, path FROM chain ORDER BY path;
-- 1 Ann 0 Ann | 2 Bob 1 Ann > Bob | 3 Cy 2 Ann > Bob > Cy | 4 Dee 1 Ann > Dee | 5 Eve 0 Eve

Experiment 6: what SQLite accepts that PostgreSQL rejects.

sql
SELECT id, total * 2 AS doubled FROM orders WHERE doubled > 100 ORDER BY id;   -- 4 198 | 7 120  (PostgreSQL: 42703)
SELECT (SELECT id FROM orders WHERE customer_id = 1 ORDER BY id) AS first_only; -- 1           (PostgreSQL: 21000)
SELECT "no_such_column" AS q;                                                    -- no_such_column (PostgreSQL: 42703)
SELECT id FROM orders ORDER BY id FETCH FIRST 2 ROWS ONLY;  -- Parse error: near "FETCH": syntax error (PostgreSQL: OK)

On PostgreSQL 18 and MySQL 8.4 (expected, not run). Repeat experiments 1–6 on both servers and note each difference against the dialect tables: PostgreSQL prints t/f, sorts the NULL country last, rejects the bare column (42803) and the alias in WHERE (42703); MySQL rejects IS DISTINCT FROM (use <=>), FULL OUTER JOIN, NULLS LAST and FETCH FIRST, rejects the bare column with 1055, and returns a decimal for 7 / 2 instead of 3.

The Go tests are the automated version of experiments 2 and 3: cd docs/snippets/database/sql-querying-fundamentals/go && go test -race -count=1 ./....

Common misconceptions ​

BeliefReality
x <> 'DE' returns every non-DE rowRows where x is NULL are UNKNOWN and dropped; use IS DISTINCT FROM or add OR x IS NULL
= NULL works if the column is NULLIt is never TRUE; use IS NULL
NOT IN and NOT EXISTS are interchangeableNOT IN returns no rows if the subquery yields a NULL
A LEFT JOIN keeps every left rowNot if WHERE tests a right-table column; put that test in ON
sum() of no rows is 0It is NULL; COALESCE(sum(x), 0)
count(col) counts rowsIt counts non-NULL values; count(*) counts rows
Rows come back in insertion or id orderNo order without ORDER BY; ties are undefined too
UNION is the default way to combine resultsUNION deduplicates (costly, may merge real duplicates); prefer UNION ALL
DISTINCT fixes a join returning too many rowsIt hides fan-out; use EXISTS or aggregate before joining
The clauses execute in written orderThe logical order is FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT; the physical plan is free
A CTE is always computed oncePostgreSQL inlines single-use CTEs unless MATERIALIZED; MySQL chooses merge or materialization
MySQL lets you select any column with GROUP BYONLY_FULL_GROUP_BY is in the 8.4 default sql_mode
NULLS LAST is standard everywhereMySQL and SQL Server lack it; defaults differ per engine
Passing nil from Go matches NULL rowscol = $1 with nil is UNKNOWN; use IS NOT DISTINCT FROM $1
SQLite behaves like PostgreSQL for testsIt accepts aliases in WHERE, bare columns, many-row scalar subqueries and loose types

Cheat sheet ​

TopicRemember
Logical orderFROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → set ops → ORDER BY → LIMIT
NULL testIS NULL, never = NULL
NULL-safe equalityIS NOT DISTINCT FROM (PostgreSQL, SQLite 3.39+), <=> (MySQL)
DefaultsCOALESCE(x, default); divide safely with x / NULLIF(y, 0)
Anti-joinNOT EXISTS; NOT IN only over NOT NULL columns
Semi-joinEXISTS, not JOIN + DISTINCT
Outer-join filterOptional-side conditions in ON
Countingcount(*) rows, count(col) non-NULL, count(DISTINCT col) different
Empty aggregatessum/avg/min/max of nothing is NULL; count is 0 (SQLite total(): 0.0)
WHERE vs HAVINGRows before grouping vs groups after
Non-aggregated columnsGroup by the primary key, or aggregate; ANY_VALUE when arbitrary is fine
Set operationsUNION ALL by default; INTERSECT binds tighter in PostgreSQL/MySQL, but SQLite and Oracle go left to right; NULLs compare equal
CTEsWITH for readability; MATERIALIZED to force once (PostgreSQL, SQLite)
RecursionWITH RECURSIVE + depth or cycle guard
SortingExplicit NULLS FIRST/LAST (not in MySQL); end with a unique column
PagingLIMIT/OFFSET (PostgreSQL, MySQL, SQLite), FETCH FIRST (standard); keyset for deep pages
Writes that returnRETURNING (PostgreSQL, SQLite 3.35+), LAST_INSERT_ID() (MySQL)
PortabilityTest on the production engine; SQLite accepts what PostgreSQL rejects

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does SELECT * FROM customers WHERE country <> 'DE' not return customers whose country is NULL? Must-know ​

Answer

Answer: Any comparison with NULL yields UNKNOWN, and WHERE keeps only rows whose condition is TRUE. NULL <> 'DE' is UNKNOWN, so the row is filtered out like a FALSE. Write country IS DISTINCT FROM 'DE' (MySQL: NOT (country <=> 'DE')) or country <> 'DE' OR country IS NULL. See NULL and three-valued logic.

2 — WHERE id NOT IN (SELECT referred_by FROM customers) returns no rows, although some customers referred nobody. Why, and what do you write instead? Must-know ​

Answer

Answer: referred_by contains NULL. x NOT IN (a, NULL) means x <> a AND x <> NULL, and the second term is UNKNOWN, so the whole test is never TRUE. Use NOT EXISTS (SELECT 1 FROM customers r WHERE r.referred_by = c.id), which is two-valued, or filter WHERE referred_by IS NOT NULL inside the subquery. See anti-join.

3 — Why does a LEFT JOIN report suddenly miss customers with no paid orders after someone added WHERE o.status = 'paid', and how do you fix it? Must-know ​

Answer

Answer: WHERE runs after the join. For customers without a paid order the joined columns are NULL, o.status = 'paid' is UNKNOWN, and the rows are removed, so the outer join behaves as an inner join (planners even rewrite it to one). Move the condition into the join: LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid', and count count(o.id) rather than count(*). See LEFT JOIN.

4 — What is the logical evaluation order of a SELECT, and why can't you use a select alias in WHERE? Must-know ​

Answer

Answer: FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, set operations, ORDER BY, LIMIT/OFFSET. The alias is created in the SELECT step, after WHERE has already run, so PostgreSQL raises 42703 and MySQL 1054. ORDER BY runs later and can use it. SQLite accepts the alias as an extension, which is why code tested only on SQLite can fail on PostgreSQL. See evaluation order.

5 — What is the difference between count(*), count(coupon_code) and count(DISTINCT coupon_code), and what does sum(total) return for zero rows? Must-know ​

Answer

Answer: count(*) counts rows, count(col) counts rows where the column is not NULL, count(DISTINCT col) counts distinct non-NULL values (lab: 8, 3, 2). The standard aggregates except count return NULL over zero rows, so sum(total) is NULL, not 0; use COALESCE(sum(total), 0). (SQLite's non-standard total() is the exception: it returns 0.0.) See aggregate functions.

6 — SELECT customer_id, status, sum(total) FROM orders GROUP BY customer_id works on SQLite and fails on MySQL 8.4 and PostgreSQL. Why, and when is a non-grouped column allowed? Important ​

Answer

Answer: status has several values per group, so the result is undefined. PostgreSQL raises 42803; MySQL rejects it with 1055 because ONLY_FULL_GROUP_BY is in its default sql_mode; SQLite returns a value from an arbitrary row (a "bare column"). A non-aggregated column is allowed when it is functionally dependent on the grouped columns, for example when you group by the table's primary key. Otherwise aggregate it, add it to GROUP BY, or use ANY_VALUE() (MySQL, PostgreSQL 18) when any value is acceptable. See ONLY_FULL_GROUP_BY.

7 — When do you use WHERE and when HAVING? Important ​

Answer

Answer: WHERE filters input rows before grouping and cannot contain aggregates; HAVING filters groups after aggregation. A condition without an aggregate belongs in WHERE, because it shrinks the input to GROUP BY. Example: WHERE status = 'paid' ... GROUP BY customer_id HAVING sum(total) >= 70. See GROUP BY and HAVING.

8 — Why is UNION ALL usually the better default than UNION, and how do set operations treat NULL? Important ​

Answer

Answer: UNION removes duplicates like DISTINCT, which costs a sort or hash and can merge rows that are legitimately identical; UNION ALL just appends. Set operations (and DISTINCT, GROUP BY) treat two NULLs as not distinct, so SELECT NULL UNION SELECT NULL returns one row. In PostgreSQL and MySQL INTERSECT is evaluated before UNION and EXCEPT; SQLite and Oracle evaluate set operators left to right with equal precedence (lab Q38). See set operations.

9 — How does a recursive CTE execute, and how do you stop it from looping forever? Important ​

Answer

Answer: The anchor member runs once; then the recursive member runs repeatedly against the rows produced by the previous iteration, and UNION ALL appends each iteration, until an iteration returns no rows. A cycle in the data never produces an empty iteration. Guard with a depth counter (WHERE depth < 20), a visited-path column, PostgreSQL's CYCLE clause, or MySQL's cte_max_recursion_depth. See recursive CTE.

10 — A scalar subquery returns two rows. What happens in PostgreSQL, MySQL and SQLite? Important ​

Answer

Answer: PostgreSQL raises SQLSTATE 21000 (cardinality_violation), MySQL raises error 1242 ("Subquery returns more than 1 row"), and SQLite silently uses the first row. A scalar subquery with no rows returns NULL everywhere. Make the subquery provably single-row (aggregate, LIMIT 1 with ORDER BY, or a unique key). See scalar subqueries.

11 — Where do NULLs appear in ORDER BY country on PostgreSQL, MySQL and SQLite, and how do you make it portable? Good to know ​

Answer

Answer: PostgreSQL sorts NULL as larger than any value (last for ASC, first for DESC); MySQL and SQLite sort it as smaller (first for ASC). Write NULLS FIRST / NULLS LAST on PostgreSQL, SQLite 3.30+ and Oracle; on MySQL use ORDER BY country IS NULL, country. See ORDER BY NULLS FIRST / LAST.

12 — How do you get the generated id of an inserted row in PostgreSQL, SQLite and MySQL from Go? Good to know ​

Answer

Answer: PostgreSQL and SQLite 3.35+ support INSERT ... RETURNING id, read with db.QueryRowContext(...).Scan(&id). MySQL 8.4 has no RETURNING; run ExecContext and call Result.LastInsertId() (the driver reads the value LAST_INSERT_ID() returns). See RETURNING.

13 — What is the difference between a semi-join and an inner join, and why does it matter? Must-know ​

Answer

Answer: An inner join returns one row per matching pair, with columns from both sides; a semi-join (EXISTS, IN) returns each left row at most once, with left columns only. "Customers with a paid order" as a join returns Ann and Cy twice (two paid orders each); patching that with DISTINCT costs a sort and can merge real duplicates. EXISTS states the question directly and planners execute it as a semi-join. See semi-join.

Glossary ​

TermMeaning
RelationA table (or query result) in the relational model: a set of tuples with the same attributes
TupleOne row of a relation
AttributeA named column of a relation
DomainThe set of values an attribute may take; SQL approximates it with types, constraints and CREATE DOMAIN
Relational algebraCodd's operators on relations (selection, projection, product, join, union, difference, rename) that SQL compiles to
ProjectionChoosing columns (π); SQL's SELECT list
SelectionChoosing rows by a predicate (σ); SQL's WHERE / HAVING
Cartesian productEvery row of one relation paired with every row of another; CROSS JOIN
Bag semanticsSQL tables allow duplicate rows (multisets), unlike mathematical relations
NULLMarker for a missing, unknown or inapplicable value; not a value, not '', not 0
Three-valued logicTRUE / FALSE / UNKNOWN; the logic SQL predicates use
UNKNOWNThe truth value of a comparison involving NULL; filters treat it as not TRUE
IS NULLThe only reliable test for NULL
IS DISTINCT FROMNULL-aware inequality that returns TRUE or FALSE; IS NOT DISTINCT FROM is NULL-aware equality
<=>MySQL's NULL-safe equal operator, equivalent to IS NOT DISTINCT FROM
COALESCEReturns its first non-NULL argument
NULLIFReturns NULL if its two arguments are equal, else the first
SELECT evaluation orderThe logical order FROM WHERE GROUP BY HAVING SELECT ORDER BY LIMIT (plus DISTINCT and set operations) that defines a query's result
DISTINCTRemoves duplicate output rows; NULLs count as equal
INNER JOINKeeps pairs of rows for which the join condition is TRUE
LEFT JOINInner join plus unmatched left rows padded with NULL
RIGHT JOINInner join plus unmatched right rows padded with NULL
FULL OUTER JOINInner join plus unmatched rows of both sides; not in MySQL
CROSS JOINCartesian product of two tables
NATURAL JOINJoin on equality of every column name the tables share; fragile under schema changes
USINGJOIN ... USING (col): equality on the named columns, one output column each
Self joinA table joined to itself under two aliases
Semi-joinReturns left rows that have at least one match, once each; EXISTS / IN
Anti-joinReturns left rows that have no match; NOT EXISTS
EXISTS / NOT EXISTSPredicates that are TRUE when a subquery returns at least one / no row
INTRUE if the left value equals some value of a list or subquery; NULL if no match and the list has a NULL
NOT IN with NULLThe trap: a NULL in the list makes NOT IN UNKNOWN for every row that does not match
Correlated subqueryA subquery that references columns of the outer query
Scalar subqueryA subquery used as a single value; error on more than one row (PostgreSQL 21000, MySQL 1242)
Derived tableA subquery in FROM with an alias
LATERALLets a FROM subquery reference earlier FROM items; SQL Server CROSS APPLY
GROUP BYFolds rows with equal grouping values into one row; NULLs form one group
HAVINGFilters groups after aggregation
Aggregate functionsFunctions such as count, sum, avg, min, max, string_agg that fold a group into one value
COUNT(*) vs COUNT(col)Rows vs non-NULL values of col
SUM AVG MIN MAXAggregates that ignore NULL inputs and return NULL over zero rows
GROUP BY with non-aggregated columnsSelecting a column that is neither grouped nor aggregated; legal only under functional dependence
ONLY_FULL_GROUP_BYMySQL sql_mode flag (on by default) that rejects non-dependent non-aggregated columns (error 1055)
Functional dependenceColumn B is determined by column A (e.g. by A's primary key), so grouping by A fixes B
ANY_VALUEMySQL and PostgreSQL 18 aggregate that returns an arbitrary value of the group
Bare columnSQLite's name for a non-aggregated, non-grouped column in an aggregate query
UNION / UNION ALLCombine results with / without removing duplicates
INTERSECTRows present in both results; binds tighter than UNION in PostgreSQL and MySQL, equal precedence (left to right) in SQLite and Oracle
EXCEPTRows of the first result not in the second; Oracle MINUS
CTECommon table expression, a named subquery introduced by WITH
WITHThe clause that defines CTEs before the main statement
Recursive CTEWITH RECURSIVE: anchor member plus a member that references the CTE itself
MATERIALIZEDCTE hint (PostgreSQL, SQLite 3.35+) forcing separate computation; NOT MATERIALIZED allows inlining (PostgreSQL ignores it for recursive or side-effecting CTEs; SQLite may still materialize)
ORDER BY NULLS FIRST LASTExplicit placement of NULLs in a sort; not in MySQL or SQL Server
LIMIT OFFSETNon-standard paging clauses (PostgreSQL, MySQL, SQLite); offset rows are still computed
FETCH FIRSTSQL:2008 standard limiting clause: OFFSET m ROWS FETCH FIRST n ROWS ONLY
CASEConditional expression; simple form compares with =, searched form takes predicates
String and date functionsEngine-specific functions such as substr, concat, date_trunc, DATE_FORMAT, strftime
Implicit castsAutomatic type conversion in comparisons and expressions; eager in MySQL, by affinity in SQLite, rare in PostgreSQL
Type affinitySQLite's per-column preferred storage class that drives conversions
Identifier quoting"name" (standard, PostgreSQL, SQLite) or `name` (MySQL) to use reserved words or exact case
Case sensitivityWhether names and string comparisons distinguish upper and lower case; set by folding rules and collations
CollationRules for comparing and sorting text
INSERT RETURNINGINSERT ... RETURNING cols returns the inserted rows (PostgreSQL, SQLite 3.35+, MariaDB)
UPDATE FROMUPDATE ... FROM other_table joins the target to other tables (PostgreSQL, SQLite 3.33+)
DELETE USINGDELETE FROM t USING other (PostgreSQL; MySQL multi-table form)
SQL standardISO/IEC 9075; current edition SQL:2023
PostgreSQL vs MySQL differencesThe dialect table on this page: division, ||, collation, NULL order, joins, RETURNING
SQLite differencesFlexible typing and permissive extensions; see the SQLite table
SQLSTATEFive-character standard error code (42703, 42803, 21000 ...)
Fan-outRow multiplication after joining a one-to-many relationship, which inflates aggregates

References ​

Built by Morteza Negahi