Whether you are writing your first SELECT statement or preparing for a database interview, this SQL cheat sheet is built to be the only page you need to bookmark. It covers every core SQL topic in one place: basic syntax, DDL and DML commands, joins, subqueries, aggregate functions, window functions, indexing, transactions, and performance tips, with clean, copy-paste ready examples for each.
SQL Cheat Sheet (Complete Quick Reference)
SQL is one of the most in-demand and durable skills in tech. It powers everything from a simple mobile app backend to enterprise data warehouses, and it remains one of the most frequently tested skills in interviews for data analysts, backend developers, and data scientists alike. If you’re building your SQL foundation from scratch, this cheat sheet pairs well with a structured MySQL course that walks through these same concepts with hands-on practice.
Use the table of contents below to jump straight to what you need, or read top to bottom for a complete SQL refresher.
1. SQL Basics
What SQL is: SQL (Structured Query Language) is a standard language used to create, read, update, and manage data stored in relational databases. Almost every relational database system, including MySQL, PostgreSQL, Oracle, and SQL Server, uses SQL or a close variant of it.
How SQL works: You write a query (a statement describing what data you want or what change you want to make), and the database engine parses it, plans the most efficient way to execute it, and returns the result. SQL is declarative, which means you describe what you want, not how to get it. The database decides the execution steps internally.
SQL syntax basics:
- SQL statements end with a semicolon (
;). - Keywords like
SELECT,FROM, andWHEREare not case sensitive, but writing them in uppercase is a common convention that improves readability. - Table and column names are usually case sensitive depending on the database and operating system.
- String values are wrapped in single quotes:
'example'.
Types of SQL statements:
| Category | Full Form | Purpose | Example Commands |
|---|---|---|---|
| DDL | Data Definition Language | Defines and modifies database structure | CREATE, ALTER, DROP, TRUNCATE |
| DML | Data Manipulation Language | Manages the data inside tables | INSERT, UPDATE, DELETE, SELECT |
| DCL | Data Control Language | Manages permissions and access | GRANT, REVOKE |
| TCL | Transaction Control Language | Manages transactions | COMMIT, ROLLBACK, SAVEPOINT |
Popular relational databases: MySQL, PostgreSQL, Microsoft SQL Server, Oracle Database, SQLite, and MariaDB are among the most widely used relational database systems, and they all share the same core SQL syntax covered in this guide, with small variations in advanced features.
2. Database Commands (DDL)
-- Create a new database
CREATE DATABASE company_db;
-- Switch to using a specific database
USE company_db;
-- Rename a database (syntax varies by database system)
ALTER DATABASE company_db MODIFY NAME = company_data;
-- Delete a database permanently
DROP DATABASE company_db;
CREATE DATABASE sets up a new, empty database. USE tells the database engine which database your following queries should run against. ALTER DATABASE changes database-level settings such as its name or character set, and the exact syntax differs between MySQL, PostgreSQL, and SQL Server. DROP DATABASE deletes the entire database along with all its tables and data, so it should always be used with caution.
3. Table Commands
-- Create a new table
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(100),
department VARCHAR(50),
salary DECIMAL(10,2)
);
-- Add a new column to an existing table
ALTER TABLE employees ADD email VARCHAR(100);
-- Modify an existing column
ALTER TABLE employees MODIFY salary DECIMAL(12,2);
-- Delete a column
ALTER TABLE employees DROP COLUMN email;
-- Remove all rows but keep the table structure
TRUNCATE TABLE employees;
-- Delete a table completely
DROP TABLE employees;
-- Rename a table
RENAME TABLE employees TO staff;
CREATE TABLE defines a new table along with its columns and data types. ALTER TABLE is used any time you need to add, modify, or remove a column without recreating the table. TRUNCATE TABLE quickly empties a table but keeps its structure intact for future use, while DROP TABLE removes the table and its structure entirely. RENAME TABLE is useful when your schema evolves and a table name no longer reflects its purpose.
4. CRUD Operations
CRUD stands for Create, Read, Update, and Delete, the four fundamental operations you perform on data.
-- INSERT: add new records
INSERT INTO employees (emp_id, emp_name, department, salary)
VALUES (1, 'Ananya Rao', 'Engineering', 65000);
-- SELECT: read records
SELECT emp_name, department FROM employees;
-- UPDATE: modify existing records
UPDATE employees
SET salary = 70000
WHERE emp_id = 1;
-- DELETE: remove records
DELETE FROM employees
WHERE emp_id = 1;
Use INSERT when you’re adding a brand new row to a table, such as registering a new employee or customer. Use SELECT any time you need to retrieve data for reporting, display, or analysis, and it is by far the most frequently used SQL command. Use UPDATE when existing data needs to change, such as a salary revision or a status update, always paired with a WHERE clause so you only affect the intended rows. Use DELETE to remove records that are no longer needed, again always with a WHERE clause, since running DELETE without one removes every row in the table.
5. WHERE Clause
The WHERE clause filters rows based on a condition, and it can be combined with several operators for more precise filtering.
-- Comparison operators
SELECT * FROM employees WHERE salary > 50000;
SELECT * FROM employees WHERE department = 'Engineering';
-- BETWEEN: match a range
SELECT * FROM employees WHERE salary BETWEEN 40000 AND 80000;
-- IN: match any value in a list
SELECT * FROM employees WHERE department IN ('Engineering', 'Sales');
-- LIKE: pattern matching
SELECT * FROM employees WHERE emp_name LIKE 'A%';
-- IS NULL: check for missing values
SELECT * FROM employees WHERE department IS NULL;
-- AND, OR, NOT: combine conditions
SELECT * FROM employees WHERE department = 'Engineering' AND salary > 60000;
SELECT * FROM employees WHERE department = 'Engineering' OR department = 'Sales';
SELECT * FROM employees WHERE NOT department = 'Sales';
Comparison operators (=, >, <, >=, <=, !=) are the building blocks of filtering. BETWEEN is a cleaner way to write a range condition instead of two separate comparisons. IN avoids writing multiple OR conditions when checking against a list of values. LIKE is used for pattern-based text searches, where % matches any number of characters and _ matches exactly one character. IS NULL (and its counterpart IS NOT NULL) is the correct way to check for missing values, since = NULL does not work in SQL. AND, OR, and NOT let you combine multiple conditions into a single, more precise filter.
6. ORDER BY
-- Ascending order (default)
SELECT * FROM employees ORDER BY salary ASC;
-- Descending order
SELECT * FROM employees ORDER BY salary DESC;
-- Sorting by multiple columns
SELECT * FROM employees ORDER BY department ASC, salary DESC;
ORDER BY sorts your result set after the data has been filtered. ASC (ascending) is the default order and can be omitted, while DESC reverses it. When sorting by multiple columns, SQL sorts by the first column first, and only uses the second column to break ties within groups that share the same value in the first column. This is useful, for example, when you want employees grouped by department, and within each department, sorted from highest to lowest salary.
7. Aggregate Functions
SELECT COUNT(*) FROM employees; -- total number of rows
SELECT SUM(salary) FROM employees; -- total of all salaries
SELECT AVG(salary) FROM employees; -- average salary
SELECT MIN(salary) FROM employees; -- lowest salary
SELECT MAX(salary) FROM employees; -- highest salary
COUNT() tells you how many rows match a condition, commonly used to count total employees, orders, or transactions. SUM() adds up numeric values, such as total revenue or total salary expenditure. AVG() calculates the mean, useful for metrics like average order value or average salary by department. MIN() and MAX() return the smallest and largest values in a column, often used to find the earliest date, the lowest price, or the top performer in a dataset. Aggregate functions become especially powerful once combined with GROUP BY, covered next.
8. GROUP BY & HAVING
-- Grouping records
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
-- Filtering grouped results with HAVING
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 55000;
GROUP BY collapses multiple rows that share the same value in a column into a single summary row, typically used alongside aggregate functions to answer questions like “how many employees are in each department” or “what is the average salary per department.”
Difference between WHERE and HAVING: WHERE filters individual rows before any grouping happens, and it cannot use aggregate functions. HAVING filters groups after GROUP BY has already summarized the data, and it is specifically designed to work with aggregate functions like AVG(), SUM(), or COUNT(). A simple rule to remember: filter rows with WHERE, filter groups with HAVING.
9. SQL Joins

Joins combine rows from two or more tables based on a related column, usually a foreign key relationship.
-- INNER JOIN: only matching rows from both tables
SELECT e.emp_name, d.department_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.dept_id;
-- LEFT JOIN: all rows from the left table, matched rows from the right
SELECT e.emp_name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id;
-- RIGHT JOIN: all rows from the right table, matched rows from the left
SELECT e.emp_name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;
-- FULL OUTER JOIN: all rows from both tables, matched where possible
SELECT e.emp_name, d.department_name
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.dept_id;
-- CROSS JOIN: every row from one table combined with every row from another
SELECT e.emp_name, d.department_name
FROM employees e
CROSS JOIN departments d;
-- SELF JOIN: a table joined with itself
SELECT a.emp_name AS employee, b.emp_name AS manager
FROM employees a
JOIN employees b ON a.manager_id = b.emp_id;
Joins Comparison Table
| Join Type | Returns | Common Use Case |
|---|---|---|
| INNER JOIN | Only rows with matches in both tables | Fetching employees who belong to a valid department |
| LEFT JOIN | All rows from the left table, with NULLs where no match exists on the right | Listing all employees, including those not yet assigned a department |
| RIGHT JOIN | All rows from the right table, with NULLs where no match exists on the left | Listing all departments, including empty ones with no employees |
| FULL OUTER JOIN | All rows from both tables, matched where possible | Auditing data to find mismatches on both sides |
| CROSS JOIN | Every combination of rows from both tables | Generating all possible pairings, such as product and size combinations |
| SELF JOIN | Rows from the same table compared to each other | Finding an employee’s manager within the same employees table |
A simple way to visualize joins is with overlapping circles, similar to a Venn diagram. INNER JOIN is the overlapping middle section only. LEFT JOIN is the entire left circle plus the overlap. RIGHT JOIN is the entire right circle plus the overlap. FULL OUTER JOIN is both circles combined entirely. Joins are one of the most heavily tested SQL topics in interviews, so it is worth practicing each type until you can write them without referring back to a cheat sheet.
10. Subqueries
A subquery is a query nested inside another query, often used when a value needed for filtering has to be calculated first.
-- Basic nested query
SELECT emp_name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
-- EXISTS: check if a subquery returns any rows
SELECT emp_name
FROM employees e
WHERE EXISTS (
SELECT 1 FROM departments d WHERE d.dept_id = e.dept_id
);
-- NOT EXISTS: check if a subquery returns no rows
SELECT emp_name
FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM departments d WHERE d.dept_id = e.dept_id
);
-- IN: match against a list returned by a subquery
SELECT emp_name
FROM employees
WHERE dept_id IN (SELECT dept_id FROM departments WHERE location = 'Hyderabad');
-- ANY: compare against any value returned by a subquery
SELECT emp_name
FROM employees
WHERE salary > ANY (SELECT salary FROM employees WHERE department = 'Sales');
-- ALL: compare against every value returned by a subquery
SELECT emp_name
FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE department = 'Sales');
-- Correlated subquery: references the outer query
SELECT emp_name, salary
FROM employees e
WHERE salary > (
SELECT AVG(salary) FROM employees WHERE department = e.department
);
Nested queries run once and their result is used by the outer query. EXISTS and NOT EXISTS are efficient for checking whether related records exist, without needing to return the actual matching data. IN is convenient when comparing against a list of values from another table. ANY returns true if the condition matches at least one value from the subquery, while ALL requires the condition to hold true for every value returned. A correlated subquery is different from a regular subquery because it references a column from the outer query, which means it runs once for every row processed by the outer query, so it can be slower on large datasets.
11. Set Operations
-- UNION: combine results, removing duplicates
SELECT emp_name FROM employees
UNION
SELECT client_name FROM clients;
-- UNION ALL: combine results, keeping duplicates
SELECT emp_name FROM employees
UNION ALL
SELECT client_name FROM clients;
-- INTERSECT: return only rows common to both queries
SELECT emp_name FROM employees
INTERSECT
SELECT client_name FROM clients;
-- EXCEPT: return rows from the first query not present in the second
SELECT emp_name FROM employees
EXCEPT
SELECT client_name FROM clients;
UNION merges the results of two queries and automatically removes duplicate rows, which requires extra processing. UNION ALL does the same but keeps duplicates, making it faster when you know duplicates either do not exist or do not matter. INTERSECT returns only the rows that appear in both result sets, useful for finding overlapping records. EXCEPT (called MINUS in Oracle) returns rows from the first query that do not appear in the second, useful for finding records present in one dataset but missing from another. All set operations require both queries to return the same number of columns with compatible data types.
12. Constraints
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
order_amount DECIMAL(10,2) CHECK (order_amount > 0),
order_status VARCHAR(20) DEFAULT 'Pending',
tracking_code VARCHAR(50) UNIQUE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
PRIMARY KEY uniquely identifies every row in a table and does not allow NULL values. FOREIGN KEY creates a link between two tables, ensuring that a value in one table must correspond to a valid value in another, which enforces referential integrity. UNIQUE ensures that no two rows share the same value in that column, though unlike a primary key, it can allow one NULL value. CHECK enforces a custom rule, such as requiring an amount to always be positive. DEFAULT automatically assigns a value to a column when none is provided during an insert. NOT NULL prevents a column from being left empty, which is essential for fields that must always contain data, such as a customer ID or an email address.
13. SQL Keys
| Key Type | Definition |
|---|---|
| Primary Key | A column, or set of columns, that uniquely identifies every row in a table. Cannot contain NULL values, and a table can have only one primary key. |
| Foreign Key | A column that references the primary key of another table, used to link related tables together. |
| Candidate Key | Any column, or combination of columns, that could qualify as a primary key because it uniquely identifies each row. A table can have multiple candidate keys. |
| Composite Key | A primary key made up of two or more columns combined, used when a single column alone cannot guarantee uniqueness. |
| Alternate Key | Any candidate key that was not chosen as the primary key. |
| Super Key | A set of one or more columns that can uniquely identify a row, which may include extra columns beyond what is strictly necessary. Every candidate key is a super key, but not every super key is a candidate key. |
Understanding the relationships between these key types is a common interview topic, particularly the distinction between a candidate key, a super key, and a primary key, since the definitions are closely related but not identical.
14. Views
-- Create a view
CREATE VIEW high_earners AS
SELECT emp_name, department, salary
FROM employees
WHERE salary > 70000;
-- Query a view like a regular table
SELECT * FROM high_earners;
-- Update a view's definition
CREATE OR REPLACE VIEW high_earners AS
SELECT emp_name, department, salary
FROM employees
WHERE salary > 75000;
-- Drop a view
DROP VIEW high_earners;
A view is a virtual table based on the result of a stored query. It does not store data itself; it stores the query definition and pulls fresh data from the underlying tables every time it is queried.
Advantages: Views simplify complex queries by letting you reuse them under a simple name, restrict sensitive columns from certain users for security, and present a consistent, simplified structure to reporting tools without changing the underlying tables.
Updating views: A view can be updated using CREATE OR REPLACE VIEW, and in some cases you can even run INSERT, UPDATE, or DELETE directly on a view if it is based on a single table without aggregate functions.
Materialized views (where supported): Unlike a regular view, a materialized view actually stores the query result physically on disk and needs to be refreshed periodically. Databases like PostgreSQL and Oracle support materialized views, and they are useful for speeding up expensive queries that do not need real-time data, such as a daily sales summary report.
15. Indexes
-- Create a basic index
CREATE INDEX idx_department ON employees(department);
-- Create a unique index
CREATE UNIQUE INDEX idx_email ON employees(email);
-- Create a composite index on multiple columns
CREATE INDEX idx_dept_salary ON employees(department, salary);
-- Drop an index
DROP INDEX idx_department ON employees;
An index is a data structure that speeds up data retrieval by allowing the database to find rows without scanning the entire table.
- Clustered Index: Determines the physical storage order of data in a table. A table can have only one clustered index, and in many databases, the primary key automatically creates one.
- Non-Clustered Index: A separate structure from the actual table data, containing pointers back to the original rows. A table can have several non-clustered indexes.
- Composite Index: An index built on two or more columns, useful when queries frequently filter or sort by the same combination of columns together.
- Unique Index: Enforces uniqueness on the indexed column, similar to a
UNIQUEconstraint, while also improving lookup speed.
When indexes help and when they hurt: Indexes dramatically speed up SELECT queries that filter, join, or sort on the indexed columns, especially on large tables. However, every index adds overhead to INSERT, UPDATE, and DELETE operations, because the index itself must also be updated whenever the underlying data changes. This is why indexing every column is not a good practice. A good rule of thumb is to index columns that are frequently used in WHERE clauses, joins, and sorting, while avoiding indexes on columns that change very often or are rarely queried.
16. Transactions
BEGIN;
UPDATE accounts SET balance = balance - 5000 WHERE account_id = 101;
UPDATE accounts SET balance = balance + 5000 WHERE account_id = 202;
SAVEPOINT before_final_check;
-- If something goes wrong, roll back to the savepoint or the entire transaction
ROLLBACK TO before_final_check;
-- or
ROLLBACK;
-- If everything looks correct, make the changes permanent
COMMIT;
BEGIN (or START TRANSACTION) marks the start of a transaction, a group of SQL statements treated as a single unit of work. COMMIT permanently saves all changes made during the transaction. ROLLBACK undoes all changes made since the transaction began, restoring the database to its previous state. SAVEPOINT creates a checkpoint within a transaction, allowing you to roll back only part of the transaction instead of the entire thing.
ACID properties describe the guarantees a reliable transaction must provide:
- Atomicity: All operations in a transaction succeed together, or none of them are applied at all.
- Consistency: A transaction moves the database from one valid state to another, without violating any rules or constraints.
- Isolation: Concurrent transactions do not interfere with each other, even when running at the same time.
- Durability: Once a transaction is committed, the changes remain permanent, even in the event of a system crash.
A classic example of why transactions matter is a bank transfer: deducting money from one account and adding it to another must happen together as a single atomic unit. If the deduction succeeds but the addition fails, the transaction should roll back entirely so no money disappears.
17. Stored Procedures
DELIMITER //
CREATE PROCEDURE GetEmployeesByDepartment(IN dept_name VARCHAR(50))
BEGIN
SELECT emp_name, salary
FROM employees
WHERE department = dept_name;
END //
DELIMITER ;
-- Call the stored procedure
CALL GetEmployeesByDepartment('Engineering');
Purpose: A stored procedure is a precompiled block of SQL code stored inside the database that can be executed repeatedly by calling its name, instead of rewriting the same query every time.
Benefits: Stored procedures improve performance since they are precompiled, reduce code duplication across applications, add a layer of security by controlling exactly what operations are exposed, and keep business logic centralized within the database rather than scattered across application code.
Parameters: Procedures can accept input parameters (IN), return output parameters (OUT), or use both (INOUT), making them flexible enough to handle dynamic filtering, calculations, or multi-step operations.
Use cases: Common use cases include generating standardized reports, performing batch updates, validating complex business rules before an insert, and automating repetitive administrative tasks like archiving old records.
18. Window Functions
Window functions perform calculations across a set of rows related to the current row, without collapsing the result into a single summarized row like GROUP BY does.
-- ROW_NUMBER: assigns a unique sequential number to each row
SELECT emp_name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num
FROM employees;
-- RANK: assigns a rank, with gaps after ties
SELECT emp_name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees;
-- DENSE_RANK: assigns a rank, without gaps after ties
SELECT emp_name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_salary_rank
FROM employees;
-- LEAD: looks ahead to the next row's value
SELECT emp_name, salary,
LEAD(salary) OVER (ORDER BY salary) AS next_salary
FROM employees;
-- LAG: looks back at the previous row's value
SELECT emp_name, salary,
LAG(salary) OVER (ORDER BY salary) AS previous_salary
FROM employees;
-- NTILE: divides rows into a specified number of buckets
SELECT emp_name, salary,
NTILE(4) OVER (ORDER BY salary DESC) AS salary_quartile
FROM employees;
Practical scenarios: ROW_NUMBER() is often used to remove duplicate rows by keeping only the first occurrence per group. RANK() and DENSE_RANK() are used for leaderboard-style reports, such as ranking employees by salary within each department, with RANK() skipping numbers after a tie and DENSE_RANK() not skipping any. LEAD() and LAG() are useful for comparing a row to the one before or after it, such as calculating month-over-month sales growth. NTILE() is commonly used to divide customers or employees into performance buckets, like quartiles or deciles, for segmentation and analysis.
19. Common SQL Functions
String Functions
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
SELECT SUBSTRING(emp_name, 1, 3) FROM employees;
SELECT LENGTH(emp_name) FROM employees;
SELECT UPPER(emp_name) FROM employees;
SELECT LOWER(emp_name) FROM employees;
SELECT TRIM(' Codegnan ') AS trimmed_text;
CONCAT() joins two or more strings together, commonly used to combine first and last names. SUBSTRING() extracts a portion of a string starting at a given position. LENGTH() returns the number of characters in a string. UPPER() and LOWER() convert text to uppercase or lowercase, useful for case-insensitive comparisons. TRIM() removes leading and trailing spaces from a string, which is especially useful when cleaning imported or user-entered data.
Date Functions
SELECT CURRENT_DATE;
SELECT CURRENT_TIMESTAMP;
SELECT DATE_ADD(order_date, INTERVAL 7 DAY) AS delivery_estimate FROM orders;
SELECT DATEDIFF(delivery_date, order_date) AS days_taken FROM orders;
CURRENT_DATE returns today’s date, and CURRENT_TIMESTAMP returns the current date and time together. DATE_ADD() adds a specified interval, such as days, months, or years, to a date, commonly used to calculate deadlines or delivery estimates. DATEDIFF() calculates the number of days between two dates, useful for measuring turnaround time or customer tenure.
Numeric Functions
SELECT ROUND(salary, 0) FROM employees;
SELECT CEIL(4.2) AS rounded_up;
SELECT FLOOR(4.8) AS rounded_down;
SELECT ABS(-150) AS absolute_value;
ROUND() rounds a number to a specified number of decimal places. CEIL() rounds a number up to the nearest whole number, while FLOOR() rounds it down. ABS() returns the absolute value of a number, removing any negative sign, which is useful when comparing the magnitude of a difference regardless of direction.
20. SQL Performance Tips
Writing correct SQL is only half the job. Writing efficient SQL is what separates a query that runs in milliseconds from one that times out on a large table. Keep these practices in mind:
- Use indexes appropriately. Index columns that are frequently used in
WHERE,JOIN, andORDER BYclauses, but avoid over-indexing tables that see heavy write activity. - Avoid
SELECT *where possible. Retrieving every column when you only need a few wastes memory, network bandwidth, and processing time. - Filter data early using
WHERE. Reducing the number of rows as early as possible in a query keeps every later step, including joins and sorting, faster. - Analyse execution plans. Most databases provide an
EXPLAINcommand that shows exactly how a query will be executed, helping you spot missing indexes or inefficient joins before they become production problems. - Optimise JOIN operations. Always join on indexed columns, and join tables in an order that minimizes the number of rows processed at each step where possible.
- Retrieve only required columns. This reduces the size of the result set and makes queries easier to read and maintain.
- Normalize data appropriately. A well-normalized schema reduces redundancy and keeps data consistent, though in some reporting-heavy systems, a degree of denormalization can also improve read performance.
- Avoid unnecessary subqueries. In many cases, a subquery can be rewritten as a join, which often performs better since the database can optimize joins more effectively than nested queries.
- Use prepared statements. Prepared statements improve performance for repeated queries and, just as importantly, protect against SQL injection attacks.
- Regularly maintain database statistics. Keeping table statistics up to date helps the database’s query planner make better decisions about how to execute a query efficiently.
Performance tuning is a skill that develops with real-world practice on large datasets, and it’s a core part of what’s covered in a well-structured Data Structures and Algorithms foundation, where thinking about efficiency and complexity becomes second nature.
21. SQL Interview Revision

Before an interview, revise these core topics in order, since they tend to build on each other and are asked in roughly this sequence during technical rounds:
- SQL Commands: Be confident with the difference between DDL, DML, DCL, and TCL commands, and be ready to write basic
CREATE,INSERT,SELECT,UPDATE, andDELETEstatements from memory. - Joins: Practice writing all six join types without hesitation, and be ready to explain the difference between
INNER JOINandLEFT JOINwith a real example. - Aggregate Functions: Know
COUNT(),SUM(),AVG(),MIN(), andMAX()cold, and be ready to combine them withGROUP BYandHAVING. - Constraints: Review
PRIMARY KEY,FOREIGN KEY,UNIQUE,CHECK,DEFAULT, andNOT NULL, since interviewers often ask you to design a small schema on the spot. - Normalization: Be ready to explain the first three normal forms (1NF, 2NF, 3NF) and why reducing data redundancy matters.
- Transactions: Understand
BEGIN,COMMIT,ROLLBACK, andSAVEPOINT, and how they relate to real-world scenarios like financial transfers. - ACID Properties: Be able to explain Atomicity, Consistency, Isolation, and Durability in your own words with an example for each.
- Window Functions: Practice
ROW_NUMBER(),RANK(),DENSE_RANK(),LEAD(), andLAG(), since these are increasingly common in data analyst and data science interviews. - Indexing: Know the difference between clustered and non-clustered indexes, and be ready to explain the tradeoff between faster reads and slower writes.
- Query Optimization: Be prepared to talk through how you would speed up a slow query, mentioning indexing, avoiding
SELECT *, and reading an execution plan.
If you want structured, guided interview practice beyond this revision list, Codegnan’s data science roadmap and interview preparation resources walk through SQL alongside the other skills recruiters test for analyst and data roles.
Download Section
Want this entire cheat sheet in one place for offline revision? Save this page, bookmark it for quick access before interviews and exams, or request the downloadable PDF version through Codegnan’s course resources so you always have this reference handy, even without an internet connection.
FAQs
What is an SQL cheat sheet?
An SQL cheat sheet is a condensed, quick reference guide that lists the most important SQL commands, syntax, and query patterns in one place. It is designed to help you quickly recall the correct syntax for tasks like filtering data, joining tables, or writing subqueries, without having to search through full documentation every time.
Which SQL commands are used most often?
The most frequently used SQL commands are SELECT, INSERT, UPDATE, and DELETE, since these cover the core CRUD operations used in nearly every application. Beyond these, WHERE, JOIN, GROUP BY, and ORDER BY are used constantly to filter, combine, summarize, and sort data.
What are the four basic SQL operations?
The four basic SQL operations, known as CRUD, are Create (INSERT), Read (SELECT), Update (UPDATE), and Delete (DELETE). Together, these four commands cover almost everything you need to manage data stored in a relational database.
Which SQL JOIN should I use?
Use INNER JOIN when you only want rows that have matching data in both tables. Use LEFT JOIN when you want all rows from the first table, even if there is no match in the second table. Use RIGHT JOIN for the reverse case, and FULL OUTER JOIN when you want all rows from both tables regardless of matches. Use CROSS JOIN only when you deliberately need every possible combination of rows, and SELF JOIN when a table needs to be compared against itself, such as finding employees and their managers within the same table.
Is SQL difficult to learn?
No, SQL is considered one of the easier programming languages to start learning, especially compared to general-purpose languages like Java or C. The basic syntax for filtering, sorting, and combining data can be picked up within a few weeks of consistent practice. What takes longer to master is writing efficient queries on large, real-world datasets, understanding database design, and learning advanced topics like window functions, indexing, and query optimization.
What should an SQL cheat sheet include?
A complete SQL cheat sheet should include basic syntax and statement types, DDL and DML commands, the WHERE clause with its operators, sorting with ORDER BY, aggregate functions, GROUP BY and HAVING, all join types, subqueries, set operations, constraints, keys, views, indexes, transactions, stored procedures, window functions, common string, date, and numeric functions, and performance optimization tips, exactly as covered in this guide.
Can I use this SQL cheat sheet for interviews?
Yes. This cheat sheet is structured to double as an interview revision guide, with the dedicated “SQL Interview Revision” section listing the core topics in the order they are typically tested. Reviewing each section’s examples and being able to explain them in your own words is one of the most effective ways to prepare for SQL-based interview rounds.
Which databases use SQL?
Most relational database management systems use SQL, including MySQL, PostgreSQL, Microsoft SQL Server, Oracle Database, SQLite, and MariaDB. While the core SQL syntax is largely standardized, each database has its own extensions and minor syntax differences for advanced features, so it’s worth checking database-specific documentation for anything beyond standard queries.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before any grouping takes place, and it cannot be used with aggregate functions like SUM() or AVG(). HAVING filters groups of rows after GROUP BY has already summarized the data, and it is specifically meant to be used with aggregate functions. In short, WHERE works on raw rows, and HAVING works on grouped results.
How can I improve my SQL skills?
The most effective way to improve your SQL skills is through consistent, hands-on practice with real datasets rather than only reading syntax. Start by rewriting the examples in this cheat sheet using your own sample tables, then move on to solving practice problems that involve joins, subqueries, and aggregate functions together. Structured, mentor-led practice, like what’s offered through Codegnan’s online MySQL course, can also help you build query-writing speed and confidence for both real projects and interviews faster than self-study alone.




