SQL Cheatsheet
Essential SQL commands, with a focus on modern PostgreSQL features. From basic queries to advanced data types.
When This Cheatsheet Helps Most
Use this page when you need to inspect production-like data quickly, verify joins, group records into reports, or debug JSON-heavy schemas in PostgreSQL without jumping between many docs pages.
Basics
| Key / Code | Description |
|---|---|
| SELECT * FROM users | Select all columns from a table. |
| WHERE age > 18 | Filter rows. |
| ORDER BY created_at DESC | Sort results. |
| LIMIT 10 OFFSET 5 | Pagination. |
Joins
| Key / Code | Description |
|---|---|
| INNER JOIN | Returns records that have matching values in both tables. |
| LEFT JOIN | Returns all records from the left table, and the matched records from the right table. |
| RIGHT JOIN | Returns all records from the right table, and the matched records from the left table. |
| FULL OUTER JOIN | Returns all records when there is a match in either left or right table. |
PostgreSQL JSONB
Modern Postgres allows semi-structured data.
-- Select a value from a JSON column
SELECT data->>'name' FROM events;
-- Filter by JSON value
SELECT * FROM events WHERE data->>'status' = 'completed';Common Table Expressions (CTE)
Use `WITH` to create temporary result sets. Makes complex queries readable.
WITH regional_sales AS (
SELECT region, SUM(amount) as total_sales
FROM orders
GROUP BY region
)
SELECT * FROM regional_sales WHERE total_sales > 10000;Common SQL Mistakes
Frequent mistakes include forgetting the join condition, filtering after aggregation instead of before it, and assuming NULL behaves like an empty string or zero. Those errors usually produce results that look plausible but are wrong.
Related
Clean up large queries before sharing them in reviews, debugging sessions, or docs.
Helpful when your data mixes relational tables with nested JSON documents.
Use these thresholds when deciding whether a query or report is fast enough.
Useful for preprocessing, validating, or cleaning text before it reaches SQL.