25
JulSQL Cheat Sheet: Full Guide for Beginners & Professionals
SQL Cheat Sheet is your one-stop reference to the most important SQL commands, syntax, and concepts you need to work efficiently with databases. With real-world examples and clear explanations, this cheat sheet will help you write better, faster, and more optimized SQL queries for any relational database.
Whether you're a beginner trying to learn the basics or a professional looking to brush up on advanced SQL queries, this SQL cheat sheet provides a concise, comprehensive overview of essential commands, functions, and best practices. From creating tables and retrieving data to using joins, subqueries, and aggregate functions, this guide is designed to help you write efficient SQL queries with confidence.
Step 1: SQL Basics
1. SQL Structured Query Language
SQL is a standard programming language used to manage and manipulate relational databases. It allows you to insert, update, delete, and retrieve data from databases.
Syntax :
SELECT * FROM Employees;
This SQL command retrieves all records from the Employees table.
Real-World Example: Think of SQL like a menu at a restaurant. You choose query what food data you want, and the kitchen database serves it to you.
2. DBMS Database Management System
A DBMS is software that allows you to create, manage, and use databases. It stores data in a structured format and provides tools for querying and maintaining the data.
- Popular DBMSs: MySQL, PostgreSQL, Oracle, Microsoft SQL Server, SQLite
- Real-World Example: Imagine a library – the DBMS is the librarian who helps you find books data, adds new ones, or removes outdated ones.
3. Table
A table is a collection of related data organized in rows and columns. It represents one entity type—like Customers, Orders, or Products.
Syntax Example:
CREATE TABLE Students (
ID INT,
Name VARCHAR(50),
Age INT
);
Real-World Example: A table is like a spreadsheet in Excel or Google Sheets—each sheet table contains related information.
4. Row
A row also called a record in a table represents a single data item or entry. Each row contains a complete set of values for each column.
Example:
ID | Name | Age |
---|---|---|
1 | John Doe | 22 |
This single line is a row, representing one student.
Real-World Example: Think of a student admission form—each form is a row in the table of students.
5. Column
A column defines the type of data stored for each row in that field. It represents a specific attribute.
Example: In the Students table:
- ID is a column for student ID numbers.
- Name is a column for student names.
- Age is a column for their age.
Real-World Example: Each blank field in a form that says Enter your Name, Enter your Age, etc., is a column.
Step 2: Data Types
In SQL, data types define the kind of data a column can store. Choosing the right data type is crucial for accurate, fast, and reliable database design.
Data Type - What is it?
A data type tells the database what kind of value can be stored in a column such as number, text, or date.
CREATE TABLE Products (
ProductID INT,
Name VARCHAR 100,
Price DECIMAL 8,2
);
This example stores product ID as a number, name as short text, and price as a decimal with 2 digits after the point.
1. INT Integer
Stores whole numbers positive or negative without decimals.
Age INT
CREATE TABLE Students (
ID INT,
Age INT
);
Used for Age, Quantity, Serial numbers
ID | Age |
---|---|
1 | 25 |
2. VARCHAR n
Stores variable length text up to n characters. Saves only needed space.
Name VARCHAR 50
CREATE TABLE Employees (
Name VARCHAR 50
);
Used for Names, Cities, Titles
Name |
---|
John Doe |
3. TEXT
Stores long text such as descriptions or paragraphs.
Description TEXT
CREATE TABLE Articles (
Title VARCHAR 100,
Content TEXT
);
Used for Blogs, Product Descriptions, Comments
Title | Content |
---|---|
SQL Basics | SQL is a language used to manage data in databases |
4. DATE
Stores date values in YYYY-MM-DD format
DOB DATE
CREATE TABLE Students (
Name VARCHAR 50,
DOB DATE
);
Used for Birth dates, Order dates, Join dates
Name | DOB |
---|---|
Alice | 2005-06-12 |
5. BOOLEAN
Stores TRUE or FALSE values represented as 1 or 0 in some databases
IsActive BOOLEAN
CREATE TABLE Users (
Username VARCHAR 50,
IsActive BOOLEAN
);
Used for Is user active, In stock, Payment made
Username | IsActive |
---|---|
admin | TRUE |
6. DECIMAL p s
Stores exact numbers with decimal points. p is total digits, s is digits after the point
Price DECIMAL 6,2
CREATE TABLE Products (
ProductName VARCHAR 100,
Price DECIMAL 8,2
);
Used for Prices, Tax, Financial values
ProductName | Price |
---|---|
Smartphone | 749.99 |
List of Datatypes
Data Type | Description |
---|---|
INT | Integer values |
VARCHAR(n) | Variable-length character string |
CHAR(n) | Fixed-length string |
TEXT | Large text values |
DATE | Date values (YYYY-MM-DD) |
TIME | Time values (HH:MM:SS) |
DATETIME | Date and time |
BOOLEAN | TRUE or FALSE |
Step 3: SQL CRUD Operations
CRUD stands for the four basic operations you can perform on a SQL database Create Read Update and Delete. These are used to manage data in a table.
1. CREATE: Insert New Data
Used to add new records into a table.
INSERT INTO Students ID Name Age
VALUES 1 Alice 14
This adds a new student record into the Students table.
Real world example A new student fills out the admission form and the data is stored in the system.
2. READ: Retrieve Data
Used to fetch data from a table using SELECT statement.
SELECT star FROM Students
This retrieves all student records from the Students table.
ID | Name | Age |
---|---|---|
1 | Alice | 14 |
Real world example A teacher views the list of all enrolled students.
3. UPDATE: Modify Existing Data
Used to change existing records in a table.
UPDATE Students
SET Age 15
WHERE ID 1
This updates the age of the student with ID 1 to 15.
Real world example A student's age was entered incorrectly and needs to be corrected.
4. DELETE: Remove Data
Used to remove records from a table.
DELETE FROM Students
WHERE ID 1
This deletes the student record with ID 1 from the Students table.
Real world example A student transfers to another school and their record is removed from the system.
Step 4: Filtering and Sorting
Filtering and sorting in SQL help you control what data to retrieve and how to display it. These features are essential for narrowing down and organizing query results.
1. WHERE Clause
The WHERE clause is used to filter rows based on a specific condition.
SELECT star FROM Students
WHERE Age greater than 14
This returns all students older than 14.
ID | Name | Age |
---|---|---|
2 | Bob | 15 |
Real world example A teacher wants to see only students older than 14.
2. AND OR NOT
AND Operator
Returns rows where both conditions are true.
SELECT star FROM Students
WHERE Age greater than 14 AND Grade equals 9
Real world example Show students who are older than 14 and in grade 9.
OR Operator
Returns rows where at least one condition is true.
SELECT star FROM Students
WHERE Age equals 14 OR Grade equals 8
Real world example Show students who are either 14 years old or in grade 8.
NOT Operator
Returns rows where the condition is false.
SELECT star FROM Students
WHERE NOT Grade equals 10
Real world example Show all students except those in grade 10.
3. ORDER BY
Used to sort the result set in ascending or descending order.
SELECT star FROM Students
ORDER BY Age DESC
This sorts students by age from highest to lowest.
ID | Name | Age |
---|---|---|
2 | Bob | 15 |
1 | Alice | 14 |
Real world example Sort students by age from oldest to youngest.
4. LIMIT and TOP
LIMIT in MySQL or PostgreSQL
Used to return a limited number of rows.
SELECT star FROM Students
LIMIT 3
Real world example Show only the first 3 students.
TOP in SQL Server
Used similarly to LIMIT in SQL Server.
SELECT TOP 3 star FROM Students
Real world example Show top 3 students in the list.
Step 5: Aggregate Functions in SQL
Aggregate functions perform calculations on multiple rows of a table and return a single value. They are commonly used with the GROUP BY clause in reporting and data analysis.
1. COUNT()
This function returns the number of rows that match a specified condition.
Syntax:
SELECT COUNT(column_name) FROM table_name WHERE condition;
Example:
SELECT COUNT(*) FROM Employees;
Real-world Use Case: You are building an HR dashboard and need to show how many employees are in the company.
2. SUM()
This function Returns the total sum of a numeric column.
Syntax:
SELECT SUM(column_name) FROM table_name WHERE condition;
Example:
SELECT SUM(Salary) FROM Employees WHERE Department = 'Sales';
Real-world Use Case: To calculate total revenue, expenses, or budget for a department or project.
3. AVG()
It Returns the average value of a numeric column.
Syntax:
SELECT AVG(column_name) FROM table_name WHERE condition;
Example:
SELECT AVG(Salary) FROM Employees;
Real-world Use Case: To determine average customer spend, employee salary, product rating, etc.
4. MIN()
Min() returns the smallest (minimum) value in a column.
Syntax:
SELECT MIN(column_name) FROM table_name;
Example:
SELECT MIN(Price) FROM Products;
Real-world Use Case: To find the cheapest product, minimum grade, or earliest joining date.
5. MAX()
It Returns the largest (maximum) value in a column.
Syntax:
SELECT MAX(column_name) FROM table_name;
Example:
SELECT MAX(Salary) FROM Employees;
Real-world Use Case: To identify the most expensive item, top scorer, or latest order date.
Step 6: GROUP BY and HAVING
When working with aggregated data like totals or averages you can group and filter your results using GROUP BY and HAVING clauses.
1 GROUP BY Clause
The GROUP BY clause groups rows that have the same values into summary rows. It is commonly used with aggregate functions like COUNT SUM AVG MAX and MIN.
GROUP BY Syntax
SELECT column_name AGGREGATE_FUNCTION column_name
FROM table_name
GROUP BY column_name
Example
Customer | Product | Quantity |
---|---|---|
Alice | Book | 2 |
Bob | Pen | 5 |
Alice | Pen | 3 |
Bob | Book | 1 |
Query Group Total Quantity by Customer
SELECT Customer SUM Quantity AS TotalOrdered
FROM Orders
GROUP BY Customer
Output
Customer | TotalOrdered |
---|---|
Alice | 5 |
Bob | 6 |
Real world example You want to know how many items each customer has ordered.
2 HAVING Clause
The HAVING clause is used to filter groups created by GROUP BY. Unlike WHERE which filters rows HAVING filters groups based on an aggregate condition.
HAVING Syntax
SELECT column_name AGGREGATE_FUNCTION column_name
FROM table_name
GROUP BY column_name
HAVING AGGREGATE_FUNCTION column_name condition
Query Show customers who ordered more than 5 items
SELECT Customer SUM Quantity AS TotalOrdered
FROM Orders
GROUP BY Customer
HAVING SUM Quantity greater than 5
Output
Customer | TotalOrdered |
---|---|
Bob | 6 |
Real world example Find customers who placed large orders with total quantity above 5.
Step 7: SQL Joins
SQL Joins are used to combine data from two or more tables based on a related column. It allows you to build relationships across multiple tables using keys.
Sample Tables
Table Customers
CustomerID | CustomerName |
---|---|
1 | Alice |
2 | Bob |
3 | Charlie |
Table Orders
OrderID | CustomerID | Product |
---|---|---|
101 | 1 | Book |
102 | 2 | Pen |
103 | 4 | Pencil |
1. INNER JOIN
Returns rows that have matching values in both tables.
SELECT Customers CustomerName Orders Product
FROM Customers
INNER JOIN Orders ON Customers CustomerID equals Orders CustomerID
Output
CustomerName | Product |
---|---|
Alice | Book |
Bob | Pen |
Use case Show customers who have placed orders
2. LEFT JOIN
Returns all rows from the left table and matched rows from the right table. Non matching rows will show nulls on the right side.
SELECT Customers CustomerName Orders Product
FROM Customers
LEFT JOIN Orders ON Customers CustomerID equals Orders CustomerID
Output
CustomerName | Product |
---|---|
Alice | Book |
Bob | Pen |
Charlie | NULL |
Use case Show all customers and their orders even if some have not ordered
3. RIGHT JOIN
Returns all rows from the right table and matched rows from the left table. Non matching rows will show nulls on the left side.
SELECT Customers CustomerName Orders Product
FROM Customers
RIGHT JOIN Orders ON Customers CustomerID equals Orders CustomerID
Output
CustomerName | Product |
---|---|
Alice | Book |
Bob | Pen |
NULL | Pencil |
Use case Show all orders even if some do not have a matching customer
4. FULL JOIN
Returns all rows when there is a match in either left or right table. If no match the result shows null on the missing side.
SELECT Customers CustomerName Orders Product
FROM Customers
FULL JOIN Orders ON Customers CustomerID equals Orders CustomerID
Output
CustomerName | Product |
---|---|
Alice | Book |
Bob | Pen |
Charlie | NULL |
NULL | Pencil |
Use case Get a complete list of customers and orders including unmatched data
Step 8: Subqueries
A subquery is a query written inside another SQL query. It is used to return data that will be used by the main outer query.
Subquery Syntax
SELECT column_name
FROM table_name
WHERE column_name IN
SELECT column_name FROM another_table WHERE condition
Example Table Students
StudentID | Name | Marks |
---|---|---|
1 | Alice | 90 |
2 | Bob | 75 |
3 | Clara | 88 |
Query Students scoring above average
SELECT Name
FROM Students
WHERE Marks greater than
SELECT AVG Marks FROM Students
Output
Name |
---|
Alice |
Clara |
Real world example Find students who scored above the class average
Step 9: Aliases
An alias is a temporary name given to a table or column. It is used for better readability and simpler query writing especially in complex joins or reports.
Column Alias Syntax
SELECT column_name AS alias_name
FROM table_name
Table Alias Syntax
SELECT t column1 t column2
FROM table_name AS t
Example Table Employees
EmpID | FullName | Salary |
---|---|---|
1 | John Williams | 50000 |
2 | Sarah Parker | 60000 |
Query Rename FullName as EmployeeName
SELECT FullName AS EmployeeName Salary
FROM Employees
Output
EmployeeName | Salary |
---|---|
John Williams | 50000 |
Sarah Parker | 60000 |
Query Using Table Alias
SELECT e FullName e Salary
FROM Employees AS e
Step 10: Constraints
Constraints in SQL are rules used to limit the type of data that can be stored in a table. They help ensure the accuracy and integrity of the database.
1. PRIMARY KEY
The PRIMARY KEY uniquely identifies each row in a table. It cannot contain null values and must be unique for every record.
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR 100
)
Use case Each student should have a unique ID.
2. FOREIGN KEY
The FOREIGN KEY links two tables by referencing the primary key of another table. It ensures referential integrity.
CREATE TABLE Orders (
OrderID INT,
StudentID INT,
FOREIGN KEY StudentID REFERENCES Students StudentID
)
Use case Make sure each order belongs to a valid student.
3. NOT NULL
The NOT NULL constraint prevents a column from having null values. It forces the user to always provide a value.
CREATE TABLE Courses (
CourseID INT,
CourseName VARCHAR 100 NOT NULL
)
Use case Ensure every course has a name.
4. UNIQUE
The UNIQUE constraint ensures all values in a column are different. It prevents duplicate entries in that column.
CREATE TABLE Users (
UserID INT,
Email VARCHAR 100 UNIQUE
)
Use case Make sure each email is registered only once.
5. CHECK
The CHECK constraint limits the values that can be placed in a column by setting a condition.
CREATE TABLE Employees (
EmpID INT,
Age INT CHECK Age greater than or equal to 18
)
Use case Allow only employees who are 18 or older.
6. DEFAULT
The DEFAULT constraint sets a default value for a column if no value is specified by the user.
CREATE TABLE Accounts (
AccountID INT,
Status VARCHAR 20 DEFAULT Active
)
Use case Set new accounts to Active status by default.
Read More: Differences between Primary Key and Foreign Key |
Step 11: Table Operations
1. CREATE TABLE
Used to create a new table with defined columns and data types.
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR 100,
Age INT
)
Use case Create a student table to store data with unique IDs.
2. ALTER TABLE
Used to add modify or delete columns in an existing table.
Add Column
ALTER TABLE Students ADD Email VARCHAR 100
Modify Column
ALTER TABLE Students ALTER COLUMN Age INT
Drop Column
ALTER TABLE Students DROP COLUMN Email
Use case Adjust the table structure as per updated requirements.
3. DROP TABLE
Deletes the table and all its data permanently from the database.
DROP TABLE Students
Use case Remove tables that are no longer needed.
Step 12: Other Concepts
1. Indexes
Indexes improve the speed of data retrieval queries by allowing faster searches.
CREATE INDEX idx_name ON Students Name
Use case Speed up lookup based on student names.
2. Views
Views are virtual tables created from a SELECT query. They do not store data themselves.
CREATE VIEW StudentView AS
SELECT Name Age FROM Students WHERE Age greater than 18
Use case Show only students above a certain age without exposing full table.
3. Stored Procedures
A stored procedure is a block of SQL statements stored in the database and executed as a single call.
CREATE PROCEDURE GetAllStudents
AS
SELECT * FROM Students
Execution
EXEC GetAllStudents
Use case Reuse common operations like fetching student list in reports.
4. Transactions
Transactions group multiple SQL statements into a single unit of work that can be committed or rolled back.
BEGIN TRANSACTION
UPDATE Accounts SET Balance equals Balance minus 100 WHERE AccountID equals 1
UPDATE Accounts SET Balance equals Balance plus 100 WHERE AccountID equals 2
COMMIT
Rollback Example
ROLLBACK
Use case Ensure safe transfer of money between two accounts by making both updates succeed or fail together.
Step 13 Best Practices to Learn SQL
1. Use Online Interactive Platforms
Start learning SQL on hands on websites where you can write and test queries instantly.
- Popular Platforms: Scholarhat, LeetCode HackerRank Mode
- Why: You will get immediate feedback and guided examples perfect for beginners.
- Tip: Solve at least five SQL problems daily to improve steadily.
2. Install a Local SQL Environment
Set up a database system on your computer to experience real database management.
- Recommended Tools: MySQL PostgreSQL SQLite Microsoft SQL Server Express
- Why: You learn how to create tables import data and run SQL on real systems.
- Tip: Try importing CSV files into your tables and query from them.
3.Work with Sample Databases
Practice with real world datasets that mimic business scenarios.
- Popular Databases: Sakila Northwind Chinook AdventureWorks
- Why: Helps understand business logic like orders customers and inventory.
- Tip: Ask questions and write queries to answer them using the data.
4 Take Mini Projects
Build simple database projects that integrate all you learn.
- Project Ideas: Student system Library management Online store Payroll system
- Why: Projects reinforce learning and prepare you for real use cases.
- Tip: Document your project and push it to GitHub with a readme file.
5 Practice Writing Queries Daily
Consistent practice is the best way to get fluent in SQL.
- Suggestions: Use LeetCode StrataScratch or HackerRank daily
- Why: Improves syntax recall and problem solving ability.
- Tip: Maintain a SQL log journal where you write what you practiced.
Conclusion
This cheat sheet covers all essential SQL concepts from selecting data to advanced joins and indexing. Mastering these will help you crack interviews, optimize performance, and write clean, production-ready queries. Meanwhile if you want to master SQL We brought you Free course on SQL Server check it out and win the SQL this time. Click Here and Start Learning.
FAQs
Take our Sqlserver skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.