Cheatsheet
← All cheat sheets

SQL cheat sheet

Standard SQL that works in PostgreSQL, MySQL, SQLite and SQL Server, with small differences noted. Click a query to copy it.

Reading data

Every column of every row
Only some columns
Each value once
Rename a column in the result
Number of rows

Filtering

Equal to (<> or != for not equal)
Combine conditions (OR, NOT too)
In a range, including both ends
Matches any value in a list
Starts with “An” (% any text, _ one character)
Empty value (IS NOT NULL for filled)

Sorting and limiting

Newest first (ASC for oldest first)
Sort by several columns
Only the first 10 rows (SQL Server: SELECT TOP 10)
Rows 21–30, for paging

Joins

Rows that match in both tables (INNER JOIN)
All users, with orders when they have any
After a LEFT JOIN: users without orders
All rows from both tables (not in MySQL)

Grouping

Count per group
Other totals per group
Filter groups (WHERE filters rows before grouping)

Changing data

Add a row
Change rows (always add WHERE!)
Delete rows (always add WHERE!)
Do several changes together (ROLLBACK to cancel)

Tables and indexes

Create a table (PostgreSQL types)
Add a column
Speed up searches on a column
Delete a table and all its data

Handy extras

First value that isn’t empty
If/else inside a query
Name a sub-query (CTE) to keep things readable
Stack results, without duplicates (UNION ALL keeps them)
Something not working?

Send feedback

What is it?

The page you’re on, your browser and your screen size are sent along to help us fix it. Never your files or what you typed into the tool.