SQL Cheat Sheet: Full Guide for Beginners & Professionals

SQL Cheat Sheet: Full Guide for Beginners & Professionals

23 Jul 2025
Beginner
31 Views
40 min read
Learn with an interactive course and practical hands-on labs

Free SQL Server Online Course with Certificate - Start Today

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.

SQL Cheat Sheet

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:

IDNameAge
1John Doe22

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

IDAge
125

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

TitleContent
SQL BasicsSQL 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

NameDOB
Alice2005-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

UsernameIsActive
adminTRUE

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

ProductNamePrice
Smartphone749.99

List of Datatypes

Data TypeDescription
INTInteger values
VARCHAR(n)Variable-length character string
CHAR(n)Fixed-length string
TEXTLarge text values
DATEDate values (YYYY-MM-DD)
TIMETime values (HH:MM:SS)
DATETIMEDate and time
BOOLEANTRUE 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.

IDNameAge
1Alice14

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.

IDNameAge
2Bob15

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.

IDNameAge
2Bob15
1Alice14

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 

CustomerProductQuantity
AliceBook2
BobPen5
AlicePen3
BobBook1

Query Group Total Quantity by Customer

SELECT Customer SUM Quantity AS TotalOrdered
FROM Orders
GROUP BY Customer

Output

CustomerTotalOrdered
Alice5
Bob6

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

CustomerTotalOrdered
Bob6

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

CustomerIDCustomerName
1Alice
2Bob
3Charlie

Table Orders

OrderIDCustomerIDProduct
1011Book
1022Pen
1034Pencil

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

CustomerNameProduct
AliceBook
BobPen

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

CustomerNameProduct
AliceBook
BobPen
CharlieNULL

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

CustomerNameProduct
AliceBook
BobPen
NULLPencil

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

CustomerNameProduct
AliceBook
BobPen
CharlieNULL
NULLPencil

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

StudentIDNameMarks
1Alice90
2Bob75
3Clara88

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

EmpIDFullNameSalary
1John Williams50000
2Sarah Parker60000

Query Rename FullName as EmployeeName

SELECT FullName AS EmployeeName Salary
FROM Employees

Output

EmployeeNameSalary
John Williams50000
Sarah Parker60000

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

 A primary key uniquely identifies each record in a table. It cannot be null and must be unique. 

Normalization is the process of organizing data to reduce redundancy and improve data integrity. It involves dividing a database into two or more related tables. 

 An index improves the speed of data retrieval from a table at the cost of additional space and slower write operations. 

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.

GET FREE CHALLENGE

Live Training - Book Free Demo
ASP.NET Core Certification Training
26 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Advanced Full-Stack .NET Developer with Gen AI Certification Training
26 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
.NET Microservices Certification Training
27 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
ASP.NET Core Project
27 Jul
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
.NET Solution Architect Certification Training
27 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this