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 for | Go to |
|---|---|
| Every rule on one screen | Everything in one minute |
| Why SQL is declarative and set-based | Why SQL works this way |
| Codd, SEQUEL, SQL-86 to SQL:2023 | Where it comes from |
| The three tables every example uses | The lab schema |
| Relation, tuple, attribute, domain, relational algebra | The relational model in SQL terms |
NULL, UNKNOWN, IS NULL, IS DISTINCT FROM, COALESCE, NULLIF | NULL and three-valued logic |
Why an alias is unknown in WHERE | How a SELECT is evaluated |
| Inner, left, right, full, cross, natural, self joins | Joins |
EXISTS, IN, NOT IN with NULL, correlated, scalar, derived, LATERAL | Subqueries, semi-joins and anti-joins |
COUNT(*), HAVING, ONLY_FULL_GROUP_BY, functional dependence | Aggregation |
UNION, UNION ALL, INTERSECT, EXCEPT | Set operations |
WITH, MATERIALIZED, WITH RECURSIVE | Common table expressions |
NULLS FIRST, LIMIT, OFFSET, FETCH FIRST | Sorting and limiting |
CASE, string and date functions, casts, quoting | Expressions and types |
RETURNING, UPDATE ... FROM, DELETE ... USING | Changing data with queries |
| PostgreSQL vs MySQL vs SQLite vs the others | Dialect differences |
| Error codes and what the engine does with your query | Mechanics |
| Top-N per group, latest row, missing rows, Go and Laravel code | Solving the classic problems |
| Which construct for which question | Choosing a construct |
| Services, replicas, caches, sharding | In architecture |
| Run every example yourself | Lab |
| Test yourself, wrong beliefs, terms | Self-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).
| Step | Clause | In plain words | What it can see |
|---|---|---|---|
| 1 | FROM / JOIN | Build one big row set from the tables | Table columns |
| 2 | WHERE | Keep rows whose condition is TRUE | Table columns, no aggregates, no select aliases |
| 3 | GROUP BY | Fold rows into groups | Table columns and expressions |
| 4 | HAVING | Keep groups whose condition is TRUE | Grouped columns and aggregates |
| 5 | SELECT | Compute output expressions and aliases | Grouped columns, aggregates, window functions |
| 6 | DISTINCT | Remove duplicate output rows | Output columns |
| 7 | UNION / INTERSECT / EXCEPT | Combine query blocks | Output columns by position |
| 8 | ORDER BY | Sort | Output aliases and (outside set operations) input columns |
| 9 | LIMIT / OFFSET / FETCH FIRST | Cut the sorted result | Row positions |
Joins and subquery shapes.
| Construct | Keeps | Tiny example (lab data) | Watch out |
|---|---|---|---|
INNER JOIN | Matched pairs only | 8 customer-order rows, Eve missing | Multiplies rows per match |
LEFT JOIN | Matched pairs + unmatched left rows with NULLs | 9 rows, Eve with NULL order | A WHERE on the right table undoes it |
RIGHT JOIN | Matched pairs + unmatched right rows | Coupon SPRING with no order | MySQL docs recommend LEFT JOIN instead |
FULL OUTER JOIN | Everything from both sides | Orders without coupon and coupon without order | Not in MySQL 8.4 |
CROSS JOIN | Every combination (Cartesian product) | 5 customers × 3 coupons = 15 | Accidental when the ON is forgotten |
Semi-join (EXISTS, IN) | Left rows that have a match, once | Ann, Bob, Cy have a paid order | JOIN + DISTINCT is the slow imitation |
Anti-join (NOT EXISTS) | Left rows with no match | Eve has no order | NOT IN with NULL returns nothing |
| Scalar subquery | One value per outer row | Last order date per customer | More than one row: error (PostgreSQL, MySQL) |
| Derived table / CTE | A named intermediate result | Revenue per customer, then filter | CTE may or may not be materialized |
NULL rules.
| Expression | Result | Why |
|---|---|---|
NULL = NULL | NULL (UNKNOWN) | Unknown compared with unknown is unknown |
NULL IS NULL | TRUE | The only reliable NULL test |
NULL IS NOT DISTINCT FROM NULL | TRUE | NULL-aware equality (MySQL: <=>) |
TRUE OR NULL / FALSE AND NULL | TRUE / FALSE | The unknown side cannot change the answer |
3 NOT IN (1, NULL) | NULL | 3 <> NULL is UNKNOWN |
count(col) / count(*) | Ignores NULLs / counts rows | Aggregates skip NULL inputs |
sum(x) over zero rows | NULL, not 0 | Wrap with COALESCE(sum(x), 0) |
GROUP BY, DISTINCT, UNION | All NULLs form one group | Grouping uses "not distinct", not = |
ORDER BY x | PostgreSQL: NULLs last ascending; MySQL and SQLite: first | Use 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 steps | The engine picks them; the result must equal the logical definition |
| Correctness follows the code you wrote | Correctness follows set semantics and three-valued logic |
| Easy to reason about one record at a time | Easy to reason about whole sets, harder per row |
| Changing storage means changing code | Indexes and plans change without touching queries |
| N+1 round trips are natural | One 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
- "
WHERE x <> 'DE'returns every row that is not DE." It returns rows where the comparison is TRUE; rows withxNULL are UNKNOWN and disappear (lab Q02: Dee is missing). - "A
LEFT JOINalways keeps every left row." Only until aWHEREcondition on a right-table column throws the NULL-padded rows away again (lab Q08). - "A query without
ORDER BYreturns 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 whenORDER BYstates 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.
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.
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.id | name | country | referred_by | orders.id | customer | status | total | coupon_code | |
|---|---|---|---|---|---|---|---|---|---|
| 1 | Ann | DE | NULL | 1 | 1 | paid | 50 | WELCOME | |
| 2 | Bob | FR | 1 | 2 | 1 | paid | 20 | NULL | |
| 3 | Cy | DE | 2 | 3 | 1 | refunded | 15 | NULL | |
| 4 | Dee | NULL | 1 | 4 | 2 | paid | 99 | BF26 | |
| 5 | Eve | IR | NULL | 5 | 2 | pending | 5 | NULL | |
| 6 | 3 | paid | 40 | NULL | |||||
| 7 | 3 | paid | 60 | BF26 | |||||
| 8 | 4 | pending | 25 | NULL |
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 term | SQL term | Lab example | Notes |
|---|---|---|---|
| Relation | Table, view, query result | customers | A query result is also a relation, which is why queries nest |
| Tuple | Row | (4, 'dee@x.io', 'Dee', NULL, 1, ...) | SQL allows duplicate rows; the model does not |
| Attribute | Column | country | Referenced by name, never by position (except ORDER BY 1) |
| Domain | Data type + constraints | status IN ('pending','paid','refunded') | PostgreSQL CREATE DOMAIN makes a reusable one |
| Degree / cardinality | Number of columns / rows | 6 columns, 5 rows | |
| Candidate key / primary key | PRIMARY KEY, UNIQUE NOT NULL | customers.id, customers.email | What makes functional dependence work in GROUP BY |
| Foreign key | REFERENCES | orders.customer_id | Joins 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 operator | Symbol | SQL spelling | Lab example |
|---|---|---|---|
| Selection | σ | WHERE / HAVING | WHERE status = 'paid' |
| Projection | π | SELECT col, ... (plus DISTINCT for set semantics) | SELECT DISTINCT country |
| Cartesian product | × | CROSS JOIN, or FROM a, b without a condition | customers × coupons = 15 rows |
| Theta join / equi-join | ⋈θ | JOIN ... ON a.x = b.y | orders ⋈ customers |
| Natural join | ⋈ | NATURAL JOIN, JOIN ... USING (col) | customers ⋈ country_names |
| Union, intersection, difference | ∪ ∩ − | UNION, INTERSECT, EXCEPT | paid ∪ pending customers |
| Rename | ρ | AS alias | customers AS c |
| Semi-join / anti-join | ⋉ / ▷ | EXISTS / NOT EXISTS | customers with / without orders |
| Grouping and aggregation | γ | GROUP BY + aggregate functions | revenue 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
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."
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, droppedReal 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(*).
| Behaviour | PostgreSQL 18 | MySQL 8.4 | SQLite 3.54 | Oracle | SQL Server |
|---|---|---|---|---|---|
NULL = NULL | NULL | NULL | NULL | NULL | NULL: "Starting with SQL Server 2017 (14.x), ANSI_NULLS is always set to ON" (SET ANSI_NULLS OFF is deprecated) |
'' is NULL | No | No | No | Yes (VARCHAR2) | No |
| Booleans | Real boolean type, prints t/f | Comparisons "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 column | Distinct (many NULLs allowed); NULLS NOT DISTINCT option | Distinct | Distinct (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".
-- 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'")| Need | PostgreSQL | MySQL 8.4 | SQLite | SQL standard |
|---|---|---|---|---|
| Is missing | x IS NULL | x IS NULL | x IS NULL, x ISNULL | IS NULL |
| NULL-safe equal | x IS NOT DISTINCT FROM y | x <=> y | x IS y or IS NOT DISTINCT FROM (3.39+) | IS NOT DISTINCT FROM |
| NULL-safe not equal | x IS DISTINCT FROM y | NOT (x <=> y) | x IS NOT y | IS 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).
-- 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| Function | PostgreSQL | MySQL | SQLite | SQL Server | Oracle |
|---|---|---|---|---|---|
| First non-NULL | COALESCE | COALESCE, IFNULL(a,b) | COALESCE, IFNULL(a,b) | COALESCE, ISNULL(a,b) | COALESCE, NVL(a,b) |
| NULL if equal | NULLIF | NULLIF | NULLIF | NULLIF | NULLIF |
How a SELECT is evaluated
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:
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 outputThe 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.
| Clause | Can use select aliases? PostgreSQL | MySQL 8.4 | SQLite | SQL standard |
|---|---|---|---|---|
WHERE | No (42703) | No (1054) | Yes (extension) | No |
GROUP BY | Yes (extension) | Yes (extension) | Yes | No (input columns only) |
HAVING | No | Yes (extension) | Yes | No |
ORDER BY | Yes | Yes | Yes | Yes |
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.
SELECT DISTINCT country FROM customers ORDER BY country; -- lab Q06
-- NULL / DE / FR / IR (SQLite sorts NULL first; PostgreSQL would print it last)Joins
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.
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.
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 idiomReal 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.
| Product | LEFT JOIN | RIGHT JOIN | Notes |
|---|---|---|---|
| PostgreSQL | Yes | Yes | |
| MySQL 8.4 | Yes | Yes | Manual: "To keep code portable across databases, it is recommended that you use LEFT JOIN instead of RIGHT JOIN." |
| SQLite | Yes | Since 3.39.0 (2022-06-25) | Release notes: "Add (long overdue) support for RIGHT and FULL OUTER JOIN" |
| SQL Server | Yes | Yes | FROM 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).
-- 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-- 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.
| Form | Join condition | Output columns | Safe after schema changes? |
|---|---|---|---|
ON l.x = r.x | Explicit | Both l.x and r.x | Yes |
USING (x) | Equality on the named columns | One x | Yes |
NATURAL JOIN | Equality on every shared name | One per shared name | No |
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.
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 NULLFor 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.
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, CyAnti-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.
"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, 1Real 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.
| Form | NULL-safe | Typical plan | Use |
|---|---|---|---|
NOT EXISTS (correlated) | Yes | Anti join (PostgreSQL), antijoin (MySQL 8.0.17+) | Default choice |
LEFT JOIN ... WHERE r.key IS NULL | Yes (test a NOT NULL column of r) | Anti join or outer join + filter | When you also need columns of r elsewhere |
NOT IN (subquery) | No | MySQL 8.0.17+: antijoin, but "cannot in most cases be applied if the expressions being compared are nullable" | Only over NOT NULL columns |
EXCEPT | Yes (NULLs compare equal) | Set operation | Comparing 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.
-- 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").
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 100LATERAL 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."
-- 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):
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| Aggregate | Over NULL inputs | Over zero rows | Result type notes |
|---|---|---|---|
count(*) | Counts the row | 0 | bigint in PostgreSQL |
count(col) | Skips | 0 | |
count(DISTINCT col) | Skips | 0 | Sort or hash per group |
sum(col) | Skips | NULL | PostgreSQL: sum(int) → bigint, sum(bigint) → numeric |
SQLite total(col) | Skips | 0.0 ("sum() returns NULL but total() returns 0.0") | Always a floating-point value |
avg(col) | Skips (divides by non-NULL count) | NULL | PostgreSQL avg(int) → numeric; SQLite returns a float |
min / max | Skips | NULL | Work on text and dates too |
string_agg / group_concat | Skips | NULL | PostgreSQL string_agg, MySQL GROUP_CONCAT, SQLite group_concat / string_agg |
bool_and / every, bool_or | Skips | NULL | PostgreSQL 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."
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 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 descendingGROUP 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.
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".
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)| Operation | PostgreSQL | MySQL 8.4 | SQLite | Oracle | SQL Server |
|---|---|---|---|---|---|
UNION / UNION ALL | Yes | Yes | Yes | Yes | Yes |
INTERSECT | Yes, plus INTERSECT ALL | Yes: "INTERSECT was added in MySQL 8.0.31." | Yes (no ALL) | Yes, plus INTERSECT ALL | — |
EXCEPT | Yes, plus EXCEPT ALL | Yes: "EXCEPT was added in MySQL 8.0.31." | Yes (no ALL) | EXCEPT, EXCEPT ALL, MINUS, MINUS ALL (23 reference) | — |
| Parentheses around blocks | Yes | Yes | No (lab Q37: near "(": syntax error) | Yes | — |
| Precedence | INTERSECT first | INTERSECT first | Left 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.
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 70PostgreSQL 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
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.
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,5SEARCH 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.
| Engine | ASC default | DESC default | NULLS FIRST / NULLS LAST syntax |
|---|---|---|---|
| PostgreSQL | NULLs last | NULLs first | Yes |
| MySQL 8.4 | NULLs first | NULLs last | No: use ORDER BY col IS NULL, col |
| SQLite | NULLs first | NULLs last | Yes, since 3.30.0 |
| Oracle | NULLs last | NULLs first | Yes ("NULLS LAST is the default for ascending order") |
| SQL Server | NULLs first ("NULL values are treated as the lowest possible values") | NULLs last | No (not in the ORDER BY syntax) |
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.
| Engine | LIMIT n OFFSET m | OFFSET m ROWS FETCH FIRST n ROWS ONLY | Other |
|---|---|---|---|
| PostgreSQL | Yes | Yes (WITH TIES too) | |
| MySQL 8.4 | Yes, also LIMIT m, n | No | |
| SQLite | Yes, also LIMIT m, n | No (lab Q26: near "FETCH": syntax error) | |
| SQL Server | No | Yes, as part of ORDER BY | TOP (n) [WITH TIES] |
| Oracle | No | Yes (row_limiting_clause) |
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 ....
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+.
| Task | PostgreSQL 18 | MySQL 8.4 | SQLite 3.54 |
|---|---|---|---|
| Concatenate | a || b, concat(a, b) (ignores NULL) | CONCAT(a, b) (NULL if any NULL), CONCAT_WS | a || b, concat() |
| Length in characters | length(s), char_length(s) | CHAR_LENGTH(s) (LENGTH is bytes) | length(s) (characters for text) |
| Substring | substr(s, 1, 3), substring(s from 1 for 3) | SUBSTRING(s, 1, 3) | substr(s, 1, 3) |
| Position | strpos(s, '@'), position('@' in s) | LOCATE('@', s), INSTR(s, '@') | instr(s, '@') |
| Case-insensitive match | ILIKE, lower(a) = lower(b) | LIKE is case-insensitive with the default _ci collations | LIKE is case-insensitive for ASCII |
| Today / now | current_date, now() (transaction start) | CURDATE(), NOW() | date('now'), datetime('now') (UTC) |
| Add a month | d + interval '1 month' | DATE_ADD(d, INTERVAL 1 MONTH) | date(d, '+1 month') |
| Truncate to month | date_trunc('month', ts) | DATE_FORMAT(ts, '%Y-%m-01') | strftime('%Y-%m-01', ts) |
| Format | to_char(ts, 'YYYY-MM') | DATE_FORMAT(ts, '%Y-%m') | strftime('%Y-%m', ts) |
| Difference in days | d2 - d1 (integer for date) | DATEDIFF(d2, d1) | julianday(d2) - julianday(d1) |
-- 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-29SQLite 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):
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) 0PostgreSQL'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."
| Question | PostgreSQL | MySQL 8.4 | SQLite |
|---|---|---|---|
| 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 case | Folded to lower | Columns 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 case | Exact | Same rules as unquoted | Case-insensitive |
'Ann' = 'ann' | false (deterministic collations) | true with the default utf8mb4_0900_ai_ci collation | false (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.*(theWITH ( { 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
FROMclause. MySQL writes a multi-tableUPDATE 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 hasDELETE t1 FROM t1 JOIN t2 ...andDELETE FROM t1 USING t1 JOIN t2 ...; SQLite has neither (lab Q33:near "USING": syntax error) and uses a subquery.
-- 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-- 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.
| Topic | PostgreSQL 18 | MySQL 8.4 |
|---|---|---|
7 / 2 | 3 (integer division truncates) | decimal division (3/5 → 0.60); DIV for integer |
a || b | Concatenation | Logical OR (unless PIPES_AS_CONCAT) |
'Ann' = 'ann' | false | true (default _ai_ci collation) |
| Identifier quote | "x" | `x` (or "x" with ANSI_QUOTES) |
| NULL-safe equal | IS NOT DISTINCT FROM | <=> |
NULLs in ORDER BY ASC | Last | First |
NULLS FIRST/LAST | Yes | No |
FULL OUTER JOIN | Yes | No |
INTERSECT / EXCEPT | Yes (with ALL) | Since 8.0.31 |
LATERAL | Yes | Since 8.0.14 |
RETURNING | Yes | No (LAST_INSERT_ID()) |
UPDATE ... FROM / DELETE ... USING | Yes | Multi-table UPDATE ... JOIN / DELETE t FROM ... JOIN |
CTE MATERIALIZED hint | Yes | No |
| Data-modifying CTE | Yes | No |
| Non-aggregated column | 42803 unless functionally dependent on a PK | 1055 under ONLY_FULL_GROUP_BY (default); dependence via PK, unique NOT NULL or WHERE equality |
FETCH FIRST | Yes | No |
| Boolean results | boolean (t/f) | 1 / 0 / NULL |
| String to number comparison | Error or explicit cast | Silent 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).
| Topic | SQLite 3.54 | Since |
|---|---|---|
RIGHT JOIN, FULL OUTER JOIN | Yes | 3.39.0 (2022-06-25) |
IS [NOT] DISTINCT FROM | Yes (= IS NOT / IS) | 3.39.0 |
RETURNING | Yes | 3.35.0 (2021-03-12) |
AS [NOT] MATERIALIZED | Yes | 3.35.0 |
UPDATE ... FROM | Yes | 3.33.0 (2020-08-14) |
NULLS FIRST / NULLS LAST | Yes | 3.30.0 (2019-10-04) |
LATERAL, FETCH FIRST, DELETE ... USING | No | |
| Typing | Flexible typing with column affinity; STRICT tables opt out | |
Select alias in WHERE, GROUP BY, HAVING | Accepted (lab Q05, Q37) | |
| Bare columns in aggregates | Accepted (value from the min/max row) | |
| Double-quoted string literal | Accepted when no column matches (a documented quirk) | |
| Scalar subquery with many rows | First 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.
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 1242Two rewrites matter for semantics:
- Outer-join simplification. If a
WHEREcondition on the nullable side rejects NULLs (o.status = 'paid'), aLEFT JOINproduces the same result as anINNER JOIN, and planners convert it. That is the formal reason behind lab Q08's "Dee and Eve vanish". - Subquery to join.
EXISTS/INbecome semi-joins andNOT EXISTSbecomes 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 showsHash Semi Join/Hash Anti Joinnodes. Reading those nodes is taught in Query Planning and the cheatsheet.
Error codes you will meet Important
| Situation | PostgreSQL SQLSTATE | MySQL error | SQLite message (lab) |
|---|---|---|---|
| Syntax error | 42601 syntax_error | 1064 | near "FETCH": syntax error |
Unknown column / alias in WHERE | 42703 undefined_column | 1054 ER_BAD_FIELD_ERROR "Unknown column '%s' in '%s'" | accepted (alias) |
| Ambiguous column | 42702 ambiguous_column | 1052 ER_NON_UNIQ_ERROR "Column '%s' in %s is ambiguous" | ambiguous column name: id |
Non-aggregated column with GROUP BY | 42803 grouping_error | 1055 ER_WRONG_FIELD_WITH_GROUP "'%s' isn't in GROUP BY" | accepted (bare column) |
Aggregate in WHERE | 42803 grouping_error | 1111 ER_INVALID_GROUP_FUNC_USE "Invalid use of group function" | misuse of aggregate function sum() |
| Scalar subquery returns several rows | 21000 cardinality_violation | 1242 ER_SUBQUERY_NO_1_ROW "Subquery returns more than 1 row" | first row, no error |
| Derived table without alias | accepted | 1248 ER_DERIVED_MUST_HAVE_ALIAS | accepted |
| Division by zero | 22012 division_by_zero | SELECT: NULL; INSERT/UPDATE: warning or (with strict mode) error under ERROR_FOR_DIVISION_BY_ZERO | NULL (lab Q37) |
| Bad text to number cast | 22P02 invalid_text_representation | numeric context: '1a' converts to 1 | leading digits used (lab Q29) |
The knobs that change query semantics Important
| Knob | Product | Effect | Default |
|---|---|---|---|
sql_mode ONLY_FULL_GROUP_BY | MySQL | Rejects non-dependent bare columns | On in 8.4 |
sql_mode ANSI_QUOTES | MySQL | "x" becomes an identifier | Off |
sql_mode PIPES_AS_CONCAT | MySQL | || concatenates | Off |
sql_mode STRICT_TRANS_TABLES | MySQL | Bad values error instead of being adjusted | On |
lower_case_table_names | MySQL | Table-name case sensitivity | 0 Unix, 1 Windows, 2 macOS |
cte_max_recursion_depth | MySQL | Stops runaway recursive CTEs | 1000 ("By default, cte_max_recursion_depth has a value of 1000"); settable per statement with SET_VAR |
transform_null_equals | PostgreSQL | "When on, expressions of the form expr = NULL (or NULL = expr) are treated as expr IS NULL" | off |
standard_conforming_strings | PostgreSQL | "ordinary string literals ('...') treat backslashes literally" | on (since 9.1) |
Collation (COLLATE) | All | Equality and sort order of text | Per database / column |
PRAGMA case_sensitive_like | SQLite | LIKE case sensitivity ("by default 'a' LIKE 'A' is true") | off |
STRICT tables | SQLite | Rigid column types, "as of version 3.37.0 (2021-11-27)" | off (per table) |
Solving the classic problems
| Problem | Preferred solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Rows with no match (customers without orders) | NOT EXISTS | Correlated anti-join | NULL-safe, becomes an anti-join | Needs an index on the inner key |
| Rows with at least one match | EXISTS | Semi-join | No duplicates, stops at first match | |
| Count per parent including zero | LEFT JOIN + filter in ON + count(child.id) | Q08 | Keeps every parent | Fan-out if you join two child tables |
| Sum per parent including zero | COALESCE(sum(x), 0) | Q18 | Numbers instead of NULL | |
| Latest row per group | LATERAL ... ORDER BY ... LIMIT 1 (PostgreSQL, MySQL); correlated subquery in ON (SQLite) | Q35 | One index probe per parent | Window functions for whole sets |
| Top N per group | ROW_NUMBER() window, or LATERAL ... LIMIT n | Advanced SQL | ||
| Equality with nullable values | IS NOT DISTINCT FROM / <=> | Q03 | Two-valued | Spelling differs: MySQL only has <=> |
| Pivot / conditional totals | sum(CASE WHEN ... END), PostgreSQL FILTER | Q27 | Portable | One pass, wide queries get long |
| Hierarchy of unknown depth | WITH RECURSIVE + depth guard | Q24 | One statement | Cycles need guards |
| Reconcile two lists | FULL OUTER JOIN, or EXCEPT both ways | Q09, Q22 | Shows both sides' gaps | MySQL needs UNION ALL emulation |
| Read generated ids after insert | RETURNING (PostgreSQL, SQLite); LAST_INSERT_ID() (MySQL) | Q31 | One round trip | |
| Update from another table | UPDATE ... FROM / MySQL UPDATE ... JOIN | Q32 | Set-based, no loop | Duplicates 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
// 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
// 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:
// 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
}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/sqlcannot scan NULL intostringorint64(thebeforetest checks the error). Usesql.NullString/sql.NullInt64, a pointer (*string), or the genericsql.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 whycountry = $1needsIS NOT DISTINCT FROM. - Placeholders are driver syntax, not SQL. pgx uses
$1(README examplewhere 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 inschema/proves$1binds positionally withmodernc.org/sqlite. QueryRowContext(...).ScanonINSERT ... RETURNINGis the PostgreSQL and SQLite way to get a generated id; with MySQL useExecContextandResult.LastInsertId().- Aggregates come back as driver-specific types. The Go type a driver returns for a
numeric/NUMERICaggregate differs between drivers (the SQLite driver returnsfloat64orint64); theafterpackage converts to integer cents in SQL withCAST(ROUND(x * 100) AS INTEGER)so the Go type is stable; withoutROUND, SQLite turns 0.29 into 28 cents, because 0.29 * 100 is 28.999... as a float andCASTtruncates (lab Q38, testTestRevenueRoundsFractionalCents). Money belongs in integer cents ornumeric(see Schema Design). - Always close rows and check
rows.Err(); a query that fails mid-stream reports the error there, not fromNext().
Fixing the same bugs in Laravel
Before
<?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
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
whereNotInwith a closure isNOT IN (subquery)and has the NULL trap;whereNotExistswithwhereColumnis the anti-join. Both are Laravel 13 query builder methods (Illuminate\Database\Query\Builder).where('country', null)becomescountry is null, so the builder protects you;whereRaw('country = ?', [null])does not. For "equal, NULLs included" Laravel 13 haswhereNullSafeEquals: the docs say it compares "while treating two NULL values as equal", and the grammars emitis not distinct from(base grammar, used by PostgreSQL),<=>(MySQL) andis(SQLite).- Conditions on a left-joined table go into the join closure (
JoinClause::where), exactly likeON ... ANDin SQL. The docs: thewheremethods of theJoinClause"will compare the column against a value". joinLateral/leftJoinLateralbuildLATERALjoins; "Lateral joins are currently supported by PostgreSQL, MySQL >= 8.0.14, and SQL Server."unionAllkeeps duplicates;unionremoves them.- There is no CTE builder method in the documented query builder; use
DB::selectwith bindings (asreferralChaindoes) or a package. Eloquent relationship queries express the same questions:whereDoesntHaveadds "query constraints to your doesntHave queries" (the anti-join), andwithCountwill "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
| Question | Use | Avoid | Reason |
|---|---|---|---|
| "Parents with at least one child" | EXISTS | JOIN + DISTINCT | Semi-join, no fan-out |
| "Parents with no child" | NOT EXISTS | NOT IN over nullable columns | NULL makes NOT IN empty |
| "Every parent, with child data if any" | LEFT JOIN, filters in ON | Filters on the child in WHERE | WHERE undoes the outer join |
| "One value per row from elsewhere" | Scalar subquery or LATERAL ... LIMIT 1 | Joining a many-side then max() everywhere | Clearer, no fan-out |
| "Filter on an aggregate" | HAVING | Aggregate in WHERE | Aggregates exist after grouping |
| "Filter rows before grouping" | WHERE | HAVING without aggregates | Fewer rows reach GROUP BY |
| "Combine two result lists" | UNION ALL | UNION by habit | Dedup costs a sort or hash |
| "Rows in A not in B, whole rows" | EXCEPT | Long NOT EXISTS on many columns | NULLs compare equal in set operations |
| "Readable multi-step query" | CTE | Nested derived tables 4 levels deep | Same meaning; PostgreSQL inlines single-use CTEs |
| "Tree of unknown depth" | WITH RECURSIVE + guard | Application loop of queries | One round trip |
| "Paged list" | ORDER BY ... , id + keyset | Large OFFSET | Offset rows are still computed |
| "Equal, NULL included" | IS NOT DISTINCT FROM / <=> | a = b OR (a IS NULL AND b IS NULL) copies | Shorter, 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.
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 GoWhat 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 theGROUP BYresult. - Sharding by
customer_id: joins and aggregates within one customer stay local;GROUP BY countryacross all customers becomes scatter-gather: each shard computes a partial aggregate (sum,count) and the coordinator combines them.avgmust be shipped assumandcount,count(DISTINCT)cannot be combined from partial counts, andORDER BY ... LIMIT 10needs 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×
| Load | What changes | SQL technique |
|---|---|---|
| 1× (thousands of rows) | Nothing; correctness is the only concern | Right join kind, NOT EXISTS, COALESCE, explicit ORDER BY |
| 10× (millions) | Plans matter; indexes on join and filter columns | Same SQL, plus indexes (Indexing), keyset pagination, UNION ALL over UNION |
| 100× (billions, many services) | Aggregates precomputed, joins moved to read models | Summary 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:
.headers on
.mode column
.nullvalue NULLSetup. Paste the three CREATE TABLE statements from The lab schema, then the seed:
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:
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 EveExperiment 2: the outer join that turns inner. Run both and count rows:
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 2Experiment 3: NOT IN with NULL.
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 | 1Experiment 4: aggregates over NULLs and empty sets.
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: 1055Experiment 5: set operations and a recursive CTE.
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 EveExperiment 6: what SQLite accepts that PostgreSQL rejects.
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
| Belief | Reality |
|---|---|
x <> 'DE' returns every non-DE row | Rows where x is NULL are UNKNOWN and dropped; use IS DISTINCT FROM or add OR x IS NULL |
= NULL works if the column is NULL | It is never TRUE; use IS NULL |
NOT IN and NOT EXISTS are interchangeable | NOT IN returns no rows if the subquery yields a NULL |
A LEFT JOIN keeps every left row | Not if WHERE tests a right-table column; put that test in ON |
sum() of no rows is 0 | It is NULL; COALESCE(sum(x), 0) |
count(col) counts rows | It counts non-NULL values; count(*) counts rows |
| Rows come back in insertion or id order | No order without ORDER BY; ties are undefined too |
UNION is the default way to combine results | UNION deduplicates (costly, may merge real duplicates); prefer UNION ALL |
DISTINCT fixes a join returning too many rows | It hides fan-out; use EXISTS or aggregate before joining |
| The clauses execute in written order | The logical order is FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT; the physical plan is free |
| A CTE is always computed once | PostgreSQL inlines single-use CTEs unless MATERIALIZED; MySQL chooses merge or materialization |
MySQL lets you select any column with GROUP BY | ONLY_FULL_GROUP_BY is in the 8.4 default sql_mode |
NULLS LAST is standard everywhere | MySQL and SQL Server lack it; defaults differ per engine |
| Passing nil from Go matches NULL rows | col = $1 with nil is UNKNOWN; use IS NOT DISTINCT FROM $1 |
| SQLite behaves like PostgreSQL for tests | It accepts aliases in WHERE, bare columns, many-row scalar subqueries and loose types |
Cheat sheet
| Topic | Remember |
|---|---|
| Logical order | FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → set ops → ORDER BY → LIMIT |
| NULL test | IS NULL, never = NULL |
| NULL-safe equality | IS NOT DISTINCT FROM (PostgreSQL, SQLite 3.39+), <=> (MySQL) |
| Defaults | COALESCE(x, default); divide safely with x / NULLIF(y, 0) |
| Anti-join | NOT EXISTS; NOT IN only over NOT NULL columns |
| Semi-join | EXISTS, not JOIN + DISTINCT |
| Outer-join filter | Optional-side conditions in ON |
| Counting | count(*) rows, count(col) non-NULL, count(DISTINCT col) different |
| Empty aggregates | sum/avg/min/max of nothing is NULL; count is 0 (SQLite total(): 0.0) |
WHERE vs HAVING | Rows before grouping vs groups after |
| Non-aggregated columns | Group by the primary key, or aggregate; ANY_VALUE when arbitrary is fine |
| Set operations | UNION ALL by default; INTERSECT binds tighter in PostgreSQL/MySQL, but SQLite and Oracle go left to right; NULLs compare equal |
| CTEs | WITH for readability; MATERIALIZED to force once (PostgreSQL, SQLite) |
| Recursion | WITH RECURSIVE + depth or cycle guard |
| Sorting | Explicit NULLS FIRST/LAST (not in MySQL); end with a unique column |
| Paging | LIMIT/OFFSET (PostgreSQL, MySQL, SQLite), FETCH FIRST (standard); keyset for deep pages |
| Writes that return | RETURNING (PostgreSQL, SQLite 3.35+), LAST_INSERT_ID() (MySQL) |
| Portability | Test on the production engine; SQLite accepts what PostgreSQL rejects |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Relation | A table (or query result) in the relational model: a set of tuples with the same attributes |
| Tuple | One row of a relation |
| Attribute | A named column of a relation |
| Domain | The set of values an attribute may take; SQL approximates it with types, constraints and CREATE DOMAIN |
| Relational algebra | Codd's operators on relations (selection, projection, product, join, union, difference, rename) that SQL compiles to |
| Projection | Choosing columns (π); SQL's SELECT list |
| Selection | Choosing rows by a predicate (σ); SQL's WHERE / HAVING |
| Cartesian product | Every row of one relation paired with every row of another; CROSS JOIN |
| Bag semantics | SQL tables allow duplicate rows (multisets), unlike mathematical relations |
| NULL | Marker for a missing, unknown or inapplicable value; not a value, not '', not 0 |
| Three-valued logic | TRUE / FALSE / UNKNOWN; the logic SQL predicates use |
| UNKNOWN | The truth value of a comparison involving NULL; filters treat it as not TRUE |
| IS NULL | The only reliable test for NULL |
| IS DISTINCT FROM | NULL-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 |
| COALESCE | Returns its first non-NULL argument |
| NULLIF | Returns NULL if its two arguments are equal, else the first |
| SELECT evaluation order | The logical order FROM WHERE GROUP BY HAVING SELECT ORDER BY LIMIT (plus DISTINCT and set operations) that defines a query's result |
| DISTINCT | Removes duplicate output rows; NULLs count as equal |
| INNER JOIN | Keeps pairs of rows for which the join condition is TRUE |
| LEFT JOIN | Inner join plus unmatched left rows padded with NULL |
| RIGHT JOIN | Inner join plus unmatched right rows padded with NULL |
| FULL OUTER JOIN | Inner join plus unmatched rows of both sides; not in MySQL |
| CROSS JOIN | Cartesian product of two tables |
| NATURAL JOIN | Join on equality of every column name the tables share; fragile under schema changes |
| USING | JOIN ... USING (col): equality on the named columns, one output column each |
| Self join | A table joined to itself under two aliases |
| Semi-join | Returns left rows that have at least one match, once each; EXISTS / IN |
| Anti-join | Returns left rows that have no match; NOT EXISTS |
| EXISTS / NOT EXISTS | Predicates that are TRUE when a subquery returns at least one / no row |
| IN | TRUE 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 NULL | The trap: a NULL in the list makes NOT IN UNKNOWN for every row that does not match |
| Correlated subquery | A subquery that references columns of the outer query |
| Scalar subquery | A subquery used as a single value; error on more than one row (PostgreSQL 21000, MySQL 1242) |
| Derived table | A subquery in FROM with an alias |
| LATERAL | Lets a FROM subquery reference earlier FROM items; SQL Server CROSS APPLY |
| GROUP BY | Folds rows with equal grouping values into one row; NULLs form one group |
| HAVING | Filters groups after aggregation |
| Aggregate functions | Functions 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 MAX | Aggregates that ignore NULL inputs and return NULL over zero rows |
| GROUP BY with non-aggregated columns | Selecting a column that is neither grouped nor aggregated; legal only under functional dependence |
| ONLY_FULL_GROUP_BY | MySQL sql_mode flag (on by default) that rejects non-dependent non-aggregated columns (error 1055) |
| Functional dependence | Column B is determined by column A (e.g. by A's primary key), so grouping by A fixes B |
| ANY_VALUE | MySQL and PostgreSQL 18 aggregate that returns an arbitrary value of the group |
| Bare column | SQLite's name for a non-aggregated, non-grouped column in an aggregate query |
| UNION / UNION ALL | Combine results with / without removing duplicates |
| INTERSECT | Rows present in both results; binds tighter than UNION in PostgreSQL and MySQL, equal precedence (left to right) in SQLite and Oracle |
| EXCEPT | Rows of the first result not in the second; Oracle MINUS |
| CTE | Common table expression, a named subquery introduced by WITH |
| WITH | The clause that defines CTEs before the main statement |
| Recursive CTE | WITH RECURSIVE: anchor member plus a member that references the CTE itself |
| MATERIALIZED | CTE 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 LAST | Explicit placement of NULLs in a sort; not in MySQL or SQL Server |
| LIMIT OFFSET | Non-standard paging clauses (PostgreSQL, MySQL, SQLite); offset rows are still computed |
| FETCH FIRST | SQL:2008 standard limiting clause: OFFSET m ROWS FETCH FIRST n ROWS ONLY |
| CASE | Conditional expression; simple form compares with =, searched form takes predicates |
| String and date functions | Engine-specific functions such as substr, concat, date_trunc, DATE_FORMAT, strftime |
| Implicit casts | Automatic type conversion in comparisons and expressions; eager in MySQL, by affinity in SQLite, rare in PostgreSQL |
| Type affinity | SQLite'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 sensitivity | Whether names and string comparisons distinguish upper and lower case; set by folding rules and collations |
| Collation | Rules for comparing and sorting text |
| INSERT RETURNING | INSERT ... RETURNING cols returns the inserted rows (PostgreSQL, SQLite 3.35+, MariaDB) |
| UPDATE FROM | UPDATE ... FROM other_table joins the target to other tables (PostgreSQL, SQLite 3.33+) |
| DELETE USING | DELETE FROM t USING other (PostgreSQL; MySQL multi-table form) |
| SQL standard | ISO/IEC 9075; current edition SQL:2023 |
| PostgreSQL vs MySQL differences | The dialect table on this page: division, ||, collation, NULL order, joins, RETURNING |
| SQLite differences | Flexible typing and permissive extensions; see the SQLite table |
| SQLSTATE | Five-character standard error code (42703, 42803, 21000 ...) |
| Fan-out | Row multiplication after joining a one-to-many relationship, which inflates aggregates |
References
- E. F. Codd, "A Relational Model of Data for Large Shared Data Banks", CACM 1970 — https://www.seas.upenn.edu/~zives/03f/cis550/codd.pdf
- PostgreSQL 18: Concepts — https://www.postgresql.org/docs/18/tutorial-concepts.html
- PostgreSQL 18: Joins Between Tables — https://www.postgresql.org/docs/18/tutorial-join.html
- PostgreSQL 18: Aggregate Functions (tutorial) — https://www.postgresql.org/docs/18/tutorial-agg.html
- PostgreSQL 18: Table Expressions (joins,
LATERAL,GROUP BY) — https://www.postgresql.org/docs/18/queries-table-expressions.html - PostgreSQL 18: Select Lists — https://www.postgresql.org/docs/18/queries-select-lists.html
- PostgreSQL 18: Combining Queries — https://www.postgresql.org/docs/18/queries-union.html
- PostgreSQL 18: Sorting Rows — https://www.postgresql.org/docs/18/queries-order.html
- PostgreSQL 18: LIMIT and OFFSET — https://www.postgresql.org/docs/18/queries-limit.html
- PostgreSQL 18: WITH Queries — https://www.postgresql.org/docs/18/queries-with.html
- PostgreSQL 18: Comparison Functions and Operators — https://www.postgresql.org/docs/18/functions-comparison.html
- PostgreSQL 18: Conditional Expressions — https://www.postgresql.org/docs/18/functions-conditional.html
- PostgreSQL 18: Subquery Expressions — https://www.postgresql.org/docs/18/functions-subquery.html
- PostgreSQL 18: Aggregate Functions — https://www.postgresql.org/docs/18/functions-aggregate.html
- PostgreSQL 18: String Functions — https://www.postgresql.org/docs/18/functions-string.html
- PostgreSQL 18: Date/Time Functions — https://www.postgresql.org/docs/18/functions-datetime.html
- PostgreSQL 18: SELECT — https://www.postgresql.org/docs/18/sql-select.html
- PostgreSQL 18: INSERT — https://www.postgresql.org/docs/18/sql-insert.html
- PostgreSQL 18: UPDATE — https://www.postgresql.org/docs/18/sql-update.html
- PostgreSQL 18: DELETE — https://www.postgresql.org/docs/18/sql-delete.html
- PostgreSQL 18: Constraints — https://www.postgresql.org/docs/18/ddl-constraints.html
- PostgreSQL 18: Lexical Structure — https://www.postgresql.org/docs/18/sql-syntax-lexical.html
- PostgreSQL 18: Type Conversion Overview — https://www.postgresql.org/docs/18/typeconv-overview.html
- PostgreSQL 18: Error Codes — https://www.postgresql.org/docs/18/errcodes-appendix.html
- MySQL 8.4: SELECT — https://dev.mysql.com/doc/refman/8.4/en/select.html
- MySQL 8.4: JOIN — https://dev.mysql.com/doc/refman/8.4/en/join.html
- MySQL 8.4: MySQL Handling of GROUP BY — https://dev.mysql.com/doc/refman/8.4/en/group-by-handling.html
- MySQL 8.4: Detection of Functional Dependence — https://dev.mysql.com/doc/refman/8.4/en/group-by-functional-dependence.html
- MySQL 8.4: WITH (Common Table Expressions) — https://dev.mysql.com/doc/refman/8.4/en/with.html
- MySQL 8.4: Set Operations — https://dev.mysql.com/doc/refman/8.4/en/set-operations.html
- MySQL 8.0: INTERSECT — https://dev.mysql.com/doc/refman/8.0/en/intersect.html
- MySQL 8.4: Lateral Derived Tables — https://dev.mysql.com/doc/refman/8.4/en/lateral-derived-tables.html
- MySQL 8.4: Problems with NULL Values — https://dev.mysql.com/doc/refman/8.4/en/problems-with-null.html
- MySQL 8.4: Comparison Functions and Operators — https://dev.mysql.com/doc/refman/8.4/en/comparison-operators.html
- MySQL 8.4: Type Conversion in Expression Evaluation — https://dev.mysql.com/doc/refman/8.4/en/type-conversion.html
- MySQL 8.4: Identifier Case Sensitivity — https://dev.mysql.com/doc/refman/8.4/en/identifier-case-sensitivity.html
- MySQL 8.4: Server SQL Modes — https://dev.mysql.com/doc/refman/8.4/en/sql-mode.html
- MySQL 8.4: UPDATE — https://dev.mysql.com/doc/refman/8.4/en/update.html
- MySQL 8.4: DELETE — https://dev.mysql.com/doc/refman/8.4/en/delete.html
- MySQL 8.4: String Functions — https://dev.mysql.com/doc/refman/8.4/en/string-functions.html
- MySQL 8.4: Server Error Message Reference — https://dev.mysql.com/doc/mysql-errors/8.4/en/server-error-reference.html
- MySQL: Semijoin and antijoin transformations (8.4 URL redirects to the 8.0 page) — https://dev.mysql.com/doc/refman/8.4/en/semijoins.html
- MySQL 8.4: INSERT — https://dev.mysql.com/doc/refman/8.4/en/insert.html
- MySQL 8.0: EXCEPT — https://dev.mysql.com/doc/refman/8.0/en/except.html
- MySQL 8.4: Arithmetic Operators — https://dev.mysql.com/doc/refman/8.4/en/arithmetic-functions.html
- MySQL 8.4: Server Character Set and Collation — https://dev.mysql.com/doc/refman/8.4/en/charset-server.html
- MySQL 8.4: Flow Control Functions — https://dev.mysql.com/doc/refman/8.4/en/flow-control-functions.html
- MySQL 8.4: Date and Time Functions — https://dev.mysql.com/doc/refman/8.4/en/date-and-time-functions.html
- PostgreSQL 18: Mathematical Functions — https://www.postgresql.org/docs/18/functions-math.html
- PostgreSQL 18: Pattern Matching (
ILIKE) — https://www.postgresql.org/docs/18/functions-matching.html - PostgreSQL 18: Data Type Formatting Functions — https://www.postgresql.org/docs/18/functions-formatting.html
- PostgreSQL 18: Version and Platform Compatibility settings — https://www.postgresql.org/docs/18/runtime-config-compatible.html
- PostgreSQL 12.0 release notes (CTE inlining) — https://www.postgresql.org/docs/release/12.0/
- PostgreSQL 18 release notes (
RETURNING OLD/NEW) — https://www.postgresql.org/docs/18/release-18.html - SQLite: SELECT — https://sqlite.org/lang_select.html
- SQLite: WITH clause — https://sqlite.org/lang_with.html
- SQLite: NULL Handling in SQLite Versus Other Database Engines — https://sqlite.org/nulls.html
- SQLite: RETURNING — https://sqlite.org/lang_returning.html
- SQLite: UPDATE — https://sqlite.org/lang_update.html
- SQLite: Datatypes In SQLite — https://sqlite.org/datatype3.html
- SQLite: Quirks, Caveats, and Gotchas — https://sqlite.org/quirks.html
- SQLite: SQL Keywords (identifier quoting) — https://sqlite.org/lang_keywords.html
- SQLite: Release History — https://sqlite.org/changes.html
- SQLite: Core Functions — https://sqlite.org/lang_corefunc.html
- SQLite: PRAGMA statements (
case_sensitive_like) — https://sqlite.org/pragma.html - SQLite: STRICT Tables — https://sqlite.org/stricttables.html
- MariaDB: INSERT...RETURNING — https://mariadb.com/kb/en/insertreturning/
- Microsoft Learn: SET ANSI_NULLS — https://learn.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql?view=sql-server-ver16
- Microsoft Learn: UNIQUE and CHECK constraints — https://learn.microsoft.com/en-us/sql/relational-databases/tables/unique-constraints-and-check-constraints?view=sql-server-ver16
- Microsoft Learn: ORDER BY clause (OFFSET/FETCH, NULL ordering) — https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver16
- Microsoft Learn: FROM clause (APPLY, joins) — https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-ver16
- Microsoft Learn: OUTPUT clause — https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver16
- Microsoft Learn: TOP — https://learn.microsoft.com/en-us/sql/t-sql/queries/top-transact-sql?view=sql-server-ver16
- Microsoft Learn: ISNULL — https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql?view=sql-server-ver16
- Microsoft Learn: IIF — https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql?view=sql-server-ver16
- Oracle Database 23 SQL Reference: SELECT — https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/SELECT.html
- Oracle Database 23 SQL Reference: set operators — https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/The-UNION-ALL-INTERSECT-MINUS-Operators.html
- Oracle Database 23 SQL Reference: NVL — https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/NVL.html
- Oracle Database 23 SQL Reference: Data Types (BOOLEAN) — https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/Data-Types.html
- Wikipedia (secondary): SQL — https://en.wikipedia.org/wiki/SQL
- Wikipedia (secondary): SQL:2023 — https://en.wikipedia.org/wiki/SQL:2023
- Wikipedia (secondary): Relational algebra — https://en.wikipedia.org/wiki/Relational_algebra
- Markus Winand, "NULL in the Oracle Database" — https://use-the-index-luke.com/sql/where-clause/null
- Go 1.22 release notes (
sql.Null[T]) — https://go.dev/doc/go1.22 - Go source:
database/sql— https://go.dev/src/database/sql/sql.go - Laravel 13: Query Builder — https://laravel.com/docs/13.x/queries
- Laravel 13: Eloquent Relationships (
whereDoesntHave,withCount) — https://laravel.com/docs/13.x/eloquent-relationships - lib/pq
doc.go(placeholders) — https://raw.githubusercontent.com/lib/pq/master/doc.go - go-sql-driver/mysql README (
?placeholders,interpolateParams) — https://raw.githubusercontent.com/go-sql-driver/mysql/master/README.md - pgx README — https://raw.githubusercontent.com/jackc/pgx/master/README.md
- Laravel framework 13.x source: Query
Builderand grammars — https://raw.githubusercontent.com/laravel/framework/13.x/src/Illuminate/Database/Query/Builder.php