AI Generate SQL docs instantly

SQL Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

SELECT Queries

7 snippets

Basic Select

SELECT * FROM users;

Columns

SELECT name, email FROM users;

Where

SELECT * FROM users WHERE age > 18;

AND/OR

SELECT * FROM users WHERE age > 18 AND status = 'active';

Order By

SELECT * FROM users ORDER BY name ASC;

Limit

SELECT * FROM users LIMIT 10 OFFSET 20;

Distinct

SELECT DISTINCT country FROM users;

JOINs

4 snippets

Inner Join

SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id;

Left Join

SELECT u.name, o.total
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;

Right Join

SELECT u.name, o.total
FROM users u
RIGHT JOIN orders o ON u.id = o.user_id;

Full Join

SELECT u.name, o.total
FROM users u
FULL OUTER JOIN orders o ON u.id = o.user_id;

Aggregate Functions

6 snippets

Count

SELECT COUNT(*) FROM users;

Sum

SELECT SUM(amount) FROM orders;

Avg

SELECT AVG(price) FROM products;

Min/Max

SELECT MIN(age), MAX(age) FROM users;

Group By

SELECT country, COUNT(*)
FROM users
GROUP BY country;

Having

SELECT country, COUNT(*)
FROM users
GROUP BY country
HAVING COUNT(*) > 10;

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Data Modification

4 snippets

Insert

INSERT INTO users (name, email)
VALUES ('John', 'john@example.com');

Insert Multiple

INSERT INTO users (name, email) VALUES
('John', 'john@example.com'),
('Jane', 'jane@example.com');

Update

UPDATE users
SET status = 'active'
WHERE id = 1;

Delete

DELETE FROM users WHERE id = 1;

Table Operations

4 snippets

Create Table

CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(255) UNIQUE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Alter Table

ALTER TABLE users ADD COLUMN phone VARCHAR(20);

Drop Table

DROP TABLE IF EXISTS users;

Truncate

TRUNCATE TABLE users;

Subqueries & CTEs

3 snippets

Subquery

SELECT * FROM users
WHERE id IN (
  SELECT user_id FROM orders WHERE total > 100
);

CTE

WITH active_users AS (
  SELECT * FROM users WHERE status = 'active'
)
SELECT * FROM active_users WHERE age > 18;

Exists

SELECT * FROM users u
WHERE EXISTS (
  SELECT 1 FROM orders o WHERE o.user_id = u.id
);

Indexes

4 snippets

Create Index

CREATE INDEX idx_email ON users(email);

Unique Index

CREATE UNIQUE INDEX idx_email ON users(email);

Composite Index

CREATE INDEX idx_name_email ON users(name, email);

Drop Index

DROP INDEX idx_email ON users;

Window Functions

6 snippets

Calculations across row sets

ROW_NUMBER

SELECT name, salary,
  ROW_NUMBER() OVER (ORDER BY salary DESC) as rank
FROM employees;

RANK / DENSE_RANK

SELECT name, salary,
  RANK() OVER (ORDER BY salary DESC) as rank,
  DENSE_RANK() OVER (ORDER BY salary DESC) as dense_rank
FROM employees;

PARTITION BY

SELECT department, name, salary,
  ROW_NUMBER() OVER (
    PARTITION BY department
    ORDER BY salary DESC
  ) as dept_rank
FROM employees;

LAG / LEAD

SELECT date, amount,
  LAG(amount, 1) OVER (ORDER BY date) as prev_amount,
  LEAD(amount, 1) OVER (ORDER BY date) as next_amount
FROM sales;

Running Total

SELECT date, amount,
  SUM(amount) OVER (
    ORDER BY date
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  ) as running_total
FROM sales;

NTILE

SELECT name, salary,
  NTILE(4) OVER (ORDER BY salary) as quartile
FROM employees;

CASE Expressions

4 snippets

Conditional logic in queries

Simple CASE

SELECT name,
  CASE status
    WHEN 'A' THEN 'Active'
    WHEN 'I' THEN 'Inactive'
    ELSE 'Unknown'
  END as status_name
FROM users;

Searched CASE

SELECT name, salary,
  CASE
    WHEN salary > 100000 THEN 'High'
    WHEN salary > 50000 THEN 'Medium'
    ELSE 'Low'
  END as salary_band
FROM employees;

CASE in WHERE

SELECT * FROM orders
WHERE status = CASE
  WHEN @filter = 'active' THEN 'pending'
  ELSE status
END;

CASE in ORDER BY

SELECT * FROM products
ORDER BY
  CASE WHEN featured = 1 THEN 0 ELSE 1 END,
  name;

NULL Handling

4 snippets

Work with NULL values

COALESCE

SELECT COALESCE(nickname, name, 'Unknown') as display_name
FROM users;

NULLIF

-- Returns NULL if equal, prevents division by zero
SELECT total / NULLIF(count, 0) as average
FROM stats;

IS NULL

SELECT * FROM users WHERE email IS NULL;
SELECT * FROM users WHERE email IS NOT NULL;

IFNULL / NVL

-- MySQL
SELECT IFNULL(email, 'N/A') FROM users;

-- Oracle
SELECT NVL(email, 'N/A') FROM users;

Transactions

4 snippets

Ensure data integrity

Basic Transaction

BEGIN TRANSACTION;

UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

COMMIT;

Rollback

BEGIN TRANSACTION;

UPDATE inventory SET qty = qty - 1 WHERE id = 1;

-- Something went wrong
ROLLBACK;

Savepoints

BEGIN TRANSACTION;

INSERT INTO orders (...) VALUES (...);
SAVEPOINT after_order;

INSERT INTO order_items (...) VALUES (...);
-- Oops, rollback just the items
ROLLBACK TO SAVEPOINT after_order;

COMMIT;

Isolation Levels

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

String Functions

6 snippets

Manipulate text data

CONCAT

SELECT CONCAT(first_name, ' ', last_name) as full_name
FROM users;

SUBSTRING

SELECT SUBSTRING(name, 1, 3) FROM users;  -- First 3 chars
SELECT LEFT(name, 3) FROM users;           -- Same result
SELECT RIGHT(name, 3) FROM users;          -- Last 3 chars

TRIM

SELECT TRIM(name) FROM users;
SELECT LTRIM(name) FROM users;  -- Left trim
SELECT RTRIM(name) FROM users;  -- Right trim

UPPER / LOWER

SELECT UPPER(name), LOWER(email) FROM users;

REPLACE

SELECT REPLACE(phone, '-', '') FROM users;

LENGTH

SELECT name, LENGTH(name) as name_length FROM users;

More Cheat Sheets

FAQ

Frequently asked questions

What is a SQL cheat sheet?

A SQL cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in SQL. It helps developers quickly look up syntax without searching through documentation.

How do I learn SQL quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important SQL concepts?

Key SQL concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my SQL code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your SQL code using AI.

Code Conversion Tools

Convert SQL to Other Languages

Easily translate your SQL code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate SQL Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week