Most developers use maybe 20 percent of SQL's capabilities.
They write SELECT, JOIN, and GROUP BY, and stop there.
But SQL has a second layer - features that turn a page of application code or three separate queries into a single clean statement.
Senior developers reach for these all the time. Many junior and mid-level developers have never seen them.
None of them is new or obscure. They are sitting in the database you already use, waiting to be picked up.
Today, I want to show you 10 rare SQL features every developer should know.
In this post, we will explore:
- Common Table Expressions (CTEs)
- Window functions
- LATERAL joins
- GROUPING SETS, ROLLUP, and CUBE
- The FILTER clause in aggregates
- UPSERT with INSERT ... ON CONFLICT
- JSON support
- Computed / generated columns
- TABLESAMPLE
- Partial indexes
Let's dive in.
All queries in this post were tested on the PostgreSQL database. Most of these features exist in other databases too, though the exact syntax differs - I will note the main differences as we go.
1. Common Table Expressions (CTEs)
A complex query packed into a single statement is hard to read and even harder to change.
A Common Table Expression (CTE) lets you break that query into named, sequential steps using the WITH keyword. Each step reads like a temporary, named result you can build on.
sqlWITH recent_shipments AS ( SELECT s.id, s.number, s.carrier, s.status, s.created_at FROM shipments.shipments s WHERE s.created_at >= CURRENT_DATE - INTERVAL '30 days' ), shipment_details AS ( SELECT rs.number, rs.carrier, rs.status, COUNT(si.id) AS total_items, SUM(si.quantity) AS total_quantity FROM recent_shipments rs LEFT JOIN shipments.shipment_items si ON rs.id = si.shipment_id GROUP BY rs.number, rs.carrier, rs.status ) SELECT number AS shipment_number, carrier, status, total_items, total_quantity FROM shipment_details ORDER BY total_quantity DESC;
This query has two named parts.
recent_shipments selects shipments from the last 30 days. shipment_details then builds on it, joining the items and aggregating counts and quantities. The final SELECT reads from the second CTE as if it were a table.
The result is a query you read top to bottom, like steps in a recipe, instead of using nested subqueries from the inside out.
CTEs also support recursion with WITH RECURSIVE, which is how you query hierarchical data like org charts and category trees.
A Common Table Expression can be used within a SELECT, INSERT, UPDATE, or DELETE statement.
2. Window Functions
Sometimes you need a calculation across related rows but still want every individual row in the result.
A GROUP BY collapses rows into one per group. A window function calculates across a set of rows - the window - while keeping each row intact.
sqlSELECT number, carrier, created_at, ROW_NUMBER() OVER (PARTITION BY carrier ORDER BY created_at DESC) AS shipment_sequence, RANK() OVER (PARTITION BY carrier ORDER BY created_at DESC) AS shipment_rank FROM shipments.shipments; SELECT number, status, created_at, LAG(status) OVER (ORDER BY created_at) AS previous_status, LEAD(carrier) OVER (ORDER BY created_at) AS next_carrier FROM shipments.shipments;
The first query ranks each carrier's shipments by date. ROW_NUMBER() gives a unique sequence within each carrier (the PARTITION BY carrier), and RANK() does the same, but ties share a rank.
The second query uses LAG and LEAD to look at the previous and next row in order - here, the previous status and the next carrier - without a self-join.
Window functions are how you build running totals, rankings, moving averages, and row-to-row comparisons.
They are standard SQL and work in PostgreSQL, SQL Server, Oracle, and MySQL 8+.
3. LATERAL Joins
A normal join matches two tables on a condition. It cannot run a separate query for each row of the first table.
A LATERAL join can. It lets a subquery on the right reference columns from the table on the left, running once per row - perfect for top-N-per-group problems.
sql-- For each carrier, grab their single most recent shipment SELECT c.carrier, s.number, s.status, s.created_at FROM ( SELECT DISTINCT carrier FROM shipments.shipments ) c CROSS JOIN LATERAL ( SELECT number, status, created_at FROM shipments.shipments WHERE carrier = c.carrier ORDER BY created_at DESC LIMIT 1 ) s;
For each distinct carrier, the lateral subquery selects that carrier's single most recent shipment (ORDER BY created_at DESC LIMIT 1).
The key is WHERE carrier = c.carrier - the inner query sees the outer row's carrier, which a plain subquery cannot do.
This is the cleanest way to express "the latest row per group" or "the top 3 per category" without a window function.
Note: SQL Server writes the same thing with
CROSS APPLY(andOUTER APPLYfor the left-join version). PostgreSQL usesCROSS JOIN LATERALandLEFT JOIN LATERAL.
4. GROUPING SETS, ROLLUP & CUBE
A report often needs several levels of summary at once: totals by carrier and status, subtotals per carrier, and a grand total.
The naive way is several queries glued together with UNION ALL.
GROUPING SETS, ROLLUP, and CUBE produce all those levels in a single query.
sqlSELECT carrier, status, COUNT(*) AS shipment_count, SUM(si.quantity) AS total_quantity FROM shipments.shipments s LEFT JOIN shipments.shipment_items si ON s.id = si.shipment_id GROUP BY GROUPING SETS ( (carrier, status), -- by carrier & status (carrier), -- subtotal by carrier (status), -- subtotal by status () -- grand total ); SELECT carrier, status, DATE_TRUNC('month', created_at) AS month, COUNT(*) AS shipment_count FROM shipments.shipments GROUP BY ROLLUP ( carrier, status, DATE_TRUNC('month', created_at) );
The first query lists exactly the groupings you need: by carrier and status, by carrier alone, by status alone, and the empty () for the grand total.
ROLLUP in the second query is shorthand for hierarchical subtotals: carrier, then carrier and status, then carrier, status, and month, down to the total.
CUBE generates every possible combination of the columns.
One query replaces four queries, and the database computes the levels in a single pass rather than scanning the table multiple times.
These are part of standard SQL and work in PostgreSQL, SQL Server, and Oracle.
5. FILTER Clause in Aggregates
You often need to count or sum only the rows that meet a condition, broken out side by side.
The FILTER clause applies a condition to a single aggregate, so each one counts a different subset - in one row, in one pass over the data.
sqlSELECT carrier, COUNT(*) AS total_shipments, COUNT(*) FILTER (WHERE status = 'delivered') AS delivered_count, COUNT(*) FILTER (WHERE status = 'in_transit') AS in_transit_count, COUNT(*) FILTER (WHERE status = 'pending') AS pending_count, SUM(si.quantity) FILTER (WHERE status = 'delivered') AS delivered_quantity, SUM(si.quantity) FILTER (WHERE status = 'pending') AS pending_quantity FROM shipments.shipments s LEFT JOIN shipments.shipment_items si ON s.id = si.shipment_id GROUP BY carrier;
Each COUNT(*) FILTER (WHERE ...) counts only the matching rows, so you get delivered, in-transit, and pending counts as separate columns per carrier.
COUNT(*) FILTER (WHERE status = 'delivered') is easier to read than the old trick with case: SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END).
The intent of the filter clause is much more obvious.
Note:
FILTERis supported by PostgreSQL. SQL Server and MySQL do not have it - there you fall back toCASEinside the aggregate, likeCOUNT(CASE WHEN status = 'delivered' THEN 1 END).
6. UPSERT (INSERT ... ON CONFLICT)
Insert the row if it is new, update it if it already exists - a common need that usually takes a SELECT, an IF, and two code paths.
UPSERT does it in one atomic statement, with no race condition between the check and the write.
sqlALTER TABLE shipments.shipments ADD CONSTRAINT shipments_number_unique UNIQUE (number); INSERT INTO shipments.shipments ( id, number, order_id, address_street, address_city, address_zip, carrier, receiver_email, status, created_at, updated_at ) VALUES ( '550e8400-e29b-41d4-a716-446655440000', 'SH-2024-001', 'ORD-2024-001', '123 Main St', 'New York', '10001', 'FedEx', '[email protected]', 'pending', NOW(), NOW() ) ON CONFLICT (number) DO UPDATE SET carrier = EXCLUDED.carrier, status = EXCLUDED.status, updated_at = GREATEST(shipments.updated_at, EXCLUDED.updated_at);
First, we add a unique constraint on number, on which the conflict is detected.
Then INSERT ... ON CONFLICT (number) DO UPDATE tries to insert; if a row with that number already exists, it updates instead.
The EXCLUDED pseudo-table holds the values you tried to insert, so carrier = EXCLUDED.carrier means "use the new carrier."
GREATEST(shipments.updated_at, EXCLUDED.updated_at) keeps the later of the two timestamps.
One statement, no duplicate rows, and no read-modify-write race between concurrent callers.
Note: this is PostgreSQL syntax. The SQL standard (SQL Server, Oracle) uses the
MERGEstatement; MySQL usesINSERT ... ON DUPLICATE KEY UPDATE.
7. JSON Support
Not all data is relational. Sometimes you need to store a flexible, semi-structured payload - an event, a webhook body, a settings blob.
PostgreSQL stores JSON natively in the JSONB type and lets you query inside it, so you do not need a separate document database for occasional JSON.
Or stringified JSON as strings and further working with them in your backend code, losing all the index capabilities.
sqlCREATE TABLE shipments.events ( id SERIAL PRIMARY KEY, payload JSONB NOT NULL ); -- Insert sample data INSERT INTO shipments.events (payload) VALUES ('{"type":"click","coordinates":[{"x":10,"y":20},{"x":15,"y":25}]}'), ('{"type":"hover","coordinates":[{"x":5,"y":30}]}'), ('{"type":"scroll","coordinates":[{"x":0,"y":100},{"x":0,"y":200},{"x":0,"y":300}]}'); -- Extract simple JSON fields SELECT payload ->> 'type' AS event_type, payload -> 'coordinates' -> 0 ->> 'x' AS first_x, payload -> 'coordinates' -> 0 ->> 'y' AS first_y FROM shipments.events;
The events table stores a JSONB payload. The query then reaches into it: ->> extracts a value as text, and -> extracts a nested JSON object or array element, so payload -> 'coordinates' -> 0 ->> 'x' reads the x of the first coordinate.
JSONB is stored in a parsed binary form and can be indexed, so you can filter and extract without scanning whole documents.
Note: SQL Server queries JSON with
JSON_VALUEandOPENJSON; the SQL standard addsJSON_TABLE(in Oracle, MySQL, and PostgreSQL 17+) to turn a JSON array directly into relational rows.
8. Computed / Generated Columns
When a column's value is always derived from other columns, computing it in application code is error-prone - every write path has to remember the formula.
A generated column moves that formula into the table definition, so the database calculates and stores it automatically.
sqlCREATE TABLE shipments.shipping_costs ( id SERIAL PRIMARY KEY, shipment_id UUID NOT NULL, base_rate DECIMAL(10,2) NOT NULL, weight_kg DECIMAL(8,2) NOT NULL, distance_km DECIMAL(10,2) NOT NULL, fuel_surcharge_rate DECIMAL(5,4) NOT NULL DEFAULT 0.15, -- Generated columns weight_cost DECIMAL(10,2) GENERATED ALWAYS AS (weight_kg * 2.50) STORED, distance_cost DECIMAL(10,2) GENERATED ALWAYS AS (distance_km * 0.85) STORED, fuel_surcharge DECIMAL(10,2) GENERATED ALWAYS AS (base_rate * fuel_surcharge_rate) STORED, total_cost DECIMAL(10,2) GENERATED ALWAYS AS ( base_rate + (weight_kg * 2.50) + (distance_km * 0.85) + (base_rate * fuel_surcharge_rate) ) STORED, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), FOREIGN KEY (shipment_id) REFERENCES shipments.shipments(id) );
Each GENERATED ALWAYS AS (...) STORED column is computed from the other columns whenever a row is inserted or updated.
total_cost adds the base rate, weight cost, distance cost, and fuel surcharge - and you can never forget to recalculate it, because you cannot write to it directly.
STORED means the value is physically saved (and can be indexed), rather than recomputed on every read.
Note: SQL Server calls these computed columns, written as
total_cost AS (...)withPERSISTEDfor the stored equivalent. MySQL uses the sameGENERATED ALWAYS ASsyntax as PostgreSQL.
9. TABLESAMPLE
Running an exploratory query against a huge table is slow when you only need a feel for the data, not every row.
TABLESAMPLE returns a random sample of the table, reading a fraction of it instead of scanning everything.
sql-- Sample for testing queries on large tables SELECT carrier, COUNT(*) FROM shipments.shipments TABLESAMPLE SYSTEM (5) GROUP BY carrier; -- Get a random sample with a specific seed for reproducible results SELECT * FROM shipments.shipments TABLESAMPLE BERNOULLI (10) REPEATABLE (12345); -- Sample with WHERE clause (applied after sampling) SELECT * FROM shipments.shipments TABLESAMPLE BERNOULLI (20) WHERE status = 'pending'; -- Sample with joins SELECT s.number, s.carrier, sc.total_cost FROM shipments.shipments s TABLESAMPLE SYSTEM (10) JOIN shipments.shipping_costs sc ON s.id = sc.shipment_id;
TABLESAMPLE SYSTEM (5) samples roughly 5 percent of the table by reading random pages - fast, but block-based.
BERNOULLI (10) samples about 10 percent row-by-row, which is more statistically even but slower.
REPEATABLE (12345) fixes the random seed, so the same sample comes back on every run - useful for reproducible tests.
It is built for quick checks, profiling, and testing queries on large tables without paying for a full scan.
Note:
TABLESAMPLEis part of standard SQL; PostgreSQL ships theSYSTEMandBERNOULLImethods, and SQL Server supportsTABLESAMPLE SYSTEMas well.
10. Partial Indexes
An index over an entire table costs storage and slows writes - even when your queries only ever touch a small slice of the rows.
A partial index covers just the rows that match a condition, so it is smaller, faster to scan, and cheaper to maintain.
sql-- Create a partial index for active/pending shipments CREATE INDEX idx_shipments_pending_carrier ON shipments.shipments (carrier, created_at) WHERE status IN ('pending', 'in_transit'); -- Create a partial index for specific carrier queries CREATE INDEX idx_shipments_fedex_status ON shipments.shipments (status, updated_at) WHERE carrier = 'FedEx'; -- This query will use idx_shipments_pending_carrier SELECT number, carrier, created_at FROM shipments.shipments WHERE status = 'pending' AND carrier = 'FedEx' ORDER BY created_at DESC; -- This query will use idx_shipments_fedex_status SELECT number, status, updated_at FROM shipments.shipments WHERE carrier = 'FedEx' AND status IN ('delivered', 'pending') ORDER BY updated_at DESC;
The first index covers only pending and in-transit shipments; the second only FedEx rows. Queries that match those conditions use the matching index, and because each index holds a fraction of the table, lookups and maintenance are quicker.
Partial indexes shine for hot subsets - active records, a soft-delete is_deleted = false filter, or one high-traffic status - where most queries care about a small, predictable slice.
Note: SQL Server calls these filtered indexes, with the same
CREATE INDEX ... WHEREsyntax. For a full tour of index types, see Optimizing SQL Performance with Indexing Strategies.
Summary
None of these features is exotic.
They are standard SQL, sitting in the database you already run, and each one replaces a chunk of application code or a stack of queries with something simpler. You do not need every one of these on day one.
Pick the one that fixes a problem you have right now - a complex nested query, a slow report, a read-modify-write race - and add the rest as you meet them.
Hope you find this newsletter useful. See you next time.


Comments