Tutorial

SQL Cheat Sheet: Commands, Queries, and Window Functions Reference

Bookmark this comprehensive sql cheat sheet: essential syntax for SELECT, JOINs, aggregations, Window Functions, CTEs, and query order of execution.

Anuj SainiSep 8, 20269 min read

Having an authoritative sql cheat sheet at your fingertips accelerates query drafting, eliminates syntax lookup interruptions, and reinforces relational database fundamentals. While database engines like PostgreSQL, MySQL, Snowflake, BigQuery, and SQL Server offer vendor-specific dialects, standard ANSI SQL forms the universal backbone across all analytical platforms.

Data analysts write SQL to answer high-stakes business questions: identifying customer churn cohorts, calculating 30-day rolling sales, joining transaction logs with marketing touchpoints, and auditing ledger anomalies. But when writing nested joins or complex window functions under pressure, syntax details—such as whether HAVING accepts aliases or whether NULL = NULL evaluates to true—frequently cause silent query bugs.

In this comprehensive sql cheat sheet, you will find clear syntax blueprints, visual join summaries, aggregation templates, and execution order diagrams. For deeper practice, solve live problems on our interactive SQL practice platform and explore our complete SQL interview questions guide.


Monthly searches for SQL syntax and query cheat sheets

SQL remains the #1 requested technical skill across 75% of data analyst, business intelligence, and analytics engineer job descriptions.


SQL Cheat Sheet: Query Structure and Order of Execution

The single most common conceptual error in SQL is confusing the written syntax order with the database engine's logical execution order.

Written Order vs Execution Order

sql
-- How you WRITE a query:             -- How the database EXECUTES it:
1. SELECT                              1. FROM & JOIN
2. FROM & JOIN                         2. WHERE (row filter)
3. WHERE                               3. GROUP BY (aggregation)
4. GROUP BY                            4. HAVING (aggregate filter)
5. HAVING                               5. SELECT (expressions & aliases)
6. ORDER BY                            6. DISTINCT
7. LIMIT / OFFSET                      7. ORDER BY
                                       8. LIMIT / OFFSET

Because SELECT runs in step 5, you cannot reference a column alias created in SELECT inside your WHERE or GROUP BY clause in standard SQL.


Essential SQL Commands Reference

1. Basic Querying and Filtering

sql
-- Retrieve specific columns and filter
SELECT 
    customer_id, 
    first_name, 
    email,
    created_at
FROM customers
WHERE country = 'India'
  AND status = 'active'
  AND signup_date >= '2026-01-01'
ORDER BY created_at DESC
LIMIT 50;

Common Filtering Operators

OperatorSyntax ExampleDescription
Comparisonsalary >= 75000Greater than or equal to
Not Equalstatus <> 'churned' or !=Value does not equal string
Rangeage BETWEEN 21 AND 35Inclusive range (21 <= age <= 35)
List Membershipregion IN ('North', 'West')Value matches any item in list
Pattern Matchingemail LIKE '%@gmail.com'% matches zero or more chars; _ matches one
NULL Checkmanager_id IS NULLNever use = NULL; always use IS NULL

For a full breakdown of three-valued logic and COALESCE, read our dedicated SQL NULL guide.


2. Aggregations and GROUP BY

Aggregations collapse multiple rows into single summary metrics.

sql
SELECT 
    department,
    COUNT(*) AS total_employees,
    AVG(salary) AS average_salary,
    MIN(salary) AS lowest_salary,
    MAX(salary) AS highest_salary,
    SUM(bonus) AS total_bonuses
FROM employees
WHERE is_active = TRUE
GROUP BY department
HAVING COUNT(*) >= 5
ORDER BY average_salary DESC;

The Non-Aggregated Column Rule

Every non-aggregated column appearing in your SELECT list must be explicitly declared in the GROUP BY clause. Writing SELECT department, role, AVG(salary) FROM employees GROUP BY department; fails in standard SQL because the engine does not know which role to pair with each department's average.

For more nuances between pre-aggregation and post-aggregation filtering, see our SQL GROUP BY vs HAVING guide.


3. SQL Joins Summary

Joins combine columns from two or more tables based on a related matching key.

sql
-- INNER JOIN: Only customers who have placed orders
SELECT c.customer_name, o.order_id, o.amount
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id;
 
-- LEFT JOIN: All customers, including those with zero orders
SELECT c.customer_name, o.order_id, COALESCE(o.amount, 0) AS amount
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id;
Feature / Criteria

To avoid accidental row explosions, read our deep-dive on SQL JOIN Fan-Out and review SQL Joins Explained with Examples.


4. Window Functions Reference

Window functions calculate metrics across a partition of rows while retaining the original row count (unlike GROUP BY, which collapses rows).

sql
SELECT 
    employee_id,
    department,
    salary,
    -- Unique rank per department
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num,
    -- Rank with ties (1, 2, 2, 4)
    RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk,
    -- Dense rank with ties (1, 2, 2, 3)
    DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rnk,
    -- Prior row value for period-over-period comparison
    LAG(salary, 1) OVER (PARTITION BY department ORDER BY hire_date) AS prev_salary,
    -- Running total
    SUM(salary) OVER (PARTITION BY department ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_dept_total
FROM employees;

For comprehensive visual breakdowns, consult our SQL Window Functions Guide and SQL ROW_NUMBER vs RANK.


5. Common Table Expressions (CTEs) & Subqueries

CTEs replace messy nested subqueries with readable, top-to-bottom procedural blocks.

sql
WITH regional_sales AS (
    SELECT 
        region,
        SUM(revenue) AS total_revenue
    FROM sales
    WHERE sale_year = 2026
    GROUP BY region
),
benchmark AS (
    SELECT AVG(total_revenue) AS avg_revenue 
    FROM regional_sales
)
SELECT 
    r.region,
    r.total_revenue,
    b.avg_revenue,
    r.total_revenue - b.avg_revenue AS variance
FROM regional_sales r
CROSS JOIN benchmark b
ORDER BY variance DESC;

Read our full guide to modular queries in the SQL CTE Guide.


6. Conditional Logic (CASE WHEN)

Implements if/then/else branching directly in SQL statements.

sql
SELECT 
    order_id,
    amount,
    CASE 
        WHEN amount >= 50000 THEN 'Enterprise'
        WHEN amount >= 10000 THEN 'Mid-Market'
        WHEN amount > 0 THEN 'SMB'
        ELSE 'Refund/Zero'
    END AS tier
FROM orders;

For conditional aggregation patterns (such as pivoting columns without PIVOT), read SQL CASE WHEN & Conditional Aggregation.


Common SQL Pitfalls and How to Fix Them

Accidentally Turning a LEFT JOIN into an INNER JOIN

When you perform a LEFT JOIN and place a filter on the right table in your WHERE clause:

sql
SELECT c.name, o.status
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
WHERE o.status = 'shipped'; -- BUG!

Because unmatched customers have NULL for o.status, the WHERE condition drops them, silently converting your query into an INNER JOIN. Fix: Move the filter into the ON clause:

sql
SELECT c.name, o.status
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id AND o.status = 'shipped';

1. Counting Rows vs Counting Values

  • COUNT(*) counts every row returned, including rows containing NULL values.
  • COUNT(column_name) counts only rows where column_name is non-NULL.
  • COUNT(DISTINCT column_name) counts unique non-NULL values.

For complete nuances, performance benchmarks, and partition examples, explore our dedicated guide to the SQL COUNT function.

2. Division by Zero Crashes

Wrap denominators in NULLIF to prevent catastrophic query failures:

sql
SELECT numerator / NULLIF(denominator, 0) AS safe_ratio;

If denominator is 0, NULLIF converts it to NULL, and numerator / NULL returns NULL instead of terminating the query.


When Analysts Rely on this SQL Cheat Sheet

Timed Technical Screening Rounds. Quickly verifying window function syntax (ROWS BETWEEN UNBOUNDED PRECEDING) during live coding assessments.

Data Warehouse Migrations. Ensuring ANSI SQL compatibility when transitioning legacy Oracle or MySQL scripts to Snowflake or PostgreSQL.

Ad-hoc Cohort Modeling. Stacking CTEs to compute month-over-month retention, customer lifetime value, and marketing channel attribution.


Production Query Safety and Troubleshooting Checklist

Before executing analytical queries against production read replicas or data warehouses, review this operational safety checklist:

  • Enforce Limit on Unindexed Queries: Always append LIMIT 100 during exploratory query authoring to prevent memory buffer exhaustion.
  • Audit Join Cardinality: Count distinct keys prior to joining: SELECT COUNT(*), COUNT(DISTINCT id) FROM table. Non-unique join keys cause silent Cartesian explosions.
  • Verify Column Slicing in Analytical Warehouses: In columnar cloud warehouses (Snowflake, BigQuery), avoid SELECT *. Selecting only the 4 required columns instead of all 80 columns reduces disk scan charges and execution latency by over 90%.
  • Use CTEs for Multi-Stage Readability: Break nested 4-level subqueries into modular Common Table Expressions. CTEs isolate grain changes, making queries auditable by peer reviewers.

Explore our SQL Tutorials hub and test your syntax on Topfolio Interactive Practice.

Set up a clean local PostgreSQL environment inside VS Code with our VS Code SQLTools PostgreSQL Guide.

Practice 190+ Interactive SQL Questions

Run queries directly inside your browser with instant telemetry and step-by-step diagnostic hints.

Start Practicing Now

Frequently Asked Questions

What is included in this SQL cheat sheet?

This SQL cheat sheet covers core query syntax, filtering operators, all 5 JOIN types, GROUP BY with HAVING, Window Functions (ROW_NUMBER, RANK, LAG, LEAD), Common Table Expressions (CTEs), and DDL/DML data manipulation commands.

What is the correct logical order of execution in SQL?

SQL queries execute in this exact logical sequence: 1. FROM & JOINs, 2. WHERE, 3. GROUP BY, 4. HAVING, 5. SELECT, 6. DISTINCT, 7. ORDER BY, and 8. LIMIT / OFFSET.

What is the difference between UNION and UNION ALL in SQL?

UNION merges two result sets and executes a distinct deduplication pass, removing duplicate rows. UNION ALL merges results without deduplication, making it substantially faster and preserving all records.

When should I use WHERE versus HAVING in SQL?

Use WHERE to filter individual raw rows before any grouping or aggregation takes place. Use HAVING to filter aggregated metrics produced by GROUP BY (such as HAVING COUNT(*) > 5).

What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?

ROW_NUMBER assigns unique sequential integers (1, 2, 3, 4). RANK assigns identical ranks to ties and skips subsequent numbers (1, 2, 2, 4). DENSE_RANK assigns identical ranks to ties without skipping numbers (1, 2, 2, 3).

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.