๐Ÿ—„๏ธ SQL

โ† Back to Cheatsheets

A quick-reference cheatsheet for the most commonly used SQL features. SQL is a declarative language for querying and manipulating relational databases. While dialects differ slightly between PostgreSQL, MySQL, and SQLite, the core syntax covered here works across all of them.

Resources

PostgreSQL docs MySQL docs SQLite language reference SQLTutorial.org Use The Index, Luke โ€” query performance

Querying

The SELECT statement is the foundation of SQL. Clauses are written in a specific order but executed in a different one: FROM โ†’ WHERE โ†’ GROUP BY โ†’ HAVING โ†’ SELECT โ†’ ORDER BY โ†’ LIMIT.

Filtering & Sorting

The WHERE clause filters rows before grouping. Use HAVING to filter after aggregation. String comparisons are case-sensitive in PostgreSQL and case-insensitive in MySQL by default.

Joins

Joins combine rows from two or more tables based on a related column. INNER JOIN returns only matching rows. LEFT JOIN keeps all rows from the left table, filling NULLs where there is no match on the right. Always join on indexed columns for performance.

Aggregation

Aggregate functions collapse multiple rows into a single value. Any column in the SELECT that is not inside an aggregate must appear in GROUP BY. HAVING filters groups after aggregation, where WHERE cannot reference aggregate results.

Modifying Data

Always include a WHERE clause on UPDATE and DELETE โ€” omitting it affects every row in the table. Test with a SELECT using the same WHERE before running a destructive statement.

Schema

DDL (Data Definition Language) statements create and modify the structure of tables. Prefer adding columns as nullable or with a default when altering live tables โ€” adding a NOT NULL column without a default locks the table while it backfills on many engines.

Advanced

CTEs (Common Table Expressions) make complex queries readable by naming intermediate result sets. Subqueries can appear in SELECT, FROM, and WHERE clauses. Transactions group statements so they either all succeed or all fail together.