This comprehensive SQL cheat sheet acts as that essential desk reference. Whether you are prepping for a technical interview or writing clean production code, this guide maps out everything you need to know.
SQL Cheat Sheet
The Foundation: Basic Data Retrieval
Every data journey starts with querying. Data Query Language (DQL) allows you to extract records from a database without altering the underlying structures or data blocks. The cornerstone of DQL is the SELECT statement.
The Standard Select Syntax
To extract data cleanly, you must order your clauses precisely as expected by the database engine parser.
SQL
SELECT column_1, column_2
FROM table_name;Filtering with Precision
To prevent pulling millions of unnecessary rows across your network, use conditional filters to pinpoint exactly what you need.
WHERE: Filters data rows based on explicit conditions before any groupings are applied.AND/OR: Combines multiple logical expressions to narrow or broaden your search scope.IN: Evaluates whether a value matches any item within a specified list or subquery output.BETWEEN: Filters values within a defined inclusive range (ideal for numeric or date ranges).LIKE: Performs string pattern matching using standard wildcard symbols (%for zero or more characters,_for a single character).IS NULL/IS NOT NULL: Specifically identifies rows containing missing or populated data blocks.
SQL
SELECT product_name, unit_price
FROM inventory
WHERE category = 'Electronics'
AND unit_price BETWEEN 50 AND 500;Sorting and Restricting Outputs
Once data is filtered, organizing the presentation layout ensures readability for analytical reporting tools.
ORDER BY: Sorts the resulting records by one or more columns in ascending (ASC, default) or descending (DESC) order.LIMIT/TOP/FETCH FIRST: Restricts the total number of records returned by the engine (syntax varies across PostgreSQL, SQL Server, and Oracle).
Modifying Data: DML Operations
When you move past reading data and begin modifying the contents of your tables, you enter the realm of Data Manipulation Language (DML). These commands are transactional, meaning they can be safely wrapped in transaction blocks and rolled back if an issue arises.
Appending Records with INSERT
The INSERT command adds brand-new rows to a designated table structure. You can populate all columns or explicitly target a subset of fields.
SQL
INSERT INTO customers (customer_id, first_name, last_name, state)
VALUES (5001, 'David', 'Foster', 'Texas');Modifying Records with UPDATE
The UPDATE command alters existing records. It is critical to pair an UPDATE statement with a specific filter to prevent making accidental, sweeping changes across your entire database.
SQL
UPDATE customers
SET state = 'California'
WHERE customer_id = 5001;Removing Records with DELETE
The DELETE command surgically extracts specific data rows from a table while keeping the structure, column definitions, and indexes intact.
SQL
DELETE FROM customers
WHERE customer_id = 5001;Data Aggregation and Summary Functions
Aggregate functions process a collection of values to return a single, meaningful metric.
Essential Aggregate Functions
COUNT(): Calculates the total number of rows matching the query criteria.SUM(): Adds up the total numeric value of a designated column.AVG(): Computes the mathematical average of a numeric dataset.MIN(): Pinpoints the lowest absolute value within a column.MAX(): Identifies the highest absolute value within a column.
Grouping and Evaluating Summaries
To aggregate data across specific dimensions (such as finding total sales per state), you must use structural grouping clauses.
GROUP BY: Separates data rows into summary buckets based on one or more grouping columns.HAVING: Filters the resulting aggregated groups after theGROUP BYclause executes. Note that theWHEREclause cannot filter aggregated functions.
SQL
SELECT state, COUNT(customer_id), AVG(annual_spend)
FROM marketing_data
WHERE account_status = 'Active'
GROUP BY state
HAVING AVG(annual_spend) > 1000;Bridging Tables: The SQL JOIN Reference
In normalized relational database systems, information is intentionally spread across separate tables to minimize redundancy. To recombine this data into a meaningful view, you use JOIN operations.
The Four Primary JOIN Types
INNER JOIN: Returns only the data rows that have perfectly matching values in both tables.LEFT JOIN(orLEFT OUTER JOIN): Fetches all records from the left table, along with any matching records from the right table. Unmatched right-side columns populate asNULL.RIGHT JOIN(orRIGHT OUTER JOIN): Fetches all records from the right table, along with any matching records from the left table. Unmatched left-side columns populate asNULL.FULL JOIN(orFULL OUTER JOIN): Combines the logic of both Left and Right joins, returning all records when a match exists in either table.
SQL
SELECT o.order_id, c.last_name, o.order_date
FROM orders o
INNER JOIN customers c
ON o.customer_id = c.customer_id;Structuring the Database: DDL Operations
Data Definition Language (DDL) commands act as the blueprint architects of your environment. They build, modify, and drop the literal database structures, tables, schemas, and configurations. DDL changes generally auto-commit instantly in most enterprise engines.
CREATE TABLE
Establishes a new table structure, defining column names, storage data types, and integrity constraints.
SQL
CREATE TABLE product_catalog (
sku_id INT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
release_date DATE,
inventory_count INT DEFAULT 0
);
ALTER TABLE
Modifies the architecture of an existing table object without losing the data rows stored within it.
SQL
ALTER TABLE product_catalog ADD COLUMN wholesale_cost DECIMAL(10, 2);DROP TABLE vs. TRUNCATE TABLE
DROP TABLE: Permanently destroys the entire table structure, its columns, its indexes, its triggers, and all underlying data rows from the disk catalog.TRUNCATE TABLE: Instantly clears all rows out of a table, resetting auto-incrementing identity keys, while keeping the structural layout intact for future data input.
Comprehensive SQL Syntax Quick Reference
| Operation / Command | Syntax Blueprint | Primary Use Case | Category |
| Basic Query | SELECT cols FROM tbl WHERE cond; | Fetching filtered records | DQL |
| Insert Data | INSERT INTO tbl (cols) VALUES (vals); | Appending new rows | DML |
| Update Data | UPDATE tbl SET col = val WHERE cond; | Modifying existing rows | DML |
| Delete Data | DELETE FROM tbl WHERE cond; | Removing targeted rows | DML |
| Truncate Table | TRUNCATE TABLE tbl; | High-speed complete row purge | DDL |
| Create Table | CREATE TABLE tbl (col type const); | Building a new schema layout | DDL |
| Alter Schema | ALTER TABLE tbl ADD col type; | Modifying an existing schema | DDL |
| Drop Object | DROP TABLE tbl; | Permanent deletion of an object | DDL |
| Inner Join | SELECT * FROM t1 INNER JOIN t2 ON t1.id = t2.id; | Matching intersecting records | DQL |
| Left Join | SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id; | Preserving left-side master lists | DQL |
Advanced SQL Concepts for High-Performance Architectures
Subqueries and Nested Logic
A subquery is an inner query nested within another parent SQL statement (such as a SELECT, INSERT, or DELETE). Subqueries compute an intermediate dataset that the outer query uses to finalize its filtering execution path.
SQL
SELECT employee_name, base_salary
FROM corporate_payroll
WHERE base_salary > (SELECT AVG(base_salary) FROM corporate_payroll);Common Table Expressions (CTEs)
While subqueries are highly effective, deeply nested subqueries can become incredibly hard to read and maintain. Common Table Expressions (CTEs) provide a cleaner approach by creating named, temporary result sets that exist solely within the execution scope of that single query.
SQL
WITH regional_sales_cte AS (
SELECT region, SUM(order_total) AS total_revenue
FROM retail_orders
GROUP BY region
)
SELECT region, total_revenue
FROM regional_sales_cte
WHERE total_revenue > 500000;
Using a CTE makes your complex queries read sequentially, which simplifies code reviews and debugging sessions for engineering teams.
Rules for Safe SQL Execution
Here are the core rules I implement across enterprise production environments.
- Capitalize Reserved Keywords: Always write core syntax operations (
SELECT,FROM,JOIN,WHERE) in all-caps. This separates the programmatic commands from your unique schema tables and column variables, making your code highly scannable. - The SELECT Verification Step: Before running a destructive
UPDATEorDELETEstatement, take your exact filtering parameters and run them as aSELECT *query first. Review the output to ensure you are modifying the exact records you intend to change. - Use Transaction Blocks for Critical Edits: When altering high-value data blocks, wrap your operations within explicit transaction controls (
BEGIN TRANSACTIONandCOMMITorROLLBACK). This gives you a safe testing layer to review the row impact before making the changes permanent on the physical storage system.
You may also like the following articles:
After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a Microsoft MVP. Check out more here.