{"schemaVersion":"1.0","type":"TechArticle","types":["Article","TechArticle"],"slug":"sql-cheat-sheet-one-page-quick-reference-0rw5p","url":"https://zyvop.com/sql-cheat-sheet-one-page-quick-reference-0rw5p","title":"SQL Cheat Sheet: One-Page Quick Reference","subtitle":"A bookmark-worthy SQL reference covering queries, joins, window functions, and more, with diagrams and MySQL and SQL Server differences.","tldr":"Stop searching for syntax. This one-page SQL cheat sheet covers SELECT, joins, aggregates, CTEs, window functions, and data changes, with short examples, Mermaid diagrams, a PostgreSQL, MySQL, and SQL Server comparison table, and a checklist for safer queries.","keywords":["Window Functions","Quick Reference","SQL","databases","SQL Cheat Sheet","Databases"],"entities":["Alysaa Lissy","Window Functions","Quick Reference","SQL","databases","SQL Cheat Sheet","Databases","ZyVOP"],"keyTakeaways":["It covers the syntax you'll use most, with short examples and diagrams for the parts people forget.","Examples use PostgreSQL syntax; a dialect table near the end lists where MySQL and SQL Server differ.","flowchart TD Q{\"I want to...\"} Q --&gt; A[\"Read data\"] --&gt; A1[\"SELECT, WHERE, ORDER BY, LIMIT\"] Q --&gt; B[\"Summarize data\"] --&gt; B1[\"COUNT, SUM, GROUP BY, HAVING\"] Q --&gt; C[\"Combine tables\"] --&gt; C1[\"JOIN, UNION\"] Q --&gt; D[\"Compare rows\"] --&gt; D1[\"Window functions, CTEs\"] Q --&gt; E[\"Change data\"] --&gt; E1[\"INSERT, UPDATE, DELETE\"] Q --&gt; F[\"Build structure\"] --&gt; F1[\"CREATE, ALTER, INDEX\"]The examples use these two tables: erDiagram CUSTOMERS ||--o{ ORDERS : places CUSTOMERS { int customer_id PK string first_name string phone string city } ORDERS { int order_id PK int customer_id FK date order_date decimal amount string status }1."],"headings":["1. Query Anatomy","2. Filtering with WHERE","3. Aggregates and Grouping","4. Joins","5. Common Functions","CASE expression","6. Subqueries, CTEs, and Set Operations","7. Window Functions","8. Changing Data","Transactions","9. Defining Structure","10. Dialect Differences","11. Pre-Flight Checklist"],"outboundLinks":[],"contentText":"Bookmark this page. It covers the syntax you'll use most, with short examples and diagrams for the parts people forget. Examples use PostgreSQL syntax; a dialect table near the end lists where MySQL and SQL Server differ. flowchart TD Q{\"I want to...\"} Q --&gt; A[\"Read data\"] --&gt; A1[\"SELECT, WHERE, ORDER BY, LIMIT\"] Q --&gt; B[\"Summarize data\"] --&gt; B1[\"COUNT, SUM, GROUP BY, HAVING\"] Q --&gt; C[\"Combine tables\"] --&gt; C1[\"JOIN, UNION\"] Q --&gt; D[\"Compare rows\"] --&gt; D1[\"Window functions, CTEs\"] Q --&gt; E[\"Change data\"] --&gt; E1[\"INSERT, UPDATE, DELETE\"] Q --&gt; F[\"Build structure\"] --&gt; F1[\"CREATE, ALTER, INDEX\"]The examples use these two tables: erDiagram CUSTOMERS ||--o{ ORDERS : places CUSTOMERS { int customer_id PK string first_name string phone string city } ORDERS { int order_id PK int customer_id FK date order_date decimal amount string status }1. Query Anatomy SELECT c.city, COUNT(*) AS order_count -- what to return FROM customers c -- where it comes from JOIN orders o ON o.customer_id = c.customer_id -- combine tables WHERE o.status = 'completed' -- filter rows GROUP BY c.city -- build groups HAVING COUNT(*) &gt; 5 -- filter groups ORDER BY order_count DESC -- sort LIMIT 10 OFFSET 20; -- paginateAdd DISTINCT after SELECT to remove duplicate result rows. You write SELECT first, but SQL processes the query in the logical order below, which is why most databases reject aliases and aggregates in WHERE: flowchart LR A[\"FROM / JOIN\"] --&gt; B[\"WHERE&lt;br/&gt;filter rows\"] B --&gt; C[\"GROUP BY&lt;br/&gt;make groups\"] C --&gt; D[\"HAVING&lt;br/&gt;filter groups\"] D --&gt; E[\"SELECT&lt;br/&gt;window functions, aliases\"] E --&gt; F[\"DISTINCT\"] F --&gt; G[\"ORDER BY\"] G --&gt; H[\"LIMIT / OFFSET\"]2. Filtering with WHERE Operator Example Meaning =, &lt;&gt; status = 'completed' Equal, not equal (!= also works in most databases) &lt;, &lt;=, &gt;, &gt;= amount &gt;= 100 Comparison BETWEEN amount BETWEEN 10 AND 50 Inclusive on both ends IN city IN ('Paris', 'Rome') Matches any value in the list LIKE first_name LIKE 'A%' % = any characters, _ = one character IS NULL phone IS NULL Missing value (never use = NULL) AND, OR, NOT (a OR b) AND c Combine conditions; use parentheses 3. Aggregates and Grouping Function Returns NULLs COUNT(*) Number of rows Counted COUNT(col) Number of non-NULL values Skipped COUNT(DISTINCT col) Number of unique non-NULL values Skipped SUM, AVG, MIN, MAX Total, mean, smallest, largest Skipped SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS total FROM orders WHERE status = 'completed' -- filters rows before grouping GROUP BY customer_id HAVING SUM(amount) &gt; 1000 -- filters groups after aggregating ORDER BY total DESC;Rule: every non-aggregated column in SELECT must be listed in GROUP BY. 4. Joins SELECT c.first_name, o.amount FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id;Join Keeps INNER JOIN Only rows that match in both tables LEFT JOIN All left rows, plus matches from the right (NULL if none) RIGHT JOIN All right rows, plus matches from the left FULL JOIN All rows from both tables CROSS JOIN Every left row paired with every right row Joining Table A (ids 1, 2, 3) with Table B (ids 2, 3, 4) on id: flowchart LR A[\"Table A&lt;br/&gt;ids: 1, 2, 3\"] B[\"Table B&lt;br/&gt;ids: 2, 3, 4\"] A --&gt; I[\"INNER JOIN&lt;br/&gt;2, 3\"] B --&gt; I A --&gt; L[\"LEFT JOIN&lt;br/&gt;1, 2, 3\"] B --&gt; L A --&gt; R[\"RIGHT JOIN&lt;br/&gt;2, 3, 4\"] B --&gt; R A --&gt; F[\"FULL JOIN&lt;br/&gt;1, 2, 3, 4\"] B --&gt; FTip: to filter the right table of a LEFT JOIN, put the condition in ON, not WHERE; a WHERE condition on right-side columns silently turns it into an inner join. The one exception is WHERE o.order_id IS NULL, which finds left rows with no match. 5. Common Functions Type Functions Text UPPER(s), LOWER(s), TRIM(s), LENGTH(s), SUBSTRING(s, start, len), REPLACE(s, from, to), CONCAT(a, b) Numeric ROUND(x, n), CEIL(x) / CEILING(x), FLOOR(x), ABS(x), MOD(x, y) or x % y NULL handling COALESCE(a, b, ...) first non-NULL; NULLIF(a, b) returns NULL if equal Dates CURRENT_DATE, CURRENT_TIMESTAMP, EXTRACT(YEAR FROM d), DATE_TRUNC('month', d) (date functions vary a lot; see the dialect table) Conversion CAST(x AS type) (PostgreSQL also accepts x::type) CASE expression SELECT order_id, CASE WHEN amount &gt;= 500 THEN 'large' WHEN amount &gt;= 100 THEN 'medium' ELSE 'small' END AS order_size FROM orders;6. Subqueries, CTEs, and Set Operations -- CTE: a named, reusable subquery WITH big_spenders AS ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id HAVING SUM(amount) &gt; 1000 ) SELECT c.first_name, b.total FROM big_spenders b JOIN customers c ON c.customer_id = b.customer_id; -- EXISTS: does a related row exist? SELECT first_name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id); -- Prefer NOT EXISTS over NOT IN when the subquery can return NULL SELECT first_name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);Operator Result UNION Rows from both queries, duplicates removed UNION ALL Rows from both queries, duplicates kept (faster) INTERSECT Rows that appear in both EXCEPT Rows in the first but not the second (MINUS in Oracle) Both queries need the same number of columns with compatible types. (MySQL supports INTERSECT and EXCEPT from version 8.0.31.) 7. Window Functions Window functions calculate across related rows without collapsing them into one row. SELECT order_id, customer_id, amount, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn, LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_amount, SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM orders;PARTITION BY splits rows into groups, ORDER BY orders rows inside each group. Here's how the ranking functions treat ties, for scores 100, 100, 90: Score ROW_NUMBER() RANK() DENSE_RANK() 100 1 1 1 100 2 1 1 90 3 3 2 Other useful ones: LEAD() (next row), NTILE(n) (split into n buckets), FIRST_VALUE(). You can't filter on a window function in WHERE. To keep only rn = 1, wrap the query in a CTE or subquery first. 8. Changing Data INSERT INTO customers (first_name, city) VALUES ('Anna', 'London'); -- assumes customer_id auto-generates UPDATE orders SET status = 'cancelled' WHERE order_id = 1042; DELETE FROM orders WHERE order_id = 1042; -- Upsert (PostgreSQL) INSERT INTO customers (customer_id, first_name) VALUES (1, 'Anna') ON CONFLICT (customer_id) DO UPDATE SET first_name = EXCLUDED.first_name;Always include WHERE on UPDATE and DELETE. Without it, every row is changed. Test the filter with a SELECT first. Transactions BEGIN; -- START TRANSACTION in MySQL, BEGIN TRANSACTION in SQL Server UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- or ROLLBACK; to undo everything since BEGIN9. Defining Structure CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT NOT NULL, order_date DATE NOT NULL DEFAULT CURRENT_DATE, amount DECIMAL(10,2) CHECK (amount &gt;= 0), status VARCHAR(20), FOREIGN KEY (customer_id) REFERENCES customers (customer_id) ); ALTER TABLE orders ADD COLUMN notes TEXT; ALTER TABLE orders DROP COLUMN notes; CREATE INDEX idx_orders_customer ON orders (customer_id); TRUNCATE TABLE orders; -- destructive: deletes all rows, keeps the table DROP TABLE orders; -- destructive: deletes the table itselfType Use for INT, BIGINT Whole numbers, IDs DECIMAL(p, s) Money and exact numbers (avoid FLOAT for money) VARCHAR(n), TEXT Text DATE, TIMESTAMP Dates and date-times BOOLEAN True / false (BIT in SQL Server) 10. Dialect Differences Task PostgreSQL MySQL SQL Server Limit rows LIMIT 10 LIMIT 10 SELECT TOP 10 or OFFSET ... FETCH Current date CURRENT_DATE CURRENT_DATE CAST(GETDATE() AS DATE) Current timestamp NOW() NOW() GETDATE() Year of a date EXTRACT(YEAR FROM d) EXTRACT(YEAR FROM d) or YEAR(d) YEAR(d) or DATEPART(year, d) Truncate to month DATE_TRUNC('month', d) DATE_FORMAT(d, '%Y-%m-01') (text result) DATETRUNC(month, d) (2022+) Concatenate text CONCAT() or the double-pipe operator CONCAT() CONCAT() or + Text length LENGTH() CHAR_LENGTH() LEN() Auto-increment ID GENERATED ... AS IDENTITY AUTO_INCREMENT IDENTITY(1,1) Upsert ON CONFLICT ON DUPLICATE KEY UPDATE MERGE Full outer join FULL JOIN Not supported FULL JOIN 11. Pre-Flight Checklist Use IS NULL, not = NULL. Filter groups with HAVING, rows with WHERE. Every join except CROSS JOIN needs an ON condition. Every LIMIT needs an ORDER BY. Every UPDATE and DELETE needs a WHERE, tested with SELECT first. Use NOT EXISTS instead of NOT IN when NULLs are possible. Keep this page open while you work, and most day-to-day queries become a matter of looking up the pattern and filling in your table and column names.","contentHash":"sha256:7f8a09220ac1a738bd6053ed20f81ba7009fd81d3cc6d1221fc0910f62e0ed44","authorName":"Alysaa Lissy","authorUrl":"https://zyvop.com/author/alysaa","authorSameAs":[],"category":"Databases","tags":["Window Functions","Quick Reference","SQL","databases","SQL Cheat Sheet"],"audience":"Software engineers and developers building applications with Databases","tone":"Instructional, practical, code-first","readingTimeMinutes":6,"wordCount":1389,"faqs":null,"primaryTopic":"Databases","publishedAt":"2026-11-21T05:53:53.624Z","updatedAt":"2026-11-21T05:54:56.495Z","canonicalUrl":"https://zyvop.com/sql-cheat-sheet-one-page-quick-reference-0rw5p"}