SQL is the universal language of data. It powers the backends of every major application, from tiny mobile apps to trillion-dollar financial systems. Over 80% of professional developers interact with a relational database at least once per week, and SQL is the bridge between application code and persistent storage. Yet despite being nearly fifty years old, SQL remains intimidating to newcomers and easy to forget for experienced developers. The typical developer knows SELECT and INSERT, but freezes when asked to write a complex JOIN, construct a subquery with EXISTS, or choose between WHERE and HAVING.
Our free interactive SQL commands cheat sheet solves this by organizing seventy commands into ten real-world categories. Each command includes a concise explanation, copyable syntax examples, and visual tags for quick scanning. The Data Vault aesthetic — deep dark background, floating data-particle animations, and category-colored border glows — makes the interface as memorable as the queries themselves. Everything is client-side. No data leaves your browser.
Why SQL Deserves a Dedicated Cheat Sheet
SQL is not just a query language. It is a complete data manipulation and definition ecosystem that touches schema design, data integrity, access control, reporting, and analytics. A developer who only knows SELECT * FROM is like a writer who only knows the alphabet. The real value appears when you need to model relationships, optimize queries with indexes, aggregate millions of rows, or secure sensitive data with granular permissions.
The SQL standard has accumulated features over five decades, and every major database adds its own dialect extensions. PostgreSQL, MySQL, SQL Server, SQLite, and Oracle all implement the core standard, but diverge in function names, data types, and advanced features. Knowing which syntax works in your specific environment — and which is portable across databases — separates fluent data engineers from beginners.
A well-organized cheat sheet provides two benefits. First, it reduces the cognitive load of memorizing syntax and function signatures. Second, it surfaces commands you might not know exist. Many developers have never used WINDOW functions, COMMON TABLE EXPRESSIONS, or SAVEPOINT transactions, even though all three solve common real-world problems elegantly.
DDL — Data Definition Language
DDL commands define and manage database structures. They create tables, modify columns, build indexes, and remove objects. These are the commands you use when designing a schema or evolving it over time.
CREATE TABLE
The CREATE TABLE command defines a new table with columns, data types, constraints, and default values. This is the foundation of schema design.
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
); ALTER TABLE
The ALTER TABLE command modifies an existing table structure. You can add columns, drop columns, change data types, and add or remove constraints.
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
ALTER TABLE users DROP COLUMN phone;
ALTER TABLE users MODIFY COLUMN name VARCHAR(150);
ALTER TABLE users ADD CONSTRAINT fk_role FOREIGN KEY (role_id) REFERENCES roles(id); DROP TABLE
The DROP TABLE command permanently deletes a table and all its data. This is destructive and irreversible. Use with caution.
DROP TABLE users;
DROP TABLE IF EXISTS users; TRUNCATE TABLE
The TRUNCATE TABLE command removes all rows from a table but keeps the table structure intact. It is faster than DELETE for large tables because it does not log individual row deletions. However, it cannot be rolled back in most databases.
TRUNCATE TABLE users; CREATE INDEX
The CREATE INDEX command builds an index on one or more columns, dramatically speeding up WHERE clause filtering and JOIN operations. Indexes trade write performance for read performance.
CREATE INDEX idx_users_email ON users(email);
CREATE UNIQUE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_name_email ON users(name, email); DROP INDEX
The DROP INDEX command removes an existing index. This is useful when an index is no longer needed or is hurting write performance.
DROP INDEX idx_users_email;
DROP INDEX idx_users_email ON users; CREATE VIEW
The CREATE VIEW command creates a virtual table based on the result of a query. Views simplify complex queries, enforce security by hiding columns, and provide a stable interface even when underlying tables change.
CREATE VIEW active_users AS
SELECT id, email, name
FROM users
WHERE active = 1; DROP VIEW
The DROP VIEW command removes a view. This does not affect the underlying tables.
DROP VIEW active_users;
DROP VIEW IF EXISTS active_users; DML — Data Manipulation Language
DML commands query and modify data. These are the commands you use most often in application code — fetching records, inserting new data, updating existing rows, and deleting obsolete entries.
SELECT
The SELECT command retrieves data from one or more tables. It is the most frequently used SQL command and supports extensive filtering, sorting, and aggregation options.
SELECT * FROM users;
SELECT id, email, name FROM users;
SELECT * FROM users WHERE active = 1;
SELECT * FROM users WHERE age >= 18 AND country = 'US';
SELECT * FROM users ORDER BY created_at DESC;
SELECT * FROM users LIMIT 10 OFFSET 20;
SELECT DISTINCT country FROM users; INSERT INTO
The INSERT INTO command adds new rows to a table. You can insert a single row, multiple rows, or the result of a query.
INSERT INTO users (email, name) VALUES ('alice@example.com', 'Alice');
INSERT INTO users (email, name) VALUES
('bob@example.com', 'Bob'),
('carol@example.com', 'Carol');
INSERT INTO users_archive SELECT * FROM users WHERE active = 0; UPDATE
The UPDATE command modifies existing rows. Always include a WHERE clause — without one, every row in the table will be updated.
UPDATE users SET name = 'Alice Smith' WHERE id = 1;
UPDATE users SET active = 1, updated_at = NOW() WHERE email LIKE '%@example.com'; DELETE
The DELETE command removes rows from a table. Like UPDATE, it requires a WHERE clause to avoid catastrophic data loss.
DELETE FROM users WHERE id = 1;
DELETE FROM users WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 YEAR); JOINs — Combining Tables
JOINs are the most powerful and most misunderstood feature of SQL. They combine rows from two or more tables based on a related column. Understanding JOINs is essential for any non-trivial database design and is the number one topic in SQL interviews.
Think of two tables as circles in a Venn diagram. The JOIN type determines which overlapping and non-overlapping regions are returned.
INNER JOIN
INNER JOIN returns only rows that have matching values in both tables. This is the default JOIN behavior and the most commonly used type.
SELECT users.name, orders.total
FROM users
INNER JOIN orders ON users.id = orders.user_id; LEFT JOIN
LEFT JOIN returns all rows from the left table and matched rows from the right table. If there is no match, the right table columns contain NULL. Use this when you want every row from the primary table regardless of whether a relationship exists.
SELECT users.name, orders.total
FROM users
LEFT JOIN orders ON users.id = orders.user_id; RIGHT JOIN
RIGHT JOIN returns all rows from the right table and matched rows from the left table. It is the mirror image of LEFT JOIN. In practice, most developers prefer to restructure the query as a LEFT JOIN for consistency.
SELECT users.name, orders.total
FROM users
RIGHT JOIN orders ON users.id = orders.user_id; FULL JOIN
FULL JOIN returns all rows when there is a match in either table. Rows without a match in one table will have NULL for that table's columns. Not all databases support FULL JOIN directly — MySQL requires a UNION of LEFT and RIGHT JOINs.
SELECT users.name, orders.total
FROM users
FULL JOIN orders ON users.id = orders.user_id; CROSS JOIN
CROSS JOIN returns the Cartesian product of both tables — every row from the first table paired with every row from the second. Use with caution on large tables, as the result set grows exponentially.
SELECT users.name, products.name
FROM users
CROSS JOIN products; SELF JOIN
A SELF JOIN joins a table to itself. This is useful for hierarchical data, such as employee-manager relationships or category trees.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id; Aggregation and Grouping
Aggregation functions compute summary values across groups of rows. They are essential for reporting, analytics, and dashboard queries.
COUNT, SUM, AVG, MAX, MIN
These five functions form the core of SQL analytics. COUNT returns the number of rows, SUM adds numeric values, AVG computes the mean, and MAX and MIN return extreme values.
SELECT COUNT(*) FROM users;
SELECT SUM(total) FROM orders;
SELECT AVG(age) FROM users;
SELECT MAX(salary), MIN(salary) FROM employees; GROUP BY
The GROUP BY clause groups rows that have the same values in specified columns, allowing aggregate functions to run per group rather than across the entire table.
SELECT country, COUNT(*) AS user_count
FROM users
GROUP BY country;
SELECT category, AVG(price) AS avg_price, MAX(price) AS max_price
FROM products
GROUP BY category; HAVING
The HAVING clause filters groups after aggregation. This is the key difference from WHERE, which filters rows before aggregation. Use HAVING when your filter condition involves an aggregate result.
SELECT country, COUNT(*) AS user_count
FROM users
GROUP BY country
HAVING COUNT(*) > 100;
SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
HAVING AVG(price) > 50; String Functions
String functions manipulate text data. They are indispensable for data cleaning, formatting, search, and reporting.
CONCAT
The CONCAT function joins two or more strings together. Some databases use the || operator instead.
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
SELECT first_name || ' ' || last_name AS full_name FROM users; LENGTH
The LENGTH function returns the number of characters in a string. Useful for validation and filtering.
SELECT LENGTH(email) FROM users;
SELECT * FROM users WHERE LENGTH(password) < 8; SUBSTRING
The SUBSTRING function extracts a portion of a string. Parameters vary by database — some use SUBSTR or SUBSTRING with 1-based or 0-based indexing.
SELECT SUBSTRING(phone, 1, 3) AS area_code FROM users;
SELECT SUBSTR(email, 1, INSTR(email, '@') - 1) AS username FROM users; UPPER and LOWER
These functions convert strings to uppercase or lowercase. Essential for case-insensitive comparisons and consistent formatting.
SELECT UPPER(name) FROM users;
SELECT * FROM users WHERE LOWER(email) = 'alice@example.com'; TRIM
The TRIM function removes leading and trailing whitespace. Data imported from external sources often contains invisible padding that breaks comparisons.
SELECT TRIM(name) FROM users;
SELECT * FROM users WHERE TRIM(email) = ''; REPLACE
The REPLACE function substitutes all occurrences of a substring with another string. Useful for bulk data cleaning.
SELECT REPLACE(phone, '-', '') FROM users;
UPDATE users SET bio = REPLACE(bio, 'old_term', 'new_term'); LEFT and RIGHT
These functions extract a specified number of characters from the left or right side of a string.
SELECT LEFT(card_number, 4) FROM payments;
SELECT RIGHT(filename, 3) AS extension FROM files; Numeric Functions
Numeric functions perform mathematical operations on data. They are essential for financial calculations, statistical analysis, and data normalization.
ROUND
The ROUND function rounds a number to a specified number of decimal places.
SELECT ROUND(price, 2) FROM products;
SELECT ROUND(AVG(rating), 1) FROM reviews; CEIL and FLOOR
CEIL rounds up to the nearest integer. FLOOR rounds down. These are useful for pagination, tiered pricing, and bucketed reporting.
SELECT CEIL(4.2); -- Returns 5
SELECT FLOOR(4.8); -- Returns 4 ABS
The ABS function returns the absolute value of a number.
SELECT ABS(temperature_delta) FROM sensors; POWER
The POWER function raises a number to a specified exponent.
SELECT POWER(2, 10); -- Returns 1024
SELECT POWER(principal, years) FROM investments; MOD
The MOD function returns the remainder of a division. The % operator is equivalent in most databases.
SELECT MOD(id, 2) FROM users; -- 0 for even, 1 for odd
SELECT * FROM users WHERE id % 10 = 0; RAND / RANDOM
These functions generate random numbers. MySQL uses RAND(), PostgreSQL uses RANDOM().
SELECT RAND(); -- MySQL
SELECT RANDOM(); -- PostgreSQL
SELECT * FROM users ORDER BY RAND() LIMIT 5; Date and Time Functions
Date and time functions handle temporal data. They are critical for scheduling, reporting, time-series analysis, and data retention policies.
NOW and CURDATE
NOW returns the current date and time. CURDATE returns only the date portion. Equivalent functions exist in every dialect with slightly different names.
SELECT NOW();
SELECT CURDATE();
SELECT CURRENT_TIMESTAMP; -- Standard SQL DATEDIFF
The DATEDIFF function calculates the difference between two dates in days. PostgreSQL uses AGE or simple subtraction.
SELECT DATEDIFF(NOW(), created_at) AS days_since_signup FROM users;
SELECT NOW() - created_at FROM users; -- PostgreSQL interval DATE_ADD and DATE_SUB
These functions add or subtract a time interval from a date. PostgreSQL uses interval arithmetic with + and - operators.
SELECT DATE_ADD(NOW(), INTERVAL 7 DAY);
SELECT DATE_SUB(NOW(), INTERVAL 1 MONTH);
SELECT NOW() + INTERVAL '1 week'; -- PostgreSQL DATE_FORMAT
The DATE_FORMAT function formats a date according to a pattern string. PostgreSQL uses TO_CHAR, SQL Server uses FORMAT.
SELECT DATE_FORMAT(created_at, '%Y-%m-%d') FROM users; -- MySQL
SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM users; -- PostgreSQL EXTRACT
The EXTRACT function retrieves a specific part of a date — year, month, day, hour, minute, or second. This is standard SQL and works across most databases.
SELECT EXTRACT(YEAR FROM created_at) AS signup_year FROM users;
SELECT EXTRACT(MONTH FROM created_at) AS signup_month FROM users;
SELECT * FROM orders WHERE EXTRACT(DOW FROM created_at) = 1; -- Monday DCL and TCL — Security and Transactions
Data Control Language manages permissions. Transaction Control Language ensures data integrity during multi-step operations. Both are essential for production databases.
GRANT
The GRANT command gives specific permissions to a user or role. Permissions can be global, database-level, table-level, or column-level.
GRANT SELECT, INSERT ON users TO 'app_user'@'localhost';
GRANT ALL PRIVILEGES ON mydb.* TO 'admin'@'%';
GRANT SELECT (email, name) ON users TO 'readonly'@'%'; REVOKE
The REVOKE command removes previously granted permissions.
REVOKE INSERT ON users FROM 'app_user'@'localhost';
REVOKE ALL PRIVILEGES ON mydb.* FROM 'admin'@'%'; COMMIT
The COMMIT command permanently saves all changes made during the current transaction. Until committed, changes are invisible to other sessions and can be rolled back.
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; ROLLBACK
The ROLLBACK command undoes all changes made during the current transaction. This is your safety net when something goes wrong.
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- Oops, wrong account
ROLLBACK; SAVEPOINT
The SAVEPOINT command creates a named point within a transaction that you can roll back to without undoing the entire transaction. This enables partial rollback in complex operations.
BEGIN TRANSACTION;
UPDATE inventory SET quantity = quantity - 10 WHERE id = 1;
SAVEPOINT after_inventory;
UPDATE orders SET status = 'shipped' WHERE id = 100;
-- If shipping fails, only rollback the order update
ROLLBACK TO SAVEPOINT after_inventory;
COMMIT; How to Use the Interactive SQL Commands Cheat Sheet
Our free interactive SQL commands cheat sheet takes all seventy commands and presents them in a searchable, filterable grid. The interface is designed for speed: type a keyword to search across command names, descriptions, and tags; click a category tab to narrow the scope; hover over any code block to reveal a copy button. Destructive commands like DROP TABLE and TRUNCATE are marked with red warning badges so you never run them by accident.
The Data Vault aesthetic draws from secure data centers and server rooms — deep dark background tones, floating data-particle animations, and category-colored strip lights that evoke a high-security control room. Each card feels like a classified data sheet: clear, scannable, and precise. The typography pairs Space Grotesk display headings with Inter body text and JetBrains Mono for code.
Because the entire tool runs in your browser, there is no server, no database, and no tracking. You can use it offline after the first load, and your clipboard never leaves your machine.
Related Developer Tools
If you work with databases and SQL, these related tools will streamline your workflow:
- Git Commands Cheat Sheet — 100+ Git commands covering branching, merging, rebasing, and remote operations.
- Terminal Commands Cheat Sheet — 80+ Bash, Linux, and macOS commands for file operations, process management, and networking.
- Docker Commands Cheat Sheet — 90+ Docker commands for containers, images, volumes, and Compose.
- CSS Selectors Cheat Sheet — 70+ selectors with specificity scores and browser support notes.
- JavaScript Array Methods Cheat Sheet — 40+ array methods with mutating vs non-mutating badges and ES version tags.
- JSON Formatter — Format, validate, and minify JSON with a cartographer-themed interface.
- Regex Tester — Test regular expressions with real-time match highlighting and explanation.
- VS Code Shortcuts Cheat Sheet — 84 essential keyboard shortcuts with platform toggle and one-click copy.
- NPM Commands Cheat Sheet — 65+ NPM commands covering install, scripts, publish, audit, and workspaces.
- Python Built-in Functions Cheat Sheet — 70+ Python built-ins organized by category with syntax highlighting.
- React Hooks Cheat Sheet — 20+ built-in hooks and 10 custom patterns with React 19 coverage.
- HTML Table Generator — Generate responsive HTML tables with custom styling and copy-to-clipboard.
Conclusion
SQL is far more than SELECT * FROM. It is a complete language for defining schemas, manipulating data, controlling access, and ensuring integrity through transactions. The commands covered in this guide — DDL for structure, DML for data, JOINs for relationships, aggregation for analytics, functions for transformation, and DCL/TCL for security and safety — represent the full surface area that a professional developer uses in daily database work.
Bookmark our interactive SQL commands cheat sheet and reach for it whenever you need a quick reminder. It is free, requires no signup, and works entirely in your browser. Whether you are writing your first JOIN, optimizing a slow query with indexes, or designing a multi-table schema with foreign keys and constraints, the right command is always a search away.