SQL Commands & Queries Cheat Sheet
Essential SQL queries for developers, data analysts, and backend engineers. Searchable quick reference for joins, window functions, CTEs, aggregations, upserts, transactions, and index tuning.
Basic Select with Aliases and Distinct
Retrieves deduplicated status columns, counts orders, filters by date range, sorts in descending order, and paginates using LIMIT and OFFSET.
Pattern Matching with Wildcards (LIKE and ILIKE)
ILIKE performs case-insensitive wildcard search (PostgreSQL). Use LIKE '%text%' for standard ANSI SQL.
Range and Set Inclusion (BETWEEN and IN)
BETWEEN is inclusive of both boundary values. IN evaluates membership across a static tuple or dynamic subquery.
Conditional Evaluation (CASE WHEN)
Evaluates ordered boolean branches to compute derived values or categorical labels in result sets.
Null Coalescing and Safe Handling
COALESCE returns the first non-null argument. NULLIF returns NULL if both arguments are equal, converting empty strings to NULL.
Inner Join (Exact matches across two tables)
Returns only records where the join key matches in both tables.
Left Outer Join (All left rows, matching right rows)
Preserves every row from the left table; right columns are filled with NULL when no match exists. Useful for finding orphan records.
Full Outer Join (All rows from both tables)
Returns all rows from both tables, filling NULLs on either side where keys do not match.
Self Join (Hierarchical parent/child relationships)
Joins a table to itself using aliases to resolve hierarchical organizational charts or category trees.
Group By with Having Clause
WHERE filters rows before aggregation. HAVING filters grouped rows after aggregate computation.
Conditional Aggregation with FILTER / SUM CASE
PostgreSQL FILTER clause or ANSI SQL CASE WHEN inside aggregate functions computes multi-metric pivots in a single scan.
Row Number, Rank, and Dense Rank
Partitions records by category and orders them. ROW_NUMBER assigns sequential integers; RANK leaves gaps on ties; DENSE_RANK leaves no gaps.
Period-over-Period Delta with LAG and LEAD
LAG accesses rows preceding the current row by an offset. LEAD accesses rows following the current row.
Running Cumulative Totals (Window Framing)
Computes cumulative sums across time dimensions using explicit window frames.
Common Table Expression (WITH Clause)
Improves readability and reusability over nested subqueries by defining named temporary result sets.
Recursive CTE (Category Trees & Graph Traversal)
Recursively traverses hierarchical parent-child relationships, such as e-commerce categories or org charts.
Upsert / On Conflict (Insert or Update)
PostgreSQL ON CONFLICT (or MySQL ON DUPLICATE KEY UPDATE) executes an atomic insert-or-update without race conditions.
Delete with Subquery / Using Join
Prunes stale session records linked to deactivated accounts with interval date arithmetic.
Create Table with Constraints and Foreign Keys
Defines strict schema invariants: primary keys, cascade foreign keys, unique bounds, and check constraints.
Create Partial and Composite Indexes
Composite indexes satisfy multiple WHERE and ORDER BY columns. Partial indexes only index matching rows, reducing index disk footprint.
ACID Transaction with Savepoints
Wraps multi-table mutations in an atomic block. Savepoints allow partial rollbacks without abandoning the entire transaction.
Frequently Asked Questions About SQL Queries & Optimization
What is the difference between WHERE and HAVING in SQL?
WHERE filters rows before any groupings or aggregate functions (COUNT, SUM, AVG) are computed. HAVING filters the grouped summary rows after the GROUP BY clause has been evaluated.
When should I use ROW_NUMBER() vs RANK() vs DENSE_RANK()?
All three compute ordinal rankings within an OVER (PARTITION BY ... ORDER BY ...) window. ROW_NUMBER assigns distinct sequential numbers (1, 2, 3, 4). RANK assigns identical numbers to ties and skips subsequent numbers (1, 2, 2, 4). DENSE_RANK assigns identical numbers to ties without skipping numbers (1, 2, 2, 3).
What is the performance difference between UNION and UNION ALL?
UNION combines result sets from two queries and automatically runs an expensive sorting and deduplication step. UNION ALL simply concatenates the result sets without deduplication, making it significantly faster and less memory-intensive when rows are guaranteed unique.
Why are Common Table Expressions (CTEs) preferred over deeply nested subqueries?
CTEs (using the WITH clause) make SQL scripts modular, linear, and readable from top to bottom. They can also be referenced multiple times within the same statement and support recursion for hierarchical tree traversal.
What does an atomic UPSERT (ON CONFLICT DO UPDATE) accomplish?
An UPSERT avoids race conditions between concurrent worker threads trying to insert the same unique key simultaneously. Instead of throwing a unique constraint violation error, the database updates the existing row in place atomically.