SQL Cheatsheet - Common Query Syntax & Examples

The most-used, easiest-to-forget SQL syntax in one place: queries, joins, aggregation, window functions and transactions, with copy-ready examples.

Databases·35 commands·Last updated 2026-08-02
Back to Databases

Basic Query 6

SELECT * FROM users
Select all columns
SELECT name, age FROM users
Select specific columns
SELECT * FROM users WHERE age > 18
Filter with condition
SELECT DISTINCT city FROM users
Remove duplicates
SELECT * FROM users LIMIT 10 OFFSET 20
Pagination (skip 20, take 10)
SELECT * FROM users ORDER BY age DESC
Sort descending

Filtering & Logic 6

WHERE name LIKE 'A%'
Prefix match
WHERE name LIKE '%son'
Suffix match
WHERE age BETWEEN 18 AND 30
Range
WHERE id IN (1, 2, 3)
Set membership
WHERE a IS NULL
Null check
WHERE a AND b OR c
Logic (AND precedes OR)

Aggregation & Grouping 5

SELECT COUNT(*) FROM users
Count
SELECT AVG(age) FROM users
Average
SELECT city, COUNT(*) FROM users GROUP BY city
Group by city
HAVING COUNT(*) > 5
Filter after grouping (on aggregates)
SELECT MAX(age), MIN(age) FROM users
Max / min

JOIN 5

FROM a JOIN b ON a.id = b.a_id
Inner join
FROM a LEFT JOIN b ON a.id = b.a_id
Left join (keep all of a)
FROM a RIGHT JOIN b ON a.id = b.a_id
Right join
FROM a CROSS JOIN b
Cartesian product
SELECT * FROM a NATURAL JOIN b
Auto-join on same-named columns

Window Functions 4

ROW_NUMBER() OVER (ORDER BY age)
Row number
RANK() OVER (PARTITION BY city ORDER BY age)
Rank (gaps on ties)
SUM(amount) OVER (PARTITION BY user_id)
Partitioned running total
LAG(price) OVER (ORDER BY date)
Previous row value

DML & Transactions 5

INSERT INTO t (a, b) VALUES (1, 'x')
Insert
UPDATE t SET a = 2 WHERE id = 1
Update
DELETE FROM t WHERE id = 1
Delete
BEGIN; ... COMMIT;
Commit transaction
ROLLBACK;
Rollback transaction

DDL 4

CREATE TABLE t (id INT PRIMARY KEY, name TEXT)
Create table
ALTER TABLE t ADD COLUMN age INT
Add column
DROP TABLE t
Drop table
CREATE INDEX idx_name ON t(name)
Create index

💡 Tips

  • AND has higher precedence than OR — use parentheses for complex conditions.
  • Columns in GROUP BY must appear in SELECT (except aggregated columns).
  • LIKE case-sensitivity depends on the database collation.
  • Wrap data changes in BEGIN; and COMMIT only after verifying.

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

Publicly updated on Aug 2, 2026, continuously proofread against official docs.

Found an error? Report it

Wrong command or description? Open an issue to help us fix it.

Found an error? Report it