SQL Cheatsheet
Free SQL cheatsheet. Searchable reference for SELECT, JOINs, GROUP BY, subqueries, window functions, INSERT/UPDATE/DELETE, indexes, constraints and transactions, with MySQL, PostgreSQL, SQLite and SQL Server differences noted.
Frequently asked questions
What's the difference between WHERE and HAVING?
WHERE filters individual rows before any grouping happens, so it cannot use aggregate functions like SUM or COUNT. HAVING filters the groups after GROUP BY, so it can. For example, WHERE total > 100 keeps big orders, while HAVING COUNT(*) > 5 keeps customers with more than five orders.
What's the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only the rows that have a match in both tables. LEFT JOIN returns every row from the left table and fills the right-hand columns with NULL where there is no match, which makes it the way to find rows with no related rows, such as customers who have never ordered.
What's the difference between DELETE, TRUNCATE and DROP?
DELETE removes the rows you choose with WHERE and can usually be rolled back. TRUNCATE removes every row quickly and resets the table, and in some databases it cannot be rolled back. DROP removes the whole table, its structure included. Always check what a DELETE matches by running it as a SELECT first.
Why does WHERE column = NULL return nothing?
NULL means "unknown", and nothing is equal to an unknown value โ not even another NULL โ so the comparison is never true. Use IS NULL or IS NOT NULL instead.
What's the difference between UNION and UNION ALL?
Both stack the results of two queries. UNION removes duplicate rows, which costs extra work; UNION ALL keeps every row and is faster. Use UNION ALL unless you specifically need duplicates removed.
Does this cover MySQL, PostgreSQL, SQLite and SQL Server?
The commands are standard SQL, which all of them share. Where the databases differ โ limiting rows (LIMIT, TOP or FETCH FIRST), auto-numbering, date functions, upserts โ the entry names each dialect's syntax.