Writing Efficient and Readable SQL

Understanding query plans, indexes, partitions and warehouse costs, plus style habits that make SQL reviewable.

Advanced · about 4 hours · difficulty 4/5

Learn first: Window Functions

As tables grow into billions of rows, a careless query can run for an hour or cost real money. You do not need to be a database administrator, but you should know the main levers.

Reading the plan

EXPLAIN (and EXPLAIN ANALYZE in PostgreSQL) shows how the database executes your query: which tables are scanned, which joins are used, where time goes. Look for full scans of big tables and row estimates wildly different from actual rows.

Levers that matter

  • Filter early and select only needed columns, especially in columnar warehouses billed by bytes scanned.
  • Indexes (row databases like PostgreSQL) speed up filters and joins on indexed columns.
  • Partitioning and clustering (BigQuery, Snowflake, Redshift): filter on the partition column (usually a date) so the engine skips most data.
  • Avoid functions on filtered columns where possible: WHERE DATE(created_at) = ... can block index or partition pruning; use a range instead.
  • Aggregate before joining large tables, and avoid accidental cross joins.
  • Prefer UNION ALL over UNION when duplicates are impossible.

Readable SQL

  • One clause per line, consistent indentation, lowercase or uppercase keywords but not both.
  • Meaningful CTE names and table aliases, not a, b, c.
  • Comments explaining business logic ("exclude internal test accounts").

Pitfall: optimising before the query is correct. Correct first, then fast. Move on when you can read a basic EXPLAIN output and explain why one version of a query scans less data than another.

Key concepts

  • EXPLAIN and EXPLAIN ANALYZE
  • Indexes
  • Partition pruning and clustering
  • Sargable filters
  • Columnar storage and bytes scanned
  • SQL style guides

Mini project

Load a million-row public dataset (e.g. NYC taxi trips for one month) into PostgreSQL, time a filtered aggregation before and after adding an index, and compare the EXPLAIN ANALYZE output.

Check yourself

Why might WHERE DATE(created_at) = '2024-05-01' be slower than a half-open range on created_at?

Free resources