SQL Queries & Indexes Cheatsheet
Worked examples for GROUP BY and HAVING, composite index order, free ORDER BY, and whether an index is actually used, side by side for PostgreSQL 17/18 and MySQL 8.4 LTS (InnoDB).
How to use this page
- Find your query shape in the page map or the matrix. Each example gives the situation, the SQL, the index, the plan line that decides, and a Verdict.
- Every example runs on one schema. The theory is in Indexing, Query planning and Pagination. The commands are in the PostgreSQL and MySQL cheatsheets.
- Prove a verdict on your own data with
EXPLAINbefore you build or drop an index. Statistics, table size and versions can change the planner's choice.
Plan lines are what the documentation predicts; they were not executed. Only the node /
key/Extraline that decides the verdict is shown; costs and row counts are omitted on purpose.
Page map
| Section | Question it answers | Engines |
|---|---|---|
| Schema | Which tables and indexes do the examples assume? | PG, MySQL |
| Reading a plan | Which plan line tells me what happened? | PG, MySQL |
| GROUP BY and HAVING | Where does a filter go, and how does an index help grouping? | PG, MySQL |
| Composite indexes | Which queries can (tenant_id, status, created_at) serve? | PG, MySQL |
| Sort paths | When is ORDER BY free, and when does it sort? | PG, MySQL |
| Is the index used? | Why does my query skip the index I built? | PG, MySQL |
| Joins and subqueries | EXISTS, IN or JOIN? Which columns need an index? | PG, MySQL |
| Pagination | OFFSET or keyset, and which index? | PG, MySQL |
| Diagnostic queries | Which indexes are unused or missing? | PG, MySQL |
| Checklist | What should I check before CREATE INDEX? | both |
| Common errors | What does this error code mean? | PG, MySQL |
| From Go and Laravel | How do I see the plan from application code? | Go, PHP |
The schema every example uses
Every example uses three tables: customers, their orders, and order lines. tenant_id is on orders because almost every multi-tenant query starts with it.
-- PostgreSQL 17/18
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
country text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id bigint NOT NULL,
customer_id bigint NOT NULL REFERENCES customers (id),
status text NOT NULL, -- 'pending' | 'paid' | 'refunded'
total numeric(12,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE order_items (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id bigint NOT NULL REFERENCES orders (id),
sku text NOT NULL,
qty int NOT NULL,
price numeric(12,2) NOT NULL
);
CREATE INDEX orders_tenant_status_created ON orders (tenant_id, status, created_at);
CREATE INDEX orders_customer_id ON orders (customer_id); -- FKs are not indexed for you
CREATE INDEX order_items_order_id ON order_items (order_id);-- MySQL 8.4 (InnoDB): the same three tables; only the column types differ. Runs alone in an empty database.
CREATE TABLE customers (
id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
email varchar(255) NOT NULL,
country varchar(2) NOT NULL,
created_at datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
) ENGINE=InnoDB;
CREATE TABLE orders (
id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
tenant_id bigint NOT NULL,
customer_id bigint NOT NULL,
status varchar(16) NOT NULL,
total decimal(12,2) NOT NULL,
created_at datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
KEY orders_tenant_status_created (tenant_id, status, created_at),
KEY orders_customer_id (customer_id),
CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id)
) ENGINE=InnoDB;
CREATE TABLE order_items (
id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
order_id bigint NOT NULL,
sku varchar(64) NOT NULL,
qty int NOT NULL,
price decimal(12,2) NOT NULL,
KEY order_items_order_id (order_id),
CONSTRAINT fk_items_order FOREIGN KEY (order_id) REFERENCES orders (id)
) ENGINE=InnoDB;Seed data: 4 customers (ann@x.io and ANN@x.io are the same person) and 12 orders over October and November 2026, in tenants 1 and 2. The schema, the seed and every portable query on this page ran through sqlite3 :memory: (3.54.0), and every result shown matches that run. This proves the SQL and the results. It proves nothing about plans.
Reading a plan in 60 seconds
PostgreSQL. Run EXPLAIN (ANALYZE, BUFFERS) <query>. ANALYZE executes the statement, so wrap DML in BEGIN … ROLLBACK. On PostgreSQL 18, "The ANALYZE option implicitly enables the BUFFERS option". Read the tree from the deepest node upwards.
| Plan line | Means | Good or bad sign |
|---|---|---|
Seq Scan on orders + Filter: | Reads every page and checks each row | Fine on small tables or when most rows match; bad if few rows survive |
Index Scan using … on orders + Index Cond: | Walks the index, then fetches each heap row | Good for few rows; can return rows in index order |
Index Only Scan using … | Answers from the index (heap only for pages not all-visible) | Best case; check Heap Fetches |
Bitmap Index Scan → Bitmap Heap Scan | Collects row addresses, then reads pages in physical order | Medium selectivity; BitmapAnd/BitmapOr combine indexes |
Sort / Incremental Sort | Sorts everything / sorts within a presorted prefix | A Sort under Limit means the index did not give the order |
HashAggregate / sorted (group) aggregate | Groups by hashing / walks input already sorted by the group key | A sorted aggregate right above an index scan means the index gave the order; the exact node label varies, so read the node name your server prints |
Limit → index scan read backward | Reads the index from the end ("The index can also be scanned backward") and stops early | Free ORDER BY … DESC LIMIT n; the exact label varies |
Nested Loop / Hash Join / Merge Join | Join algorithm | See joins |
MySQL. EXPLAIN <query> prints one row per table. The columns that matter:
| Column | Read it as |
|---|---|
type | Access method. Best to worst: const → eq_ref → ref → range → index → ALL |
key | The index actually chosen (possible_keys lists the candidates) |
key_len | "enables you to determine how many parts of a multiple-part key MySQL actually uses" |
rows | "the number of rows MySQL believes it must examine"; an estimate for InnoDB |
filtered | Estimated percentage of rows that survive the table condition |
Extra | Using index (covering), Using index condition (ICP), Using filesort, Using temporary, Using index for group-by, Using index for skip scan, Backward index scan |
The manual: "If you want to make your queries as fast as possible, look out for Extra column values of Using filesort and Using temporary". EXPLAIN FORMAT=TREE prints the iterator tree. EXPLAIN ANALYZE (since 8.0.18) "runs a statement and produces EXPLAIN output along with timing", and it "always uses the TREE output format". Background: Query planning → MySQL.
GROUP BY and HAVING
WHERE filters rows, HAVING filters groups
Situation: you want paid revenue per customer, but only for customers above 110.
SELECT customer_id, sum(total) AS revenue
FROM orders
WHERE status = 'paid' -- row filter: runs before grouping
GROUP BY customer_id
HAVING sum(total) > 110 -- group filter: needs the aggregate
ORDER BY customer_id;
-- result: (1, 112) (3, 195)Verdict: a condition that needs no aggregate belongs in WHERE. PostgreSQL: "WHERE selects input rows before groups and aggregates are computed … whereas HAVING selects group rows after groups and aggregates are computed", and putting the restriction in WHERE "is more efficient". MySQL: "Do not use HAVING for items that should be in the WHERE clause". MySQL also says HAVING "is applied nearly last, just before items are sent to the client, with no optimization", and merges it into WHERE only "if you do not use GROUP BY or aggregate functions". Do not count on the engine to move a filter for you.
Customers with at least 3 paid orders in 30 days
Situation: loyalty report. The 30 days are counted back from 2026-11-29.
SELECT customer_id, count(*) AS paid_orders
FROM orders
WHERE status = 'paid' AND created_at >= '2026-10-30'
GROUP BY customer_id
HAVING count(*) >= 3;
-- result: (1, 3) (3, 3)
CREATE INDEX orders_status_created_cust ON orders (status, created_at, customer_id); -- optionalPG Index Only Scan using orders_status_created_cust on orders (then HashAggregate)
MySQL type: range key: orders_status_created_cust Extra: Using where; Using index; Using temporaryVerdict: the index narrows the WHERE (equality on status, then a range on created_at). It does not remove the grouping step, because the rows come out in created_at order, not customer_id order. MySQL: "The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive".
Duplicate finder
Situation: find emails that were stored twice with different case.
SELECT lower(email) AS email_norm, count(*) AS n
FROM customers
GROUP BY lower(email)
HAVING count(*) > 1;
-- result: (ann@x.io, 2)Verdict: it reads the whole table on purpose. Prevent the duplicates instead: PG CREATE UNIQUE INDEX ON customers (lower(email)), MySQL UNIQUE KEY ((lower(email))). See expression indexes.
Revenue per day: the function on the column
Situation: daily revenue for the first week of November.
-- kills the index on created_at: the WHERE wraps the column in a function
WHERE date(created_at) = '2026-11-05' -- MySQL DATE(); PG created_at::date
-- keeps it: a half-open range on the bare column, the function only in GROUP BY
SELECT date(created_at) AS day, sum(total) AS revenue -- PG: date_trunc('day', created_at)
FROM orders
WHERE status = 'paid' AND created_at >= '2026-11-01' AND created_at < '2026-11-08'
GROUP BY date(created_at)
ORDER BY day;
-- result: (2026-11-01, 50) (2026-11-02, 99) (2026-11-05, 100)Verdict: a function around the column in WHERE cannot use a plain B-tree on that column. A range on the bare column can. PostgreSQL builds a B-tree search only for "< <= = >= >" on an indexed column (plus BETWEEN, IN, IS NULL). An expression index is the only other way, and "All functions and operators used in an index definition must be 'immutable'". date_trunc on timestamptz fails that rule: "By default, truncation is done with respect to the current TimeZone setting".
Conditional counts: FILTER vs SUM(CASE)
Situation: a dashboard wants paid and total order counts per tenant in one query.
SELECT tenant_id,
count(*) FILTER (WHERE status = 'paid') AS paid_filter, -- PostgreSQL
sum(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_case, -- both engines
count(*) AS all_orders
FROM orders GROUP BY tenant_id;
-- result: (1, 6, 6, 8) (2, 4, 4, 4)Verdict: same answer, one pass over the rows. PostgreSQL: "If FILTER is specified, then only the input rows for which the filter_clause evaluates to true are fed to the aggregate function". The portable form is SUM(CASE …).
Non-aggregated columns: 42803 and 1055
Situation: a per-customer report also shows the email, and a careless edit groups by country instead.
SELECT c.id, c.email, count(o.id) AS orders -- legal: email depends on the PK c.id
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id;
-- result: (1, ann@x.io, 5) (2, bob@x.io, 3) (3, cy@x.io, 4) (4, ANN@x.io, 0)
SELECT c.country, c.email, count(*) FROM customers c GROUP BY c.country; -- illegal in bothVerdict: group by the primary key and you may select any column of that table. PostgreSQL: "A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column". Otherwise PostgreSQL raises 42803 grouping_error. MySQL, with ONLY_FULL_GROUP_BY (on by default), rejects such queries with ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column …. If you know the value is unique per group, write ANY_VALUE(col).
count(DISTINCT)
Situation: how many different customers bought in each tenant?
SELECT tenant_id, count(DISTINCT customer_id) AS buyers
FROM orders WHERE status = 'paid' GROUP BY tenant_id;
-- result: (1, 2) (2, 1)Verdict: exact, but it must see every qualifying row. MySQL's Loose Index Scan supports COUNT(DISTINCT) only when the query has no GROUP BY or DISTINCT of its own, and its other limits still apply (below).
HashAggregate vs sorted aggregate
Situation: order counts per tenant and status for an admin page.
SELECT tenant_id, status, count(*) FROM orders GROUP BY tenant_id, status;
-- result: (1, paid, 6) (1, pending, 1) (1, refunded, 1) (2, paid, 4)PG sorted aggregate (no Sort node) -> Index Only Scan using orders_tenant_status_created on orders
(or HashAggregate -> Seq Scan on orders, when hashing all rows is cheaper)
MySQL type: index key: orders_tenant_status_created Extra: Using indexVerdict: a B-tree whose leading columns are the GROUP BY keys can supply the rows already grouped. PostgreSQL's enable_group_by_reordering lets the planner put "GROUP BY keys sorted in the order of keys of a child node of the plan, such as an index scan". HashAggregate stays a valid choice ("hashed aggregation plan types"). MySQL needs "all GROUP BY columns reference attributes from the same index, and that the index stores its keys in order". Background: Aggregates.
MySQL loose index scan: Using index for group-by
Situation: last order time per tenant and status, on MySQL.
SELECT tenant_id, status, max(created_at) AS last_at
FROM orders GROUP BY tenant_id, status;
-- result: (1, paid, 2026-11-25 14:00) (1, pending, 2026-11-28 16:00) (1, refunded, 2026-11-21 08:00) (2, paid, 2026-11-12 10:00)MySQL type: range key: orders_tenant_status_created Extra: Using index for group-byVerdict: this reads a few keys per group, not every row. The conditions: one table; the GROUP BY "names only columns that form a leftmost prefix of the index"; the only aggregates are MIN()/MAX() on one column that "must immediately follow the columns in the GROUP BY"; any other index parts are equalities with constants; full column values (no prefix index). Add sum(total) and the shape is lost.
Latest row per group: window or DISTINCT ON
Situation: show each customer's most recent order.
-- both engines
SELECT customer_id, id, created_at
FROM (
SELECT customer_id, id, created_at,
row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn
FROM orders
) t
WHERE rn = 1;
-- result: (1, 4, 2026-11-21 08:00) (2, 7, 2026-11-28 16:00) (3, 10, 2026-11-12 10:00)
-- PostgreSQL only
SELECT DISTINCT ON (customer_id) customer_id, id, created_at
FROM orders
ORDER BY customer_id, created_at DESC, id DESC;
CREATE INDEX orders_cust_created ON orders (customer_id, created_at DESC, id DESC);Verdict: the index matching PARTITION BY / ORDER BY can stand in for the sort. PostgreSQL: "The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s)". The "first row" of each set is unpredictable unless ORDER BY makes the wanted row come first. Add id as a tie-breaker.
Composite indexes: order, prefix, range
The rule in PostgreSQL 11.3: "equality constraints on leading columns, plus any inequality constraints on the first column that does not have an equality constraint, will always be used to limit the portion of the index that is scanned". Columns further right "are checked in the index". MySQL says the same: "If the operator is >, <, >=, <=, !=, <>, BETWEEN, or LIKE, the optimizer uses it but considers no more key parts", and "MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index". Details: Indexing → composite.
The leftmost-prefix matrix for INDEX (tenant_id, status, created_at):
| Query shape | Narrows the scan? | Why | Fix |
|---|---|---|---|
tenant_id = 7 | Yes, 1 column | Leftmost prefix | none |
tenant_id = 7 AND status = 'paid' | Yes, 2 columns | Two leading equalities | none |
tenant_id = 7 AND status = 'paid' AND created_at BETWEEN a AND b | Yes, all 3 | Equality, equality, then one range | none |
tenant_id = 7 AND status IN ('paid','pending') | Yes, 2 columns | IN is a list of equalities (MySQL: "equality range comparisons") | none |
tenant_id = 7 AND created_at > X | tenant_id always; PG 18 may also use created_at via skip scan | status is unconstrained; before PG 18 (and in MySQL) created_at is only checked per entry (MySQL ICP: Using index condition) | (tenant_id, created_at) |
tenant_id = 7 AND status > 'p' AND created_at = X | tenant_id, status; PG 18 may skip within the range | The range on status ends the guaranteed narrowing; MySQL and PG 17 only check created_at | Reorder to (tenant_id, created_at, status) if this shape dominates |
status = 'paid' alone | No | Not a leftmost prefix; full index scan or skip scan | Skip scan only if tenant_id has few values; else (status, …) |
created_at > X alone | No | Two leading columns unconstrained | Own index on created_at |
tenant_id = 7 ORDER BY created_at | Narrows on tenant_id, but must sort | status sits between, so the order is not created_at | (tenant_id, created_at) (sort paths) |
tenant_id = 7 ORDER BY status, created_at LIMIT 20 | Yes, and no sort | Index order equals the requested order | none |
Equality first, then range
Situation: the query for paid orders of tenant 7 since Monday is slow on INDEX (tenant_id, created_at, status).
SELECT id, total FROM orders
WHERE tenant_id = 7 AND status = 'paid' AND created_at >= '2026-11-23';
CREATE INDEX orders_t_s_c ON orders (tenant_id, status, created_at); -- equality, equality, rangePG 17 wrong order (tenant_id, created_at, status): Index Cond: tenant_id and created_at; status only checked inside the range
PG 18 wrong order: may skip-scan over status values inside the range (planner's choice)
right order (tenant_id, status, created_at): Index Cond: all three, one contiguous slice
MySQL wrong order: key_len covers tenant_id + created_at; right order: key_len covers all threeVerdict: put the equality columns before the range column. MySQL and PostgreSQL 17 read every non-paid entry in the date range when the range sits in the middle. Read key_len to see how many key parts MySQL used. PostgreSQL 18 can soften this with a skip scan inside the range: "The skip scan optimization can also be applied selectively, during B-tree scans that have at least some useful constraints from the query predicate", and then "Index entries with c >= 77 will never need to be filtered at the table level, but it may or may not be profitable to skip over them within the index". The planner may or may not do this, so the equality-first index is still the dependable choice.
Skip scan when the leading column is missing
Situation: a report filters only on created_at, but the only index leads with low-cardinality status.
CREATE INDEX orders_status_created ON orders (status, created_at); -- status has 3 values
SELECT status, created_at FROM orders WHERE created_at >= '2026-11-23';PG 18 Index Only Scan using orders_status_created on orders (skip scan: one descent per status value)
MySQL type: range key: orders_status_created Extra: Using where; Using index for skip scanVerdict: this only pays off when the leading column has few distinct values. PostgreSQL 18 (release notes: "Allow skip scans of btree indexes"): "This approach is generally only taken when there are so few distinct x values that the planner expects the scan to skip over most of the index". MySQL 8.4 adds strict conditions: "The query references only one table", "The query does not use GROUP BY or DISTINCT", "The query references only columns in the index", and "There must be a range condition on C". SELECT * on this table disqualifies the MySQL skip scan. See Indexing → skip scan.
Covering: INCLUDE vs trailing column
Situation: a tenant's order list needs only created_at and total, and the heap lookups dominate.
-- PostgreSQL: payload column, not part of the search key
CREATE INDEX orders_tenant_created_inc ON orders (tenant_id, created_at) INCLUDE (total);
-- MySQL: add it as a trailing key part (InnoDB already stores the PK in every secondary index)
CREATE INDEX orders_tenant_created_total ON orders (tenant_id, created_at, total);
SELECT created_at, total FROM orders WHERE tenant_id = 7 AND created_at >= '2026-11-01';PG Index Only Scan using orders_tenant_created_inc on orders
MySQL type: range key: orders_tenant_created_total Extra: Using where; Using indexVerdict: covered: InnoDB needs no clustered-index lookup. PostgreSQL skips the heap only for all-visible pages. PostgreSQL: the query "must reference only columns stored in the index". For each row it then checks the visibility map: "If it's set, the row is known visible and so the data can be returned with no further work. If it's not set, the heap entry must be visited to find out whether it's visible". So the scan "will be a win only if a significant fraction of the table's heap pages have their all-visible map bits set". Watch Heap Fetches in EXPLAIN ANALYZE, and let (auto)VACUUM keep the map current. MySQL Using index: "retrieved from the table using only information in the index tree". In InnoDB "each record in a secondary index contains the primary key columns for the row", so id is covered for free. See Indexing → covering.
Which index wins, and which one is redundant
- Several candidates: MySQL "normally uses the index that finds the smallest number of rows (the most selective index)". PostgreSQL compares estimated costs from statistics (selectivity).
(a)next to(a, b)is redundant. On(col1, col2, col3)"you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3)". Drop(a)unless it is unique or much smaller for a hot index-only query.(b, a)is not redundant next to(a, b). It servesb =lookups, which(a, b)cannot narrow.- MySQL lists candidates in
sys.schema_redundant_indexes(diagnostics).
Sort paths: when ORDER BY is free
Newest 20 orders
Situation: an admin feed shows the 20 newest orders.
SELECT id, created_at FROM orders ORDER BY created_at DESC LIMIT 20;
CREATE INDEX orders_created ON orders (created_at);no index PG: Limit -> Sort -> Seq Scan MySQL: type: ALL Extra: Using filesort
index PG: Limit -> index scan on orders_created, read backward (no Sort node)
MySQL: type: index key: orders_created Extra: Backward index scan; Using indexVerdict: with the index, the sort is free and the scan stops after 20 rows. PostgreSQL: "if there is an index matching the ORDER BY, the first n rows can be retrieved directly, without scanning the remainder at all". Without one, "an explicit sort will have to process all the data to identify the first n rows". MySQL: "If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause are selected". Here SELECT lists only indexed columns. MySQL's Backward index scan is "Shown together with Using index".
Filter on one column, sort on another
Situation: a tenant's newest 20 orders, and the only composite index is (tenant_id, status, created_at).
SELECT id, created_at, total FROM orders
WHERE tenant_id = 7 ORDER BY created_at DESC LIMIT 20;
CREATE INDEX orders_tenant_created ON orders (tenant_id, created_at);only (tenant_id, status, created_at) PG: Limit -> Sort -> Index Scan using orders_tenant_status_created
MySQL: type: ref key: orders_tenant_status_created Extra: Using filesort
with (tenant_id, created_at) PG: Limit -> index scan on orders_tenant_created, read backward (no Sort)
MySQL: type: ref key: orders_tenant_created (no Using filesort)Verdict: (tenant_id, created_at) serves it. (tenant_id, status, created_at) does not, because status is between. MySQL: "key_part1 is constant, so all rows accessed through the index are in key_part2 order". Unused parts of the index must be "constants in the WHERE clause". A WHERE on one index with ORDER BY on another gives Using filesort: "The index used to fetch the rows differs from the one used in the ORDER BY".
Mixed directions
Situation: a tenant view groups orders by status ascending, newest first inside each status.
SELECT id FROM orders WHERE tenant_id = 7 ORDER BY status ASC, created_at DESC;
CREATE INDEX orders_t_status_cdesc ON orders (tenant_id, status, created_at DESC); -- PG and MySQL 8.4plain (tenant_id, status, created_at) PG: Sort or Incremental Sort MySQL: Extra: Using filesort
mixed (…, status, created_at DESC) PG: Index Scan using orders_t_status_cdesc (no Sort)
MySQL: key: orders_t_status_cdesc, no Using filesortVerdict: mixed ASC/DESC needs an index declared with the same mix (or its exact mirror). PostgreSQL: there is "no way to get that ordering from a plain index, but it is possible if the index is defined as (x ASC, y DESC) or (x DESC, y ASC)". MySQL 8.4: "DESC in an index definition is no longer ignored but causes storage of key values in descending order", and "the index must have the same homogeneity, but need not have the same actual direction".
Incremental Sort (PostgreSQL)
Situation: orders sorted by customer and then date, with only the single-column customer_id index.
SELECT id FROM orders ORDER BY customer_id, created_at LIMIT 50; -- only orders_customer_id existsPG Limit -> Incremental Sort (Presorted Key: customer_id) -> Index Scan using orders_customer_id
MySQL Extra: Using filesortVerdict: a partial win: the index gives the first key, and only the rows inside each group get sorted. "sorting incrementally allows returning tuples before the entire result set has been sorted, which particularly enables optimizations with LIMIT queries" (enable_incremental_sort, default on). An index on (customer_id, created_at) removes the sort completely.
NULL placement
| Engine | Default for an ascending B-tree / ORDER BY x | Breaks the free sort |
|---|---|---|
| PostgreSQL | "ascending order with nulls last"; a backward scan gives DESC NULLS FIRST | ORDER BY x NULLS FIRST on a default index: declare (x NULLS FIRST) |
| MySQL | "NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC" | NULLs last via ORDER BY x IS NULL, x: an expression, so Using filesort ("ORDER BY with an expression that includes terms other than the index column name") |
DISTINCT and GROUP BY reuse the order, expressions break it
SELECT DISTINCT tenant_id, status FROM orderscan read the composite index in order. MySQL: "In most cases, a DISTINCT clause can be considered as a special case of GROUP BY", but "DISTINCT combined with ORDER BY needs a temporary table in many cases".ORDER BY lower(email),ORDER BY total * 1.2, or an alias that hides an expression (MySQL: aliasaforABS(a)means "the index on t1.a cannot be used") gives a sort.- A different collation breaks the match. PostgreSQL: "An index can support only one collation per index column", and an index on the column's collation "cannot accelerate queries that involve some other collation". Build
(email COLLATE "C")or use an operator class. ORDER BY random()always sorts every row: no index stores that order.
Is the index used? The matrix
Every row assumes a plain B-tree on the column in question, under the schema above. Prove each case with EXPLAIN.
| Query shape | B-tree on the column: used? | Why | Fix |
|---|---|---|---|
lower(email) = 'ann@x.io' | No | The index stores email, the query compares lower(email) | Expression index on lower(email) (MySQL ((lower(email)))) |
date(created_at) = '2026-11-05' | No | Function on the column | Half-open range on the bare column |
created_at + interval '1 day' > now() | No | Arithmetic on the column side | Move it: created_at > now() - interval '1 day' |
total * 1.1 > 100 | No | Same: expression, not the column | total > 100 / 1.1 |
PG bigint_col = '42' | Yes | The quoted literal is type unknown and is taken as bigint | none |
MySQL varchar_col = 42 | No | "For comparisons of a string column with a number, MySQL cannot use an index on the column" | Compare with '42' |
email LIKE 'ann%' | Yes (range) | Constant pattern anchored at the start | PG non-C locale: text_pattern_ops |
email LIKE '%x.io' | No | Leading wildcard: no prefix to seek | Index the reversed string and search a prefix (PG expression index, MySQL generated column); PG also pg_trgm GIN |
tenant_id = 1 OR customer_id = 3 | Two indexes combined | One index cannot take an OR across columns | PG BitmapOr; MySQL index_merge, Using union(...) |
status IN ('paid','pending') | Yes | IN is a set of equalities | none |
status <> 'paid' / NOT IN (…) | Usually no | PG: <> is not a B-tree search operator; MySQL can build "two intervals" but they cover most rows | Partial index on the rare values |
shipped_at IS NULL | Yes | Both engines index NULLs (MySQL: same optimization as = constant) | PG partial WHERE shipped_at IS NULL if rare |
status = 'paid' on 90% of rows | No, correctly | Reading most of the table sequentially is cheaper | none; index the rare values |
| Any filter on a 100-row table | No, correctly | One page beats an index descent | none |
| Fresh bulk load, old stats | Maybe wrong plan | Estimates come from ANALYZE | ANALYZE orders; / ANALYZE TABLE orders; |
Expression index on lower(email), query upper(email) = | No | The expression must match | Same expression in query and index |
Partial WHERE status = 'pending', query status = $1 | No (generic plan) | "parameterized query clauses do not work with a partial index" | Literal in SQL, or a full index |
OFFSET 100000 LIMIT 20 | Yes, but reads 100,020 entries | Skipped rows are still computed | Keyset |
JSONB @> containment | Only with GIN | GIN supports @>, B-tree does not | USING GIN (doc) or jsonb_path_ops |
JSONB doc ->> 'sku' = 'A' | Not with a GIN on doc | The operator is not on the indexed column | Expression index on (doc ->> 'sku') |
MySQL join of utf8mb4 column to latin1 column | No | Different character sets "precludes use of an index" | Same charset (and collation) on both sides |
id::text = $1 (cast on the column) | No | Cast is a function on the column | Cast the parameter: id = $1::bigint |
ORDER BY random() LIMIT 1 | No | Sort on a value no index stores | Sample by key range or TABLESAMPLE |
-- PostgreSQL fixes for the matrix rows above
CREATE INDEX customers_email_lower ON customers (lower(email));
CREATE INDEX customers_email_pattern ON customers (email text_pattern_ops); -- LIKE 'abc%' in a non-C locale
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX customers_email_trgm ON customers USING gin (email gin_trgm_ops); -- LIKE '%abc'
CREATE INDEX orders_pending ON orders (created_at) WHERE status = 'pending'; -- rare value only
CREATE INDEX customers_email_rev ON customers (reverse(email) text_pattern_ops); -- suffix search as a prefix
SELECT id FROM customers WHERE reverse(email) LIKE reverse('x.io') || '%'; -- matches the indexed expression
-- MySQL 8.4
CREATE INDEX customers_email_lower ON customers ((lower(email)));
ALTER TABLE customers
ADD COLUMN email_rev varchar(255) AS (REVERSE(email)) VIRTUAL,
ADD INDEX customers_email_rev (email_rev); -- index on a virtual generated column
SELECT id FROM customers WHERE email_rev LIKE CONCAT(REVERSE('x.io'), '%');Suffix search, why it works: PostgreSQL reverse "Reverses the order of the characters in the string". MySQL REVERSE(str) "Returns the string str with the order of the characters reversed". The reversed suffix becomes an anchored prefix, which the B-tree serves ("anchored to the beginning of the string"; MySQL: a LIKE argument that "does not start with a wildcard character"). In MySQL, "InnoDB supports secondary indexes on virtual generated columns". Do not reach for FULLTEXT here: it matches words, not suffixes. Its parser splits on delimiters such as ". (period)", and "The default minimum length of words that are found by full-text searches is three characters for InnoDB search indexes", so x and io are not even indexed.
-- JSONB (PostgreSQL): containment uses GIN, a key extraction needs its own expression index
CREATE INDEX events_doc_gin ON events USING gin (doc);
SELECT id FROM events WHERE doc @> '{"sku": "A"}'; -- Bitmap Index Scan on events_doc_gin
CREATE INDEX events_doc_sku ON events ((doc ->> 'sku'));
SELECT id FROM events WHERE doc ->> 'sku' = 'A'; -- Index Scan using events_doc_skuDoc sentences behind the matrix:
- Pattern match (PG): a B-tree serves
LIKE"if the pattern is a constant and is anchored to the beginning of the string — for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar'". MySQL: a range needs aLIKEargument that "does not start with a wildcard character". pg_trgm indexes "support trigram-based index searches for LIKE, ILIKE, ~, ~* and = queries". OR(PG): "a query like WHERE a = 5 OR b = 6 could not directly use the index", but the system "can form AND and OR conditions across several index scans". MySQL Index Merge "retrieves rows with multiple range scans and merges their results into one".- Small tables (PG 11.12): "the 100 rows probably fit within a single disk page, and there is no plan that can beat sequentially fetching 1 disk page". MySQL: "When a query needs to access most of the rows, reading sequentially is faster than working through an index".
- Statistics:
pg_statisticentries "are always approximate even when freshly updated". "Always run ANALYZE first". MySQLANALYZE TABLE"performs a key distribution analysis". - Partial index: "a partial index can be used in a query only if the system can recognize that the WHERE condition of the query mathematically implies the predicate of the index".
- JSONB: "The default GIN operator class for jsonb supports queries with … the containment operator @>". For
jdoc -> 'tags' ? 'qui'"the index could not be used … because though the operator ? is indexable, it is not applied directly to the indexed column".
Joins and subqueries
EXISTS, IN, JOIN
Situation: list the customers who have at least one paid order.
SELECT c.id FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid');
SELECT id FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE status = 'paid');
-- both: 1, 2, 3 (a plain JOIN returns customer 1 four times, once per paid order, unless you add DISTINCT)
SELECT id FROM customers WHERE id NOT IN (1, NULL); -- returns nothingVerdict: EXISTS and IN (subquery) are semi-joins: one row per customer, and both engines plan them as joins. MySQL: "A semijoin is a preparation-time transformation that enables multiple execution strategies such as table pullout, duplicate weedout, first match, loose scan, and materialization" (8.0 manual page). Prefer NOT EXISTS to NOT IN. PostgreSQL: if "at least one right-hand row yields null, the result of the NOT IN construct will be null, not true".
Index the foreign key
Situation: deleting a customer, or JOIN orders ON orders.customer_id = c.id, scans orders.
Verdict: PostgreSQL does not index the referencing column for you: "the declaration of a foreign key constraint does not automatically create an index on the referencing columns", and a DELETE on the parent "will require a scan of the referencing table". MySQL creates it: "Such an index is created on the referencing table automatically if it does not exist." Build orders (customer_id) in PostgreSQL. The diagnostic query lists the missing ones.
N+1 vs one query
Situation: an order page loads its lines one order at a time.
-- N+1: the app runs this once per order on the page
SELECT * FROM order_items WHERE order_id = $1;
-- one round trip instead
SELECT * FROM order_items WHERE order_id = ANY($1); -- PG, $1 = bigint[]
SELECT * FROM order_items WHERE order_id IN (?, ?, ?); -- MySQL / Laravel ->with('items')
-- top 3 lines per order (LATERAL)
SELECT o.id, i.sku FROM orders o
CROSS JOIN LATERAL (SELECT sku FROM order_items WHERE order_id = o.id ORDER BY price DESC LIMIT 3) i
WHERE o.tenant_id = 7;Verdict: each version needs order_items (order_id). Without it, every probe is a full scan. More: ORM pitfalls → N+1.
Join algorithms
| Algorithm | PostgreSQL | MySQL 8.4 | Index that helps |
|---|---|---|---|
| Nested loop | Nested Loop, inner side probed per outer row | Default with a usable index on the join column | Index on the inner join column |
| Hash join | Hash Join + Hash child | "employs hash joins whenever possible" for equi-joins without a usable index | None needed; indexes for single-table filters still help |
| Merge join | Merge Join, "requires its input data to be sorted on the join keys" | Not offered (see Query planning → joins) | B-tree on both join keys |
| Block nested loop | n/a | Gone: "Beginning with MySQL 8.0.20, support for block nested loop is removed" (hash join since 8.0.18) | n/a |
Background: Query planning → joins.
Pagination
Situation: tenant 1's order list, 3 per page, newest first; page 2 starts after order 4 (2026-11-21 08:00).
-- OFFSET: page 2 of tenant 1, 3 per page
SELECT id, created_at FROM orders WHERE tenant_id = 1
ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 3;
-- result: (3, 2026-11-20 12:00) (2, 2026-11-10 09:00) (5, 2026-11-02 11:00)
-- keyset, PostgreSQL: row-value comparison after the last row of page 1 (2026-11-21 08:00, id 4)
SELECT id, created_at FROM orders
WHERE tenant_id = 1 AND (created_at, id) < ('2026-11-21 08:00:00', 4)
ORDER BY created_at DESC, id DESC LIMIT 3;
-- same 3 rows
-- keyset, MySQL: the expanded form
SELECT id, created_at FROM orders
WHERE tenant_id = 1
AND (created_at < '2026-11-21 08:00:00' OR (created_at = '2026-11-21 08:00:00' AND id < 4))
ORDER BY created_at DESC, id DESC LIMIT 3;
-- same 3 rows
CREATE INDEX orders_tenant_created_id ON orders (tenant_id, created_at, id);PG Limit -> index scan on orders_tenant_created_id, read backward Index Cond: tenant_id and ROW(created_at, id) < ROW(...)
MySQL type: range key: orders_tenant_created_id Extra: Using where; Backward index scan; Using indexVerdict: keyset reads only the page. OFFSET reads and discards every skipped row. PostgreSQL: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient". For row values, "the row elements are compared left-to-right, stopping as soon as an unequal or null pair of elements is found". MySQL: with WHERE c1=1 AND (c2,c3) > (1,1) "the optimizer uses only c1 (key_len=4…)", while the expanded form uses all three. Hence: "avoid mixing row constructors with AND/OR expressions. Use one or the other". Always end ORDER BY with a unique column. MySQL: rows with equal sort values come back in an order that "is nondeterministic with respect to the nonordered columns". More: Pagination → keyset, row values.
Diagnostic queries
-- PostgreSQL: indexes never scanned since the last stats reset (keep unique/PK ones)
SELECT s.schemaname, s.relname AS table_name, s.indexrelname AS index_name,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS size, s.idx_scan, s.last_idx_scan
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0 AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC;-- PostgreSQL: foreign keys whose first column is not the first column of any index
SELECT c.conrelid::regclass AS table_name, c.conname, a.attname AS fk_column
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
AND NOT EXISTS (SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]);-- PostgreSQL: top 10 statements by total execution time (needs pg_stat_statements)
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms,
rows, left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;-- PostgreSQL: what the planner knows about one column
SELECT n_distinct, null_frac, most_common_vals, most_common_freqs, correlation
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';-- MySQL 8.4 (sys schema / performance_schema)
SELECT * FROM sys.schema_unused_indexes WHERE object_schema = 'shop';
SELECT table_name, redundant_index_name, redundant_index_columns,
dominant_index_name, sql_drop_index
FROM sys.schema_redundant_indexes WHERE table_schema = 'shop';
SELECT query, exec_count, no_index_used_count
FROM sys.statements_with_full_table_scans LIMIT 10;
SELECT object_name, index_name, count_star, count_read, count_write
FROM performance_schema.table_io_waits_summary_by_index_usage
WHERE object_schema = 'shop' ORDER BY count_star DESC;sys.schema_unused_indexes "is most useful when the server has been up and processing long enough that its workload is representative". In table_io_waits_summary_by_index_usage, "A value of NULL means that table I/O used no index". More: Indexing → unused, duplicates.
Before you add an index
- Run
EXPLAIN (ANALYZE, BUFFERS)/EXPLAIN ANALYZEon real data. Tiny test data makes every plan aSeq Scan. - Run
ANALYZEfirst: "Examining an application's index usage without having run ANALYZE is therefore a lost cause". - Can an existing index be extended (add a trailing column,
INCLUDE) instead of adding a new one? - Column order: equality columns, then one range or sort column. No more than three columns without a reason: "Indexes with more than three columns are unlikely to be helpful unless the usage of the table is extremely stylized".
- Does the
WHEREwrap the column in a function, cast, or arithmetic? Fix the query before you add an index. - Is the value rare? Index only the rare values (partial index in PG).
- Does
ORDER BY … LIMITmatch the index order and direction, including NULL placement? - Write cost: every index is maintained on every write; "Index expressions are relatively expensive to maintain" (write amplification).
- Build online on a live table: PG
CREATE INDEX CONCURRENTLY; MySQL options in Indexing → live table. - After a week of traffic, check the unused-index views and drop what nothing uses.
Common errors
| Code | Message | Cause | Fix |
|---|---|---|---|
PG 42803 | grouping_error | Ungrouped column in SELECT/HAVING | Group by the PK, aggregate it, or add it to GROUP BY |
PG 42702 | ambiguous_column | Same column name in two joined tables | Qualify: o.id |
PG 42P01 | undefined_table | Wrong name, schema or search_path | Schema-qualify; check \dt |
PG 42883 | undefined_function | No function or operator for these argument types, often a type mismatch | Cast the literal or parameter, not the column |
PG 0A000 | feature_not_supported | Construct not supported in this context | Rewrite the statement |
MySQL 1055 | Expression #N of SELECT list is not in GROUP BY clause … only_full_group_by | Nonaggregated column not functionally dependent | Group by the PK, or ANY_VALUE() |
MySQL 1052 | Column '…' in … is ambiguous | Unqualified column in a join | Qualify with the table alias |
MySQL 1064 | … near '…' at line N | Syntax error, often PostgreSQL-only syntax pasted into MySQL | Use MySQL syntax: SUM(CASE …), ORDER BY x IS NULL, x |
MySQL 1176 | Key '…' doesn't exist in table '…' | FORCE INDEX / USE INDEX names a missing index | Fix the name or drop the hint |
MySQL 3065 | Expression #N of ORDER BY clause is not in SELECT list … | SELECT DISTINCT with ORDER BY on an unselected column | Add the column to the SELECT list or drop DISTINCT |
From Go and Laravel
A plan guard in a Go test (pgx). Run it against a database with realistic statistics. The pattern is from Indexing → plan guard.
func TestRecentOrdersUsesIndex(t *testing.T) {
ctx := context.Background()
pool := testPool(t) // *pgxpool.Pool against a seeded, ANALYZEd database
var plan string
err := pool.QueryRow(ctx,
`EXPLAIN (FORMAT JSON) SELECT id, created_at FROM orders
WHERE tenant_id = $1 ORDER BY created_at DESC LIMIT 20`, int64(7)).Scan(&plan)
if err != nil {
t.Fatal(err)
}
if strings.Contains(plan, `"Node Type": "Seq Scan"`) {
t.Fatalf("hot query lost its index path:\n%s", plan)
}
}// Laravel: print SQL, show the plan, group with HAVING, log every query
$q = DB::table('orders')
->select('customer_id', DB::raw('count(*) as paid_orders'))
->where('status', 'paid')
->where('created_at', '>=', now()->subDays(30))
->groupBy('customer_id')
->having('paid_orders', '>=', 3); // or ->havingRaw('count(*) >= ?', [3])
$q->toSql(); // "Get the SQL representation of the query." (? placeholders)
$q->dumpRawSql(); // the SQL "with all parameter bindings properly substituted"
dump($q->explain()); // explain(): "Explains the query." (returns a Collection of plan rows)
DB::enableQueryLog(); // "Enable the query log on the connection."
DB::table('order_items')->whereIn('order_id', $orderIds)->get(); // one IN (...) query, not N+1
dump(DB::getQueryLog()); // "Get the connection query log."having('paid_orders', …) uses the select alias, which MySQL accepts. PostgreSQL does not allow output-column names in HAVING ("not in the WHERE or HAVING clauses; there you must write out the expression instead"), so use havingRaw('count(*) >= ?', [3]) there.
References
PostgreSQL 18 documentation (saved 2026-11-29): 11.3 Multicolumn Indexes · 11.4 Indexes and ORDER BY · 11.5 Combining Multiple Indexes · 11.6 Unique Indexes · 11.7 Indexes on Expressions · 11.8 Partial Indexes · 11.9 Index-Only Scans · 11.10 Operator Classes · 11.2 Index Types · 11.12 Examining Index Usage · 14.1 Using EXPLAIN · EXPLAIN · 14.2 Statistics Used by the Planner · 7.2 Table Expressions · 7.6 LIMIT and OFFSET · SELECT · 4.2 Value Expressions · 9.21 Aggregate Functions · 2.7 Aggregate Functions (tutorial) · Release 18 · 19.7 Query Planning · 9.25 Row and Array Comparisons · 9.24 Subquery Expressions · Appendix A Error Codes · pg_stat_statements · 27.2 Cumulative Statistics · pg_stats · pg_trgm · 8.14 JSON Types · 5.5 Constraints · 10.2 Operators (type conversion) · CREATE INDEX · 9.9 Date/Time Functions · 36.7 Function Volatility · 9.7 Pattern Matching · 7.5 Sorting Rows · 7.3 Select Lists · 11.11 Indexes and Collations · 9.4 String Functions
MySQL 8.4 Reference Manual (saved 2026-11-29): 10.3 Optimization and Indexes · 10.3.1 How MySQL Uses Indexes · 10.3.6 Multiple-Column Indexes · 10.2.1.3 Index Merge · 10.2.1.2 Range Optimization · 10.2.1.16 ORDER BY Optimization · 10.2.1.17 GROUP BY Optimization · 10.2.1.18 DISTINCT Optimization · 10.2.1.19 LIMIT Optimization · 10.2.1.22 Row Constructor Expression Optimization · 10.2.1.15 IS NULL Optimization · 10.2.1.6 Index Condition Pushdown · 10.2.1.1 WHERE Clause Optimization · 10.2.1.4 Hash Join · 10.2.1.7 Nested-Loop Joins · 10.3.13 Descending Indexes · 10.8.2 EXPLAIN Output Format · 15.8.2 EXPLAIN Statement · 15.2.13 SELECT · 14.19.3 MySQL Handling of GROUP BY · 14.19.4 Functional Dependence · 14.3 Type Conversion · 17.6.2.1 Clustered and Secondary Indexes · 15.1.15 CREATE INDEX · 14.9 Full-Text Search · 15.7.3.1 ANALYZE TABLE · 5.3.4.6 Working with NULL Values · 14.20.2 Window Functions · sys.schema_unused_indexes · sys.schema_redundant_indexes · sys.statements_with_full_table_scans · 29.12.20.8 Table I/O Wait Summary Tables · Server Error Message Reference · 15.1.20.5 FOREIGN KEY Constraints · 14.9.1 Natural Language Full-Text Searches · 12.8.4 Collation Coercibility · 15.1.20.9 Secondary Indexes and Generated Columns · 14.8 String Functions
Go and Laravel (saved 2026-11-29): pgx v5 pgxpool/pool.go (QueryRow, Query) · pgx v5 rows.go (Row.Scan) · Laravel 12 Query Builder · Laravel 12 Database · Laravel 12 API: Query\Builder · Laravel 12 API: Connection · Laravel 12 API: ExplainsQueries
MySQL 8.0 manual pages (for version history the 8.4 pages omit): Hash Join (8.0) · EXPLAIN (8.0) · Nested-Loop Joins (8.0) · Semijoin (8.0; the 8.4 URL redirects here)