SQL Cheat Sheet

Core SQL syntax and patterns for querying, filtering, sorting, joining, grouping, and modifying data.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

SELECT Basics

Foundational read queries.

Select all columns

Return all columns from a table.

sqlANYselectbasics
sql
SELECT *
FROM users;
Notes

Good for quick exploration, but prefer explicit columns in production queries.

Select specific columns

Return only the columns you need.

sqlANYselectcolumns
sql
SELECT id, email, created_at
FROM users;
Notes

Selecting fewer columns often improves readability and can reduce I/O.

Select distinct values

Remove duplicate rows for the selected expression set.

sqlANYselectdistinct
sql
SELECT DISTINCT country
FROM customers;
Notes

DISTINCT applies to the full selected column combination.

Use column aliases

Rename output columns in query results.

sqlANYselectalias
sql
SELECT first_name AS given_name, last_name AS family_name
FROM users;
Notes

Aliases are especially useful in reports and computed expressions.

Select literals and expressions

Project computed values directly in the result set.

sqlANYselectexpressions
sql
SELECT order_id, subtotal, tax, subtotal + tax AS total
FROM orders;
Notes

Most SQL engines allow arithmetic, string, and function expressions in SELECT.

Filtering Rows

WHERE clause patterns.

Filter with equality

Return rows matching an exact value.

sqlANYwherefilter
sql
SELECT *
FROM users
WHERE status = 'active';
Notes

Use WHERE to limit the result set before grouping or ordering.

Use comparison operators

Compare numeric or date values.

sqlANYwherecomparison
sql
SELECT *
FROM invoices
WHERE amount > 1000
  AND due_date < CURRENT_DATE;
Notes

Combine predicates with AND and OR to express complex filters.

Filter with IN

Match any value from a list.

sqlANYwherein
sql
SELECT *
FROM products
WHERE category IN ('books', 'games', 'toys');
Notes

IN is often clearer than multiple OR comparisons.

Filter with BETWEEN

Filter a value within an inclusive range.

sqlANYwherebetween
sql
SELECT *
FROM events
WHERE created_at BETWEEN DATE "2025-01-01" AND DATE "2025-01-31";
Notes

BETWEEN is inclusive on both ends in standard SQL.

Pattern matching with LIKE

Find rows using wildcard patterns.

sqlANYwherelikepattern
sql
SELECT *
FROM customers
WHERE email LIKE '%@example.com';
Notes

Use % for any-length wildcard and _ for a single character.

Test for NULL

Filter rows with missing values.

sqlANYwherenull
sql
SELECT *
FROM tasks
WHERE completed_at IS NULL;
Notes

Use IS NULL or IS NOT NULL, not = NULL.

Sorting and Limiting

ORDER BY, LIMIT, FETCH, OFFSET patterns.

Sort rows

Order query results ascending or descending.

sqlANYorder-bysorting
sql
SELECT id, created_at
FROM orders
ORDER BY created_at DESC, id ASC;
Notes

ORDER BY is applied after filtering and grouping.

Limit returned rows

Return only the first N rows.

sqlANYlimitpagination
sql
SELECT *
FROM logs
ORDER BY created_at DESC
LIMIT 50;
Notes

LIMIT is widely supported, though standard SQL also supports FETCH FIRST.

Paginate with LIMIT and OFFSET

Skip rows and return a page-sized result set.

sqlANYpaginationlimitoffset
sql
SELECT *
FROM posts
ORDER BY published_at DESC
LIMIT 20 OFFSET 40;
Notes

Offset pagination is simple but can be slower for large offsets.

Fetch first rows

Use standard SQL row limiting syntax.

sqlANYfetchlimitstandard-sql
sql
SELECT *
FROM employees
ORDER BY salary DESC
FETCH FIRST 10 ROWS ONLY;
Notes

Supported in many modern SQL engines and part of the SQL standard.

Joins

Combine rows from multiple tables.

Inner join two tables

Return rows with matches in both tables.

sqlANYjoininner-join
sql
SELECT o.order_id, c.name
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id;
Notes

INNER JOIN returns only matched rows.

Left join

Keep all rows from the left table and match rows from the right table.

sqlANYjoinleft-join
sql
SELECT c.customer_id, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
Notes

Rows without a match on the right side get NULLs for right-side columns.

Right join

Keep all rows from the right table.

sqlANYjoinright-join
sql
SELECT e.employee_id, d.department_name
FROM employees e
RIGHT JOIN departments d ON d.department_id = e.department_id;
Notes

Many teams prefer rewriting RIGHT JOIN as LEFT JOIN for consistency.

Full outer join

Return matched and unmatched rows from both tables.

sqlANYjoinfull-outer-join
sql
SELECT a.id AS a_id, b.id AS b_id
FROM a
FULL OUTER JOIN b ON b.id = a.id;
Notes

Useful for reconciliation queries.

Self join

Join a table to itself.

sqlANYjoinself-join
sql
SELECT e.employee_id, e.name, m.name AS manager_name
FROM employees e
LEFT JOIN employees m ON m.employee_id = e.manager_id;
Notes

Self joins are common in hierarchical or parent-child tables.

Cross join

Return the Cartesian product of two sets.

sqlANYjoincross-join
sql
SELECT c.color, s.size
FROM colors c
CROSS JOIN sizes s;
Notes

Cross joins multiply rows, so use them deliberately.

Aggregation and Grouping

Summaries and grouped queries.

Count rows

Return total row count.

sqlANYaggregatecount
sql
SELECT COUNT(*) AS row_count
FROM users;
Notes

COUNT(*) includes rows regardless of NULL values.

Group by a column

Aggregate values per group.

sqlANYgroup-byaggregate
sql
SELECT status, COUNT(*) AS total
FROM orders
GROUP BY status;
Notes

All non-aggregated selected columns must appear in GROUP BY.

Group by multiple columns

Aggregate by more than one dimension.

sqlANYgroup-byaggregate
sql
SELECT country, status, COUNT(*) AS total
FROM customers
GROUP BY country, status;
Notes

Useful for reports sliced by multiple categories.

Filter groups with HAVING

Apply conditions after aggregation.

sqlANYhavinggroup-byaggregate
sql
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 5;
Notes

WHERE filters rows before grouping; HAVING filters grouped results.

Use common aggregate functions

Calculate summary metrics.

sqlANYaggregatesumavgmin
sql
SELECT
  COUNT(*) AS total_rows,
  SUM(amount) AS total_amount,
  AVG(amount) AS avg_amount,
  MIN(amount) AS min_amount,
  MAX(amount) AS max_amount
FROM payments;
Notes

Most SQL engines support these core aggregate functions.

Recommended next

No recommendations yet.