SQL Cheat Sheet
A complete reference of SQL commands with examples and usage instructions. Find the command you need using the search bar or browse by category.
SELECT
BasicRetrieve data from one or more tables
Syntax:
SELECT column1, column2 FROM table_name WHERE condition
Examples:
SELECT * FROM users;
Select all columns from users tableSELECT name, email FROM users;
Select specific columnsSELECT * FROM users WHERE age > 25;
Select with conditionSELECT COUNT(*) FROM users;
Count total rowsNotes:
The most fundamental SQL command for querying data
INSERT
BasicAdd new rows to a table
Syntax:
INSERT INTO table_name (column1, column2) VALUES (value1, value2)
Examples:
INSERT INTO users (name, email) VALUES ('John', 'john@email.com');
Insert single rowINSERT INTO users VALUES ('Jane', 'jane@email.com', 30);
Insert without specifying columnsINSERT INTO users (name, email) VALUES ('Bob', 'bob@email.com'), ('Alice', 'alice@email.com');
Insert multiple rowsNotes:
Use specific column names for better maintainability
UPDATE
BasicModify existing data in a table
Syntax:
UPDATE table_name SET column1 = value1 WHERE condition
Examples:
UPDATE users SET age = 31 WHERE name = 'John';
Update specific rowUPDATE users SET email = 'newemail@domain.com', age = age + 1;
Update multiple columnsUPDATE users SET status = 'active' WHERE created_date > '2023-01-01';
Update with date conditionNotes:
Always use WHERE clause to avoid updating all rows accidentally
DELETE
BasicRemove rows from a table
Syntax:
DELETE FROM table_name WHERE condition
Examples:
DELETE FROM users WHERE id = 5;
Delete specific rowDELETE FROM users WHERE age < 18;
Delete multiple rowsDELETE FROM users;
Delete all rows (use with caution)Notes:
Always use WHERE clause unless you really want to delete all rows
CREATE DATABASE
DatabaseCreate a new database
Syntax:
CREATE DATABASE database_name
Examples:
CREATE DATABASE myapp;
Create a new databaseCREATE DATABASE IF NOT EXISTS myapp;
Create only if doesn't existCREATE DATABASE myapp CHARACTER SET utf8mb4;
Create with specific character setNotes:
Database names should follow naming conventions
DROP DATABASE
DatabaseDelete an entire database
Syntax:
DROP DATABASE database_name
Examples:
DROP DATABASE myapp;
Delete database permanentlyDROP DATABASE IF EXISTS myapp;
Delete only if existsNotes:
This permanently deletes all data - use with extreme caution
USE
DatabaseSelect a database to work with
Syntax:
USE database_name
Examples:
USE myapp;
Switch to myapp databaseUSE information_schema;
Switch to system databaseNotes:
Must select a database before performing table operations
SHOW DATABASES
DatabaseList all databases
Syntax:
SHOW DATABASES
Examples:
SHOW DATABASES;
List all available databasesSHOW DATABASES LIKE 'app%';
List databases matching patternNotes:
Useful for exploring available databases
CREATE TABLE
TablesCreate a new table
Syntax:
CREATE TABLE table_name (column1 datatype, column2 datatype)
Examples:
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100), email VARCHAR(255));
Create simple tableCREATE TABLE posts (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), content TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Create table with auto-increment and timestampCREATE TABLE IF NOT EXISTS categories (id INT PRIMARY KEY, name VARCHAR(50) UNIQUE);
Create only if doesn't existNotes:
Define appropriate data types and constraints for each column
ALTER TABLE
TablesModify an existing table structure
Syntax:
ALTER TABLE table_name ADD/DROP/MODIFY column_name datatype
Examples:
ALTER TABLE users ADD phone VARCHAR(20);
Add new columnALTER TABLE users DROP COLUMN phone;
Remove columnALTER TABLE users MODIFY email VARCHAR(320);
Change column typeALTER TABLE users RENAME TO customers;
Rename tableNotes:
Be careful when modifying tables with existing data
DROP TABLE
TablesDelete a table and all its data
Syntax:
DROP TABLE table_name
Examples:
DROP TABLE users;
Delete table permanentlyDROP TABLE IF EXISTS temp_table;
Delete only if existsNotes:
This permanently deletes the table and all data
DESCRIBE
TablesShow table structure
Syntax:
DESCRIBE table_name
Examples:
DESCRIBE users;
Show column detailsDESC users;
Short form of DESCRIBESHOW COLUMNS FROM users;
Alternative syntaxNotes:
Useful for understanding table schema
INNER JOIN
JoinsReturn rows that have matching values in both tables
Syntax:
SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column
Examples:
SELECT u.name, p.title FROM users u INNER JOIN posts p ON u.id = p.user_id;
Join users with their postsSELECT * FROM orders o INNER JOIN customers c ON o.customer_id = c.id;
Join orders with customer detailsNotes:
Only returns rows where the join condition is met in both tables
LEFT JOIN
JoinsReturn all rows from left table and matching rows from right table
Syntax:
SELECT columns FROM table1 LEFT JOIN table2 ON table1.column = table2.column
Examples:
SELECT u.name, p.title FROM users u LEFT JOIN posts p ON u.id = p.user_id;
All users, with posts if they existSELECT c.name, COUNT(o.id) FROM customers c LEFT JOIN orders o ON c.id = o.customer_id GROUP BY c.id;
Customer order countsNotes:
Includes all rows from the left table, even if no match in right table
RIGHT JOIN
JoinsReturn all rows from right table and matching rows from left table
Syntax:
SELECT columns FROM table1 RIGHT JOIN table2 ON table1.column = table2.column
Examples:
SELECT u.name, p.title FROM users u RIGHT JOIN posts p ON u.id = p.user_id;
All posts, with user info if availableNotes:
Less commonly used than LEFT JOIN
FULL OUTER JOIN
JoinsReturn rows when there is a match in either table
Syntax:
SELECT columns FROM table1 FULL OUTER JOIN table2 ON table1.column = table2.column
Examples:
SELECT u.name, p.title FROM users u FULL OUTER JOIN posts p ON u.id = p.user_id;
All users and all postsNotes:
Not supported in all databases (e.g., MySQL)
COUNT
FunctionsCount the number of rows
Syntax:
COUNT(column_name) or COUNT(*)
Examples:
SELECT COUNT(*) FROM users;
Count all rowsSELECT COUNT(email) FROM users;
Count non-null emailsSELECT status, COUNT(*) FROM users GROUP BY status;
Count by groupNotes:
COUNT(*) includes NULL values, COUNT(column) excludes them
SUM
FunctionsCalculate the sum of numeric values
Syntax:
SUM(column_name)
Examples:
SELECT SUM(amount) FROM orders;
Total order amountSELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id;
Sum by customerNotes:
Only works with numeric columns
AVG
FunctionsCalculate the average of numeric values
Syntax:
AVG(column_name)
Examples:
SELECT AVG(age) FROM users;
Average user ageSELECT department, AVG(salary) FROM employees GROUP BY department;
Average salary by departmentNotes:
Automatically excludes NULL values from calculation
MIN/MAX
FunctionsFind minimum or maximum values
Syntax:
MIN(column_name) or MAX(column_name)
Examples:
SELECT MIN(price), MAX(price) FROM products;
Price rangeSELECT MIN(created_date) FROM users;
First user registrationNotes:
Works with numeric, date, and string columns
CONCAT
FunctionsConcatenate strings
Syntax:
CONCAT(string1, string2, ...)
Examples:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
Combine first and last nameSELECT CONCAT('Hello, ', name, '!') FROM users;
Create greeting messageNotes:
Use CONCAT_WS for separator-based concatenation
SUBSTRING
FunctionsExtract part of a string
Syntax:
SUBSTRING(string, start, length)
Examples:
SELECT SUBSTRING(email, 1, POSITION('@' IN email) - 1) AS username FROM users;
Extract username from emailSELECT SUBSTRING(phone, 1, 3) AS area_code FROM contacts;
Extract area codeNotes:
Position starts from 1, not 0
UPPER/LOWER
FunctionsConvert string case
Syntax:
UPPER(string) or LOWER(string)
Examples:
SELECT UPPER(name) FROM users;
Convert to uppercaseSELECT LOWER(email) FROM users;
Convert to lowercaseNotes:
Useful for case-insensitive comparisons
WHERE
FilteringFilter rows based on conditions
Syntax:
WHERE condition
Examples:
SELECT * FROM users WHERE age >= 18;
Numeric comparisonSELECT * FROM users WHERE name LIKE 'John%';
Pattern matchingSELECT * FROM users WHERE email IS NOT NULL;
NULL checkSELECT * FROM users WHERE age BETWEEN 25 AND 35;
Range conditionNotes:
Use appropriate operators: =, !=, <, >, <=, >=, LIKE, IN, BETWEEN
ORDER BY
FilteringSort query results
Syntax:
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC]
Examples:
SELECT * FROM users ORDER BY name;
Sort by name (ascending)SELECT * FROM users ORDER BY age DESC;
Sort by age (descending)SELECT * FROM users ORDER BY last_name, first_name;
Sort by multiple columnsNotes:
ASC is default, use DESC for descending order
GROUP BY
FilteringGroup rows that have the same values
Syntax:
GROUP BY column1, column2
Examples:
SELECT department, COUNT(*) FROM employees GROUP BY department;
Count employees by departmentSELECT status, AVG(age) FROM users GROUP BY status;
Average age by statusNotes:
Must use aggregate functions with non-grouped columns
HAVING
FilteringFilter groups based on aggregate conditions
Syntax:
HAVING condition
Examples:
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
Departments with more than 5 employeesSELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id HAVING SUM(amount) > 1000;
High-value customersNotes:
Use HAVING for aggregate conditions, WHERE for row conditions
LIMIT
FilteringLimit the number of rows returned
Syntax:
LIMIT number [OFFSET number]
Examples:
SELECT * FROM users LIMIT 10;
Get first 10 usersSELECT * FROM users ORDER BY created_date DESC LIMIT 5;
Get 5 newest usersSELECT * FROM users LIMIT 10 OFFSET 20;
Skip 20 rows, then get 10Notes:
Useful for pagination and performance optimization
Subquery
AdvancedQuery within another query
Syntax:
SELECT ... WHERE column IN (SELECT ...)
Examples:
SELECT * FROM users WHERE id IN (SELECT user_id FROM orders);
Users who have ordersSELECT * FROM products WHERE price > (SELECT AVG(price) FROM products);
Products above average priceNotes:
Can be used in SELECT, WHERE, and FROM clauses
UNION
AdvancedCombine results from multiple queries
Syntax:
SELECT ... UNION SELECT ...
Examples:
SELECT name FROM customers UNION SELECT name FROM suppliers;
All names from both tablesSELECT 'Customer' as type, name FROM customers UNION SELECT 'Supplier', name FROM suppliers;
Combined with type indicatorNotes:
UNION removes duplicates, use UNION ALL to keep them
CASE
AdvancedConditional logic in SQL
Syntax:
CASE WHEN condition THEN result ELSE result END
Examples:
SELECT name, CASE WHEN age >= 18 THEN 'Adult' ELSE 'Minor' END as category FROM users;
Categorize by ageSELECT name, CASE status WHEN 'active' THEN 'Active User' WHEN 'inactive' THEN 'Inactive User' ELSE 'Unknown' END FROM users;
Status labelsNotes:
Useful for creating computed columns and conditional logic
CREATE INDEX
PerformanceCreate an index to improve query performance
Syntax:
CREATE INDEX index_name ON table_name (column1, column2)
Examples:
CREATE INDEX idx_email ON users (email);
Index on email columnCREATE INDEX idx_name_age ON users (last_name, first_name);
Composite indexCREATE UNIQUE INDEX idx_username ON users (username);
Unique indexNotes:
Indexes speed up queries but slow down writes
EXPLAIN
PerformanceShow query execution plan
Syntax:
EXPLAIN SELECT ...
Examples:
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
Analyze query performanceEXPLAIN ANALYZE SELECT * FROM orders JOIN customers ON orders.customer_id = customers.id;
Detailed execution analysisNotes:
Essential for query optimization and performance tuning
PRIMARY KEY
ConstraintsDefine a primary key constraint
Syntax:
column_name datatype PRIMARY KEY
Examples:
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100));
Single column primary keyCREATE TABLE order_items (order_id INT, product_id INT, PRIMARY KEY (order_id, product_id));
Composite primary keyNotes:
Ensures uniqueness and creates clustered index
FOREIGN KEY
ConstraintsDefine a foreign key constraint
Syntax:
FOREIGN KEY (column) REFERENCES table(column)
Examples:
CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(id));
Basic foreign keyALTER TABLE posts ADD FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
Add foreign key with cascade deleteNotes:
Maintains referential integrity between tables
UNIQUE
ConstraintsEnsure column values are unique
Syntax:
column_name datatype UNIQUE
Examples:
CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255) UNIQUE);
Unique email constraintALTER TABLE users ADD CONSTRAINT uk_username UNIQUE (username);
Add unique constraintNotes:
Prevents duplicate values in specified columns
NOT NULL
ConstraintsEnsure column cannot be empty
Syntax:
column_name datatype NOT NULL
Examples:
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100) NOT NULL);
Required name fieldALTER TABLE users MODIFY email VARCHAR(255) NOT NULL;
Make existing column requiredNotes:
Prevents NULL values in specified columns
SQL Best Practices
Query Optimization
- Use
SELECT
with specific columns instead ofSELECT *
- Always use
WHERE
clauses to limit results - Create indexes on frequently queried columns
- Use
LIMIT
for large datasets - Avoid functions in
WHERE
clauses - Use
EXPLAIN
to analyze query performance
Data Safety
- Always backup before running
DROP
orDELETE
- Test queries on small datasets first
- Use transactions for multiple related operations
- Include
WHERE
clauses inUPDATE
andDELETE
- Use appropriate data types and constraints
- Normalize your database design