env.dev

SQL Cheat Sheet — Queries & Commands Quick Reference

SQL quick reference: SELECT, JOINs, GROUP BY, subqueries, window functions, indexes, and data manipulation commands.

Last updated:

A quick reference for SQL syntax. Covers SELECT queries, filtering, joins, aggregation, subqueries, window functions, indexes, and data modification statements.

SELECT & Filtering

SyntaxDescription
SELECT * FROM tSelect all columns from table
SELECT a, b FROM tSelect specific columns
SELECT DISTINCT a FROM tSelect unique values only
WHERE a = 1Filter by exact match
WHERE a IN (1, 2, 3)Filter by value list
WHERE a BETWEEN 1 AND 10Filter by range (inclusive)
WHERE a LIKE "foo%"Pattern match (% = any chars)
WHERE a IS NULLCheck for null values
WHERE a AND (b OR c)Combine conditions

ORDER BY & LIMIT

SyntaxDescription
ORDER BY col ASCSort ascending (default)
ORDER BY col DESCSort descending
ORDER BY a, b DESCSort by multiple columns
LIMIT 10Return first 10 rows
LIMIT 10 OFFSET 20Skip 20 rows, then return 10
ORDER BY col NULLS LASTPlace nulls at end (PostgreSQL)

JOINs

SyntaxDescription
INNER JOIN t2 ON t1.id = t2.idRows matching in both tables
LEFT JOIN t2 ON t1.id = t2.idAll from left, matching from right
RIGHT JOIN t2 ON t1.id = t2.idAll from right, matching from left
FULL OUTER JOIN t2 ON ..All rows from both tables
CROSS JOIN t2Cartesian product of both tables
t1 JOIN t2 USING (col)Join on identically named column
t1 NATURAL JOIN t2Auto-join on all shared column names
LEFT JOIN t2 ON .. WHERE t2.id IS NULLRows in t1 not in t2 (anti-join)

GROUP BY & Aggregation

SyntaxDescription
GROUP BY colGroup rows by column value
COUNT(*)Count all rows in group
COUNT(DISTINCT col)Count unique values
SUM(col)Sum of values in group
AVG(col)Average of values in group
MIN(col) / MAX(col)Minimum / maximum value
HAVING COUNT(*) > 1Filter groups after aggregation
GROUP BY ROLLUP(a, b)Subtotals and grand total

Subqueries

PatternDescription
WHERE col IN (SELECT ..)Filter by subquery result set
WHERE EXISTS (SELECT ..)True if subquery returns rows
WHERE col > (SELECT AVG(..))Compare to scalar subquery
SELECT (SELECT ..) AS subScalar subquery in select list
FROM (SELECT ..) AS tDerived table (inline view)
WITH cte AS (SELECT ..) SELECT ..Common Table Expression (CTE)
WITH RECURSIVE cte AS (..)Recursive CTE for hierarchies

Window Functions

SyntaxDescription
ROW_NUMBER() OVER (ORDER BY col)Sequential row number
RANK() OVER (ORDER BY col)Rank with gaps for ties
DENSE_RANK() OVER (ORDER BY col)Rank without gaps
LAG(col, 1) OVER (ORDER BY col)Value from previous row
LEAD(col, 1) OVER (ORDER BY col)Value from next row
SUM(col) OVER (PARTITION BY grp)Running total per partition
NTILE(4) OVER (ORDER BY col)Divide rows into N buckets
OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)Cumulative frame

Indexes

SyntaxDescription
CREATE INDEX idx ON t(col)Create B-tree index on column
CREATE UNIQUE INDEX idx ON t(col)Index enforcing uniqueness
CREATE INDEX idx ON t(a, b)Composite index (multi-column)
DROP INDEX idxRemove an index
CREATE INDEX CONCURRENTLY ..Non-blocking index creation (PostgreSQL)
EXPLAIN SELECT ..Show query execution plan

INSERT / UPDATE / DELETE

SyntaxDescription
INSERT INTO t (a, b) VALUES (1, 2)Insert a single row
INSERT INTO t SELECT .. FROM t2Insert from another query
UPDATE t SET a = 1 WHERE b = 2Update matching rows
DELETE FROM t WHERE a = 1Delete matching rows
TRUNCATE TABLE tDelete all rows (fast, no log)
INSERT .. ON CONFLICT DO UPDATE ..Upsert (PostgreSQL)
INSERT .. ON DUPLICATE KEY UPDATE ..Upsert (MySQL)
MERGE INTO t USING ..Upsert (SQL Server / Oracle)

Frequently Asked Questions

What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows with matches in both tables. LEFT JOIN returns all rows from the left table and matched rows from the right table, with NULL for non-matches.

What is a window function?

Window functions perform calculations across related rows without collapsing them. Examples: ROW_NUMBER(), RANK(), LAG(), LEAD(), SUM() OVER(). They use the OVER clause with optional PARTITION BY and ORDER BY.

When should I use an index?

Add indexes on columns used in WHERE, JOIN, and ORDER BY clauses. Avoid indexing columns with low cardinality or tables with frequent writes. Use EXPLAIN to verify index usage.