SQL Quick Reference
An interactive cheat sheet for modern SQL operations. Search, learn, and copy examples for PostgreSQL and MySQL.
Basic Queries (SELECT)
Retrieve, filter, sort, and paginate data from a single table.
Return only distinct (different) values.
Common operators used in the WHERE clause.
JOINs
Returns records that have matching values in both tables.
Often just written as JOIN.
Returns all records from the left (or right) table, and matched records from the other. Missing matches are NULL.
Returns all records when there is a match in either left or right table.
MySQL does not support FULL OUTER JOIN natively (requires UNION of LEFT and RIGHT joins).
Aggregation & GROUP BY
Group rows sharing a property and apply aggregate functions.
Filter results after aggregations are applied. (WHERE filters before).
Subqueries & CTEs
Queries nested inside another query.
Common Table Expressions make complex queries more readable than nested subqueries.
Window Functions
Perform calculations across a set of table rows related to the current row, without grouping them into a single output row.
Access data from a previous or subsequent row in the same result set. Great for calculating week-over-week changes.
PostgreSQL vs MySQL Specifics
| Operation | PostgreSQL | MySQL |
|---|---|---|
| String Concat | 'a' || 'b' |
CONCAT('a','b') |
| Current Date | CURRENT_DATE |
CURDATE() |
| Cast to Text | col::text |
CAST(col AS CHAR) |
| If Null | COALESCE(col, 0) |
IFNULL(col, 0) |
Useful features specific to Postgres.
Why Use This SQL Cheat Sheet?
Structured Query Language (SQL) remains the standard for interacting with relational databases like PostgreSQL, MySQL, SQL Server, and SQLite. Whether you are a data analyst writing complex reports, a backend engineer building APIs, or a beginner learning database fundamentals, having a quick reference for syntax and patterns saves time and reduces context switching.
Essential SQL Concepts
- DQL (Data Query Language): The
SELECTstatement and its clauses (WHERE,GROUP BY,HAVING,ORDER BY) form the core of data retrieval. - Data Relational Patterns: Understanding the difference between an
INNER JOIN(intersection) and aLEFT JOIN(preservation of the left table) is crucial for accurate data merging. - Advanced Analytics: Window functions like
ROW_NUMBER(),RANK(),LAG(), andLEAD()allow you to perform complex calculations across sets of rows without collapsing them into aggregate groups.
PostgreSQL vs MySQL Considerations
While standard SQL (ANSI SQL) works across most relational database management systems (RDBMS), dialects differ in syntax and capabilities. PostgreSQL is known for strict standards compliance, advanced data types (like JSONB and Arrays), and powerful features like the RETURNING clause. MySQL, heavily used in web applications, often requires specific syntax for string concatenation (CONCAT() instead of ||) and handles implicit type casting differently.