Thursday, October 9, 2025
HomeData ManagementSQL Cheat Sheet: The Ultimate Guide to Mastering Database Queries

SQL Cheat Sheet: The Ultimate Guide to Mastering Database Queries

Table of Content

Structured Query Language, better known as SQL, is the backbone of data management in modern applications. Whether you’re a software engineer, data analyst, or business intelligence professional, SQL is a skill you can’t ignore.

In this SQL Cheat Sheet, we will cover essential commands, tips, and real-world examples to help you query databases effectively. Think of this as your go-to reference whenever you’re working with relational databases like MySQL, PostgreSQL, SQL Server, or Oracle.

Why You Need an SQL Cheat Sheet

Learning SQL is easy, but remembering every syntax detail can be tricky. That’s where a cheat sheet comes in handy.

Quick reference for SQL commands.
Saves time during coding and debugging.
Helps prepare for SQL interviews.
Provides real-world scenarios for better learning.

Imagine you’re in a job interview and asked to write a query joining three tables — instead of panicking, a mental SQL cheat sheet can guide you.

Getting Started with SQL: Basics You Must Know

SQL is based on relational algebra. Databases are structured into tables (rows and columns), and SQL helps you interact with them.

Example: Creating a Database

CREATE DATABASE company;

USE company;

Example: Creating a Table

CREATE TABLE employees (

    emp_id INT PRIMARY KEY,

    name VARCHAR(100),

    department VARCHAR(50),

    salary DECIMAL(10,2)

);

SQL Data Types Explained

When designing databases, choosing the right data type is crucial.

  • INT → Whole numbers
  • DECIMAL(p,s) → Numbers with decimal precision
  • VARCHAR(n) → Variable-length string
  • DATE / DATETIME → Dates and timestamps
  • BOOLEAN → True/False values

SQL Commands Overview

SQL commands are divided into categories:

Data Manipulation Language (DML) Commands in SQL

DML commands are used to manipulate data stored in database tables. These commands help insert, update, delete, and retrieve records from databases.

Here’s a reference chart you can include:

CommandDescriptionSyntaxExample
INSERTAdds new records into a table.INSERT INTO table_name (column1, column2, …) VALUES (value1, value2, …);INSERT INTO Employees (EmpID, Name, Dept) VALUES (101, ‘John Doe’, ‘HR’);
SELECTRetrieves data from one or more tables.SELECT column1, column2 FROM table_name WHERE condition;SELECT Name, Dept FROM Employees WHERE Dept = ‘HR’;
UPDATEModifies existing records in a table.UPDATE table_name SET column1 = value1 WHERE condition;UPDATE Employees SET Dept = ‘Finance’ WHERE EmpID = 101;
DELETERemoves one or more records from a table.DELETE FROM table_name WHERE condition;DELETE FROM Employees WHERE EmpID = 101;
MERGE (optional – depends on DBMS)Inserts, updates, or deletes records in a target table based on a source table.MERGE INTO target_table USING source_table ON condition WHEN MATCHED THEN UPDATE SET … WHEN NOT MATCHED THEN INSERT …;MERGE INTO Employees AS E USING NewEmployees AS N ON E.EmpID = N.EmpID WHEN MATCHED THEN UPDATE SET E.Dept = N.Dept WHEN NOT MATCHED THEN INSERT (EmpID, Name, Dept) VALUES (N.EmpID, N.Name, N.Dept);

SQL Data Manipulation Language (DML) Commands

DML commands are used to manipulate and manage data stored inside tables. These commands include inserting, updating, retrieving, and deleting records.

CommandDescriptionSyntaxExample
INSERTAdds new record(s) into a table.INSERT INTO table_name (col1, col2, …) VALUES (val1, val2, …);INSERT INTO Employees (EmpID, Name, Dept) VALUES (101, ‘Alice’, ‘HR’);
SELECTRetrieves record(s) from one or more tables.SELECT col1, col2 FROM table_name WHERE condition;SELECT Name, Dept FROM Employees WHERE Dept = ‘HR’;
UPDATEModifies existing record(s) in a table.UPDATE table_name SET col1 = val1 WHERE condition;UPDATE Employees SET Dept = ‘Finance’ WHERE EmpID = 101;
DELETERemoves record(s) from a table.DELETE FROM table_name WHERE condition;DELETE FROM Employees WHERE EmpID = 101;
MERGE (Advanced – depends on DBMS)Performs INSERT, UPDATE, or DELETE in a single statement by comparing source and target tables.MERGE INTO target_table USING source_table ON condition WHEN MATCHED THEN UPDATE SET … WHEN NOT MATCHED THEN INSERT …;sql MERGE INTO Employees AS E USING NewEmployees AS N ON E.EmpID = N.EmpID WHEN MATCHED THEN UPDATE SET E.Dept = N.Dept WHEN NOT MATCHED THEN INSERT (EmpID, Name, Dept) VALUES (N.EmpID, N.Name, N.Dept);

SQL Data Control Language (DCL) Commands

DCL commands are used to control access and permissions in a database. These commands ensure security, authorization, and controlled access to the data.

CommandDescriptionSyntaxExample
GRANTGives a user specific privileges/permissions on database objects (tables, views, procedures, etc.).GRANT privilege_name ON object_name TO user_name;GRANT SELECT, INSERT ON Employees TO John;
REVOKERemoves or restricts previously granted privileges from a user.REVOKE privilege_name ON object_name FROM user_name;REVOKE INSERT ON Employees FROM John;
DENY (SQL Server specific)Explicitly denies a user permission to perform an action, even if granted elsewhere.DENY privilege_name ON object_name TO user_name;DENY DELETE ON Employees TO John;

SQL Transaction Control Language (TCL) Commands

TCL commands are used to manage transactions in a database. A transaction is a sequence of operations performed as a single logical unit of work. These commands ensure data integrity and consistency.

CommandDescriptionSyntaxExample
COMMITSaves all the changes made by the current transaction permanently into the database.COMMIT;INSERT INTO Employees VALUES (101, ‘Alice’, ‘HR’); COMMIT;
ROLLBACKUndoes all the changes made in the current transaction since the last COMMIT.ROLLBACK;DELETE FROM Employees WHERE EmpID = 101; ROLLBACK;
SAVEPOINTSets a point within a transaction to which you can later roll back, without affecting the entire transaction.SAVEPOINT savepoint_name;SAVEPOINT sp1; DELETE FROM Employees WHERE Dept=’Sales’; ROLLBACK TO sp1;
SET TRANSACTIONDefines the characteristics of the transaction (like read/write access or isolation level).`SET TRANSACTION [READ WRITEREAD ONLY];`

SQL SELECT Statement

The SELECT statement is the most frequently used SQL command.

SELECT name, department FROM employees;

Real-Life Example:
A school database retrieves student names and grades for report cards.

SQL WHERE Clause and Filtering Data

Use WHERE to filter rows.

SELECT * FROM employees WHERE salary > 50000;

Real-Life Example:
Filtering out high-value customers who spend more than $1000 in an online store.

SQL Operators and Expressions

  • Arithmetic Operators: +, -, *, /
  • Comparison Operators: =, >, <, >=, <=, <>
  • Logical Operators: AND, OR, NOT

Example:

SELECT * FROM employees WHERE department='HR' AND salary > 40000;

SQL Joins

SQL Joins combine rows from multiple tables.

  • INNER JOIN → Matches rows with common values.
  • LEFT JOIN → All rows from left table, matching from right.
  • RIGHT JOIN → All rows from right table, matching from left.
  • FULL JOIN → Combines results from both tables.

Example:

SELECT e.name, d.department_name

FROM employees e

INNER JOIN departments d ON e.department = d.dept_id;

Real-Life Example:
Joining orders and customers tables to view customer names with their purchases.

SQL GROUP BY and Aggregations

GROUP BY groups records, often used with aggregate functions.

SELECT department, AVG(salary)

FROM employees

GROUP BY department;

Real-Life Example:
Finding average sales per region in a retail company.

SQL ORDER BY and Sorting Results

SELECT name, salary FROM employees ORDER BY salary DESC;

Real-Life Example:
Sorting top-selling products by sales volume.

SQL Subqueries and Nested Queries

SELECT name FROM employees 

WHERE salary > (SELECT AVG(salary) FROM employees);

Real-Life Example:
Finding employees earning above-average salaries.

SQL Constraints

  • PRIMARY KEY → Uniquely identifies rows.
  • FOREIGN KEY → Links tables.
  • UNIQUE → Ensures uniqueness.
  • NOT NULL → Column must have value.
  • CHECK → Enforces condition.

Indexes and Performance Optimization

Indexes speed up queries.

CREATE INDEX idx_salary ON employees(salary);

SQL Views and Virtual Tables

Views simplify complex queries.

CREATE VIEW high_salary AS

SELECT * FROM employees WHERE salary > 60000;

SQL Stored Procedures and Functions

Reusable blocks of code.

CREATE PROCEDURE GetHighSalaryEmployees()

BEGIN

    SELECT * FROM employees WHERE salary > 70000;

END;

SQL Transactions and ACID

Transactions ensure data reliability.

Properties:

  • Atomicity
  • Consistency
  • Isolation
  • Durability

SQL Window Functions

Example:

SELECT name, salary,

RANK() OVER (ORDER BY salary DESC) AS rank

FROM employees;

Advanced SQL Functions to Add

String Functions

  • CONCAT(), SUBSTRING(), LENGTH(), REPLACE() – useful for text manipulation.
  • Example: SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;

Date and Time Functions

  • NOW(), CURDATE(), DATEADD(), DATEDIFF() – to manage timestamps.
  • Example: SELECT DATEDIFF(NOW(), hire_date) AS days_worked FROM employees;

Aggregate Functions

  • Beyond basics: GROUP_CONCAT(), STRING_AGG() (PostgreSQL, SQL Server).

Example: SELECT department, GROUP_CONCAT(employee_name) FROM employees GROUP BY department;

SQL Joins in Real-Time Applications

  • Inner Join → Matching records from two tables (e.g., customers & orders).
  • Left Join → All customers with or without orders.
  • Full Outer Join → Data from both tables even without matches.
  • Self Join → Employees and their managers within the same table.

SQL Performance Tuning Techniques

  • Use Indexes: Speeds up queries by creating fast lookups.
  • Avoid SELECT *: Retrieve only required columns.
  • Use EXPLAIN (or QUERY PLAN) to analyze queries.
  • Normalize large databases but denormalize for read-heavy systems.

SQL Security Best Practices

  • Parameterized Queries / Prepared Statements → Prevents SQL Injection.
  • Role-Based Access Control (RBAC) → Restrict users to certain operations.
  • Encrypt Sensitive Data → Protect personally identifiable information (PII).
  • Backup & Recovery Plans → Essential for production systems.

SQL vs NoSQL – When to Use?

SQL vs NoSQL – When to Use?
*datasciencedojo.com
  • SQL Databases (MySQL, PostgreSQL, Oracle, SQL Server):
    • Structured data, ACID compliance, transactional apps (banking, ERP).
  • NoSQL Databases (MongoDB, Cassandra):
    • Flexible schemas, large-scale unstructured data, IoT, social media.
  • Example: An e-commerce site might use SQL for inventory and NoSQL for user reviews.

SQL in Data Science & Machine Learning

  • Extracting structured datasets for pandas or R.
  • Writing complex queries to prepare features for ML models.

Example:

SELECT customer_id, AVG(order_amount) AS avg_spent

FROM orders

GROUP BY customer_id;

SQL in Cloud & Big Data

  • Google BigQuery → SQL-based analytics for petabyte-scale data.
  • AWS Athena → Serverless SQL queries on S3 data.
  • Snowflake → Cloud-native SQL warehouse.
  • Real-time pipelines often use SQL-like queries in Apache Spark (SparkSQL).

Real-Life Use Cases of SQL

  • Banking – Fraud detection by analyzing transaction history.
  • Healthcare – Patient record management with joins across hospital systems.
  • Retail – Inventory tracking and personalized recommendations.
  • Social Media – Analyzing user activity for targeted advertising.

SQL Cheat Sheet – Quick Query Reference (Extra Section)

Create Table

CREATE TABLE employees (

    id INT PRIMARY KEY,

    name VARCHAR(100),

    hire_date DATE

);

Insert Data

INSERT INTO employees (id, name, hire_date) VALUES (1, 'John Doe', '2023-01-10');

Update Data

UPDATE employees SET name='Jane Doe' WHERE id=1;

Delete Data

DELETE FROM employees WHERE id=1;

Select Query

SELECT * FROM employees;

Conclusion

This SQL Cheat Sheet is designed to help you navigate SQL commands, concepts, and real-time applications effectively. Whether you’re building a data-driven app, analyzing business metrics, or preparing for an interview, these examples and references will serve as a powerful toolkit.SQL remains one of the most in-demand skills, bridging data analysis and software development. With this guide, you now have a comprehensive reference to work faster, smarter, and more efficiently with databases

FAQ’s

What are the 5 basic SQL commands?

SQL commands are divided into five main categories, each serving a different purpose in database management:
DDL (Data Definition Language) – Defines the structure of the database.
Commands: CREATE, ALTER, DROP, TRUNCATE
Example: CREATE TABLE Employees (ID INT, Name VARCHAR(50));
DML (Data Manipulation Language) – Manages and manipulates the data inside tables.
Commands: SELECT, INSERT, UPDATE, DELETE
Example: INSERT INTO Employees (Name, Age) VALUES ('John', 30);
DCL (Data Control Language) – Manages access and permissions for users.
Commands: GRANT, REVOKE
Example: GRANT SELECT ON Employees TO User1;
TCL (Transaction Control Language) – Handles transactions and ensures data integrity.
Commands: COMMIT, ROLLBACK, SAVEPOINT
Example: ROLLBACK; (undoes uncommitted changes)
DQL (Data Query Language) – Focuses on retrieving data from the database.
Command: SELECT
Example: SELECT * FROM Employees WHERE Age > 25;

How to Use ORDER BY Clause in SQL?

The ORDER BY clause in SQL is used to sort query results in either ascending (ASC) or descending (DESC) order. By default, sorting is ascending.
Syntax:

SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC];
Examples:
SELECT * FROM Employees ORDER BY Name ASC; → sorts employees by name in alphabetical order.
SELECT * FROM Employees ORDER BY Salary DESC; → sorts employees by salary in highest to lowest order.
SELECT * FROM Employees ORDER BY Department ASC, Salary DESC; → sorts first by department, then within each department by salary (highest first).

The most fundamental clauses used with SELECT are?

The SELECT statement in SQL is often combined with several fundamental clauses to filter, group, and sort data. The most important ones are:
FROM – Specifies the table to retrieve data from.
Example: SELECT Name FROM Employees;
WHERE – Filters rows based on a condition.
Example: SELECT * FROM Employees WHERE Age > 30;
GROUP BY – Groups rows that share the same values.
Example: SELECT Department, COUNT(*) FROM Employees GROUP BY Department;
HAVING – Filters groups created by GROUP BY.
Example: SELECT Department, COUNT(*) FROM Employees GROUP BY Department HAVING COUNT(*) > 5;
ORDER BY – Sorts the result set in ascending or descending order.
Example: SELECT * FROM Employees ORDER BY Salary DESC;

How to write a SQL query in a database?

Writing a SQL query involves selecting the database you want to work with, choosing the table, and applying the correct SQL commands. The basic steps are:
Choose the database – Use the USE statement if multiple databases exist.

USE company_db;
Start with SELECT – Decide which columns you want to retrieve.

SELECT Name, Age FROM Employees;
Add filtering with WHERE – Narrow down results using conditions.

SELECT Name, Age FROM Employees WHERE Age > 30;
Organize with ORDER BY or GROUP BY – Sort or group your data.

SELECT Department, COUNT(*) FROM Employees GROUP BY Department ORDER BY COUNT(*) DESC;

What are SQL keywords?

SQL keywords are reserved words in Structured Query Language that have special meaning and are used to perform specific operations on databases. These keywords form the building blocks of SQL commands and cannot be used as names for tables, columns, or other identifiers.
Examples of SQL keywords include:
SELECT – retrieve data
FROM – specify the source table
WHERE – filter records
INSERT, UPDATE, DELETE – manipulate data
CREATE, ALTER, DROP – define or modify database structures
JOIN, GROUP BY, ORDER BY – combine and organize results

Leave feedback about this

  • Rating
Choose Image

Latest Posts

List of Categories

Hi there! We're upgrading to a smarter chatbot experience.

For now, click below to chat with our AI Bot on Instagram for more queries.

Chat on Instagram