Skip to content
SQL Cheat Sheet for Beginners
Back to Blog
Technology & AI12 min read

SQL Cheat Sheet for Beginners

G

GoBizly

10 October 2026

SQL Cheat Sheet for Beginners: Commands, Queries & Examples

SQL (Structured Query Language) is used to communicate with relational databases. It helps you retrieve, filter, organize, analyze, insert, update, and delete data stored in tables.

SQL is widely used in data analytics, business intelligence, software development, reporting, and database administration.

This cheat sheet explains the most important SQL commands with examples you can use as a quick reference while learning or preparing for interviews.

1. What Is SQL?

SQL allows users to work with structured data stored in relational databases.

A database typically contains tables. Each table contains rows and columns.

For example, an Employees table might contain:

employee_id

name

department

salary

101

Alex

Marketing

45000

102

Priya

Finance

55000

103

Rahul

Marketing

50000

104

Sara

Technology

65000

  • Column: A particular attribute, such as name.

  • Row: One record, such as an employee's details.

  • Primary key: A column or combination of columns that uniquely identifies each row.

  • Foreign key: A column or combination of columns that references a key in another table.

  • Query: An instruction used to retrieve or manipulate data.

Popular relational database systems include MySQL, PostgreSQL, Microsoft SQL Server, Oracle Database, and SQLite.

2. Basic SQL Syntax

The most common SQL query retrieves data using SELECT.

SELECT name, department
FROM Employees;

This returns the name and department columns for all rows in the Employees table.

To retrieve every column:

SELECT *
FROM Employees;

The * represents all columns. In production queries, selecting only the columns you need is often preferable.

SQL keywords are commonly written in uppercase for readability, although many SQL implementations treat keywords as case-insensitive.

A semicolon (;) commonly marks the end of a SQL statement.

3. Essential SQL Commands

SQL commands are often grouped by their purpose.

Category

Full form

Common commands

DQL

Data Query Language

SELECT

DML

Data Manipulation Language

INSERT, UPDATE, DELETE

DDL

Data Definition Language

CREATE, ALTER, DROP, TRUNCATE

DCL

Data Control Language

GRANT, REVOKE

TCL

Transaction Control Language

COMMIT, ROLLBACK, SAVEPOINT

These groupings are common teaching conventions; classifications can vary by database system and reference.

4. SELECT: Retrieve Data

Use SELECT to choose which columns to return.

SELECT name, salary
FROM Employees;

Retrieve distinct values:

SELECT DISTINCT department
FROM Employees;

This returns each department once.

Limit the number of returned rows:

SELECT *
FROM Employees
LIMIT 5;

LIMIT is supported by systems such as MySQL, PostgreSQL, and SQLite. SQL Server commonly uses TOP or OFFSET ... FETCH, while other systems may use different syntax.

5. WHERE: Filter Records

The WHERE clause filters rows according to a condition.

SELECT *
FROM Employees
WHERE department = 'Marketing';

Find employees earning more than 50,000:

SELECT name, salary
FROM Employees
WHERE salary > 50000;

Comparison Operators

Operator

Meaning

=

Equal to

<>

Not equal to

!=

Not equal to in many systems

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

Combine Conditions

SELECT *
FROM Employees
WHERE department = 'Marketing'
  AND salary >= 45000;

Use OR when at least one condition should be true:

SELECT *
FROM Employees
WHERE department = 'Marketing'
   OR department = 'Finance';

Use parentheses when combining AND and OR to make the intended logic clear.

6. AND, OR, and NOT

These logical operators combine or reverse conditions.

SELECT *
FROM Employees
WHERE department = 'Marketing'
  AND salary > 45000;
SELECT *
FROM Employees
WHERE department = 'Marketing'
   OR salary > 60000;
SELECT *
FROM Employees
WHERE NOT department = 'Finance';

Remember that NULL represents a missing or unknown value. Conditions involving NULL do not behave like ordinary equality comparisons.

7. BETWEEN, IN, and LIKE

BETWEEN

Find salaries within a range:

SELECT *
FROM Employees
WHERE salary BETWEEN 45000 AND 60000;

BETWEEN includes both endpoints.

IN

Match values from a list:

SELECT *
FROM Employees
WHERE department IN ('Marketing', 'Finance');

LIKE

Search text using patterns:

SELECT *
FROM Employees
WHERE name LIKE 'A%';

Common pattern symbols:

Pattern

Meaning

'A%'

Starts with A

'%a'

Ends with a

'%ar%'

Contains ar

'_lex'

Any one character followed by lex

In LIKE patterns, % represents zero or more characters and _ represents a single character. Case sensitivity depends on the database and collation.

8. ORDER BY: Sort Results

Sort employees by salary in ascending order:

SELECT name, salary
FROM Employees
ORDER BY salary ASC;

Sort from highest to lowest:

SELECT name, salary
FROM Employees
ORDER BY salary DESC;

Sort by multiple columns:

SELECT *
FROM Employees
ORDER BY department ASC, salary DESC;
  • ASC: Ascending order.

  • DESC: Descending order.

If you need predictable ordering when values are tied, add a unique column as a final sorting criterion.

9. Aggregate Functions

Aggregate functions calculate values across multiple rows.

Function

Purpose

COUNT()

Counts rows or non-NULL values

SUM()

Calculates a total

AVG()

Calculates an average

MIN()

Finds the minimum

MAX()

Finds the maximum

Examples:

SELECT COUNT(*) AS employee_count
FROM Employees;
SELECT SUM(salary) AS total_salary
FROM Employees;
SELECT AVG(salary) AS average_salary
FROM Employees;
SELECT MIN(salary), MAX(salary)
FROM Employees;

Most aggregate functions ignore NULL values. COUNT(*) counts rows, including rows containing NULL in individual columns.

10. GROUP BY: Summarize Data

GROUP BY groups rows with matching values so aggregate functions can summarize each group.

Calculate the number of employees in each department:

SELECT department, COUNT(*) AS employee_count
FROM Employees
GROUP BY department;

Calculate average salary by department:

SELECT department, AVG(salary) AS average_salary
FROM Employees
GROUP BY department;

Every selected column that is not aggregated generally needs to be included in GROUP BY, subject to the database's rules.

11. HAVING: Filter Groups

WHERE filters individual rows before grouping. HAVING filters groups after aggregation.

SELECT department, COUNT(*) AS employee_count
FROM Employees
GROUP BY department
HAVING COUNT(*) > 2;

This returns departments containing more than two employees.

You can combine WHERE and HAVING:

SELECT department, AVG(salary) AS average_salary
FROM Employees
WHERE salary > 30000
GROUP BY department
HAVING AVG(salary) > 45000;

Here, rows with salaries of 30,000 or less are excluded before the average is calculated, and only groups with an average above 45,000 are returned.

12. SQL Joins

Joins combine related data from multiple tables.

Imagine a second table called Departments:

department_id

department

1

Marketing

2

Finance

3

Technology

Suppose Employees also contains a department_id column that references Departments.department_id.

INNER JOIN

Returns rows with matching records in both tables.

SELECT e.name, d.department
FROM Employees AS e
INNER JOIN Departments AS d
    ON e.department_id = d.department_id;

LEFT JOIN

Returns every row from the left table and matching rows from the right table. If there is no match, right-side columns are typically NULL.

SELECT e.name, d.department
FROM Employees AS e
LEFT JOIN Departments AS d
    ON e.department_id = d.department_id;

RIGHT JOIN

Returns every row from the right table and matching rows from the left table.

SELECT e.name, d.department
FROM Employees AS e
RIGHT JOIN Departments AS d
    ON e.department_id = d.department_id;

Support for particular join types varies across database systems.

FULL OUTER JOIN

Returns matching rows and unmatched rows from both tables, with missing-side columns filled with NULL.

SELECT e.name, d.department
FROM Employees AS e
FULL OUTER JOIN Departments AS d
    ON e.department_id = d.department_id;

Not all database systems support FULL OUTER JOIN directly.

CROSS JOIN

Returns every combination of rows from the two tables.

SELECT e.name, d.department
FROM Employees AS e
CROSS JOIN Departments AS d;

Quick Join Reference

Join

Main behavior

INNER JOIN

Matching rows only

LEFT JOIN

All left rows plus matches

RIGHT JOIN

All right rows plus matches

FULL OUTER JOIN

All rows from both sides

CROSS JOIN

Every possible combination

13. INSERT: Add New Records

Use INSERT INTO to add a record.

INSERT INTO Employees
    (employee_id, name, department, salary)
VALUES
    (105, 'Amit', 'Finance', 48000);

Insert multiple records where supported:

INSERT INTO Employees
    (employee_id, name, department, salary)
VALUES
    (106, 'Neha', 'Marketing', 52000),
    (107, 'John', 'Technology', 61000);

The syntax for inserting multiple rows can vary by database system.

Specify column names rather than relying on the table's column order.

14. UPDATE: Modify Existing Records

Use UPDATE to change existing values.

UPDATE Employees
SET salary = 55000
WHERE employee_id = 101;

Update multiple columns:

UPDATE Employees
SET department = 'Marketing',
    salary = 57000
WHERE employee_id = 101;

Important: Without a suitable WHERE clause, an update may modify every row in the table.

Before performing a sensitive update, run a SELECT with the same condition to confirm which records will be affected.

15. DELETE: Remove Records

Delete a specific record:

DELETE FROM Employees
WHERE employee_id = 105;

Delete records matching a condition:

DELETE FROM Employees
WHERE department = 'Temporary';

Without WHERE, DELETE can remove every row from the table.

Always verify the target records before deleting data, and use transactions where supported and appropriate.

16. CREATE, ALTER, and DROP

These commands manage database structures.

CREATE TABLE

CREATE TABLE Employees (
    employee_id INT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    department VARCHAR(50),
    salary DECIMAL(10, 2)
);

This creates a table with a primary key, a required name, an optional department, and a decimal salary.

ALTER TABLE

Add a column:

ALTER TABLE Employees
ADD email VARCHAR(150);

Exact syntax for changing or removing columns differs between database systems.

DROP TABLE

DROP TABLE Employees;

DROP TABLE removes the table structure and its data. Use it with extreme care.

DELETE vs. TRUNCATE vs. DROP

Command

General purpose

DELETE

Removes selected rows or all rows

TRUNCATE

Quickly removes all rows in supported systems

DROP

Removes the database object itself

Transaction behavior, identity-counter behavior, permissions, and rollback support differ by database. Do not assume these commands are interchangeable.

17. NULL Values

NULL indicates missing, unknown, or unavailable information. It is not equivalent to zero or an empty string.

Incorrect:

SELECT *
FROM Employees
WHERE department = NULL;

Correct:

SELECT *
FROM Employees
WHERE department IS NULL;

Find records where a department has a value:

SELECT *
FROM Employees
WHERE department IS NOT NULL;

Use COALESCE() to return the first non-NULL value:

SELECT name, COALESCE(department, 'Not assigned') AS department
FROM Employees;

The comparison NULL = NULL does not evaluate to true under standard SQL's NULL logic.

18. Subqueries

A subquery is a query nested inside another SQL statement.

Find employees earning more than the overall average salary:

SELECT name, salary
FROM Employees
WHERE salary > (
    SELECT AVG(salary)
    FROM Employees
);

The inner query calculates the average salary. The outer query retrieves employees whose salary exceeds that value.

Subqueries can appear in WHERE, FROM, SELECT, and other permitted contexts.

19. Common Table Expressions (CTEs)

A CTE creates a named result set that can be referenced within a statement.

WITH DepartmentSalary AS (
    SELECT department, AVG(salary) AS average_salary
    FROM Employees
    GROUP BY department
)
SELECT department, average_salary
FROM DepartmentSalary
WHERE average_salary > 45000;

CTEs help make complex queries easier to organize and understand. Recursive CTEs can also be used for hierarchical or sequential data in supported systems.

20. CASE: Conditional Logic in SQL

CASE returns a value based on conditions.

SELECT
    name,
    salary,
    CASE
        WHEN salary >= 60000 THEN 'High'
        WHEN salary >= 45000 THEN 'Medium'
        ELSE 'Low'
    END AS salary_category
FROM Employees;

This creates a calculated salary_category column without modifying the stored records.

CASE is useful for reporting, categorization, conditional calculations, and data transformation.

21. SQL Functions for Text and Numbers

Common text functions include:

SELECT
    UPPER(name),
    LOWER(name),
    LENGTH(name)
FROM Employees;

Function names and exact syntax vary. For example, SQL Server uses LEN() for string length, while PostgreSQL and MySQL commonly use LENGTH() or related functions with database-specific behavior.

Other useful operations include:

  • TRIM(): Removes surrounding spaces.

  • CONCAT(): Combines strings in supported syntax.

  • ROUND(): Rounds numeric values.

  • ABS(): Returns an absolute value.

  • CURRENT_DATE: Retrieves the current date in systems that support this standard expression.

Always check your database's documentation for function availability, argument rules, and return types.

22. Date and Time Queries

Date and time syntax varies across database systems.

A simple filter may look like this:

SELECT *
FROM Orders
WHERE order_date >= '2026-01-01';

For date-time columns, a half-open interval is often safer than filtering on an inclusive end date:

SELECT *
FROM Orders
WHERE order_date >= '2026-01-01'
  AND order_date < '2026-02-01';

This includes January dates and times without accidentally excluding records later on January 31.

Use date types and parameterized queries appropriately, especially when applications pass dates from users.

23. SQL Constraints

Constraints help maintain data integrity.

Constraint

Purpose

PRIMARY KEY

Uniquely identifies a row

FOREIGN KEY

Enforces a relationship with a referenced key

NOT NULL

Prevents NULL values

UNIQUE

Restricts duplicate values or combinations

CHECK

Enforces a condition

DEFAULT

Supplies a default value when appropriate

Example:

CREATE TABLE Products (
    product_id INT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    price DECIMAL(10, 2) CHECK (price >= 0),
    status VARCHAR(20) DEFAULT 'Active'
);

The precise support and behavior of constraints can vary between systems.

24. Indexes and Query Performance

An index helps a database locate records more efficiently for certain queries.

CREATE INDEX idx_employee_department
ON Employees(department);

An index may improve queries that frequently filter or join using department.

However, indexes also consume storage and can add overhead to inserts, updates, and deletes.

Performance Tips

  • Select only the columns you need.

  • Filter rows using appropriate conditions.

  • Create indexes based on actual query patterns.

  • Avoid unnecessary joins.

  • Review execution plans.

  • Use appropriate data types.

  • Test queries against realistic data volumes.

  • Avoid adding indexes without considering write performance.

An index does not guarantee that every query will run faster. The database optimizer and the query's characteristics determine whether an index is useful.

25. SQL Query Execution Order

A useful conceptual order for a typical SELECT query is:

  1. FROM and JOIN

  2. WHERE

  3. GROUP BY

  4. HAVING

  5. SELECT

  6. DISTINCT

  7. ORDER BY

  8. LIMIT or the relevant database-specific row-limiting clause

This is a logical processing model, not necessarily the physical execution order chosen by the query optimizer.

Understanding it helps explain why a column alias created in SELECT may not be available in WHERE in many SQL systems.

26. SQL Transactions

Transactions group operations into a logical unit of work.

Common transaction commands include:

BEGIN;

UPDATE Accounts
SET balance = balance - 100
WHERE account_id = 1;

UPDATE Accounts
SET balance = balance + 100
WHERE account_id = 2;

COMMIT;

This illustrates transferring 100 units between two accounts. Real banking or payment systems require appropriate validation, locking or concurrency controls, error handling, and transaction management.

Common commands:

  • BEGIN: Starts a transaction in supported syntax.

  • COMMIT: Makes the transaction's changes permanent.

  • ROLLBACK: Reverses uncommitted changes when supported.

Transaction syntax and automatic-commit behavior vary across database systems and tools.

27. SQL Security Best Practices

  • Use parameterized queries when accepting user input.

  • Avoid constructing SQL statements by directly concatenating untrusted input.

  • Apply least-privilege database permissions.

  • Protect credentials and connection strings.

  • Back up important data.

  • Use transactions for related changes.

  • Review destructive commands carefully.

  • Avoid exposing sensitive information in query logs.

  • Test schema changes before applying them to production.

Parameterized queries help prevent SQL injection, a vulnerability that can occur when untrusted input is interpreted as SQL code.

28. Common SQL Mistakes

Mistake

Why it matters

Better approach

Forgetting WHERE in an update

May update every row

Verify the target rows first

Using = NULL

Does not correctly test NULL values

Use IS NULL

Confusing WHERE and HAVING

Filters at different stages

Use WHERE for rows and HAVING for groups

Joining on the wrong columns

Can produce incorrect results

Verify key relationships

Using SELECT * everywhere

Retrieves unnecessary columns

Select required columns

Ignoring duplicate rows

Can distort counts and sums

Check join relationships and use DISTINCT only when appropriate

Assuming SQL dialects are identical

Syntax and features vary

Consult the relevant database documentation

Ignoring data types

Can cause conversion errors or incorrect comparisons

Match types to the intended data

29. SQL Practice Questions

Use the Employees table introduced earlier to practice.

Beginner

  1. Retrieve every employee.

  2. Display only employee names and salaries.

  3. Find employees earning more than 50,000.

  4. Sort employees by salary from highest to lowest.

  5. Retrieve the distinct department names.

Intermediate

  1. Calculate the average salary.

  2. Count employees in each department.

  3. Find departments with an average salary above 45,000.

  4. Join employees with their department details.

  5. Find employees earning more than the company-wide average.

Advanced practice

  1. Use a CTE to calculate department-level salary statistics.

  2. Use CASE to classify salary ranges.

  3. Investigate how an index affects a frequently executed query.

  4. Use a transaction to group related updates.

  5. Compare an INNER JOIN and a LEFT JOIN using unmatched records.

Try writing each query before consulting documentation or examples.

30. SQL Quick Reference

Task

SQL pattern

Retrieve data

SELECT columns FROM table;

Filter records

WHERE condition

Sort records

ORDER BY column DESC

Remove duplicates

SELECT DISTINCT column

Limit results

LIMIT 10 in supported systems

Count records

COUNT(*)

Calculate an average

AVG(column)

Group records

GROUP BY column

Filter groups

HAVING condition

Join tables

JOIN table ON condition

Insert a record

INSERT INTO ... VALUES ...

Update records

UPDATE ... SET ... WHERE ...

Delete records

DELETE FROM ... WHERE ...

Create a table

CREATE TABLE ...

Check missing values

IS NULL

Handle alternatives

CASE WHEN ... THEN ... END

Define a CTE

WITH name AS (...)

Create an index

CREATE INDEX ...

Conclusion

SQL is an essential skill for anyone working with databases, data analytics, reporting, business intelligence, or application development.

Start by mastering SELECT, WHERE, ORDER BY, aggregate functions, and GROUP BY. Then practice joins, subqueries, CTEs, data modification, transactions, and query optimization.

Use this cheat sheet as a practical reference while building and testing queries. Remember that some syntax differs between MySQL, PostgreSQL, SQL Server, Oracle, and SQLite, so always consider which database system you are using.

#SQL#SQL Queries#Database#Database Management#SQL for Beginners

Related Posts