0% found this document useful (0 votes)
8 views15 pages

SQL Cheat Sheet

This document is a comprehensive SQL cheat sheet that covers the fundamentals of SQL, including its definition, data types, and various commands such as DDL, DML, and DQL. It explains how to create and manipulate tables, retrieve data, and use advanced features like joins, aggregate functions, and stored procedures. Additionally, it discusses concepts like transactions, triggers, and common table expressions to enhance database management and query efficiency.

Uploaded by

K. Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

SQL Cheat Sheet

This document is a comprehensive SQL cheat sheet that covers the fundamentals of SQL, including its definition, data types, and various commands such as DDL, DML, and DQL. It explains how to create and manipulate tables, retrieve data, and use advanced features like joins, aggregate functions, and stored procedures. Additionally, it discusses concepts like transactions, triggers, and common table expressions to enhance database management and query efficiency.

Uploaded by

K. Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

SQL CHEAT

SHEET
By ai_with_thiru
1. What is SQL
SQL (Structured Query Language) is a special language used to manage and work with
databases. A database is like a digital storage system that organizes and stores information
in tables. SQL helps us to:

• Create tables to store data

• Retrieve (fetch) data when needed

• Update existing data

• Delete data when it’s no longer needed

SQL is widely used in popular database systems such as MySQL, PostgreSQL, SQL
Server, and Oracle.

2. Data Types in SQL


When working with databases, we need to store different types of information, like
numbers, text, and dates. SQL provides specific data types to store and manage
different kinds of data properly.

➢ Numeric Data Types (Numbers)


These data types are used to store numbers, including whole numbers (integers)
and decimal numbers.
• INT (Integer): Stores whole numbers (numbers without decimal points).
Example: 10, 100, -5
• DECIMAL(p, s): Stores exact decimal numbers with fixed precision.
Example: 12.34 (where p is the total number of digits and s is the number
of digits after the decimal point).
• FLOAT / DOUBLE: Used for decimal numbers but with approximate
values, meaning small inaccuracies may occur in calculations. Example:
3.14159

➢ String Data Types (Text)


Used to store text, words, or characters.
• VARCHAR(n): Stores variable-length text. It only uses as much space as
needed. Example: If you store "Hello" in VARCHAR(10), it only takes 5
characters of space.
• CHAR(n): Stores fixed-length text. If you define CHAR(10), it will
always use 10 spaces, even if the word is shorter. Example: If you store
"Hi" in CHAR(5), it will store "Hi___" (with spaces).
• TEXT: Used for storing long text, like paragraphs or articles. Example:
Product descriptions, user comments.
➢ Date & Time Data Types
These are used to store dates, times, or both together.
• DATE: Stores a date in YYYY-MM-DD format. Example: 2024-02-26
(February 26, 2024).
• DATETIME: Stores both date and time in YYYY-MM-DD HH:MI:SS
format. Example: 2024-02-26 14:30:00 (February 26, 2024, at 2:30 PM).
• TIMESTAMP: Stores time as the number of seconds since January 1,
1970 (Unix timestamp). It is useful for tracking events in real-time
applications. Example: 1708953600 represents a specific date and time.
• TIME: Stores only time in HH:MI:SS format. Example: 14:30:00 (2:30
PM).

3. DDL (Data Definition Language)


DDL is a set of SQL commands used to define and manage the structure of database
objects such as tables, indexes, and schemas. These commands help create, modify, and
delete tables.

a) CREATE TABLE (Creating a Table)

The CREATE TABLE statement is used to create a new table in a database


Example:

Explanation:

• id INT PRIMARY KEY: A unique ID for each employee (Primary Key ensures
uniqueness).

• name VARCHAR(50): Stores names with a maximum of 50 characters.

• age INT: Stores the employee’s age as a whole number.

• department VARCHAR(50): Stores department names.

• salary DECIMAL(10,2): Stores salary values with two decimal places (e.g.,
50000.50).
b) ALTER TABLE (Modifying an Existing Table)

The ALTER TABLE statement is used to change an already existing table by adding,
deleting, or modifying columns.

Example:

1. Adding a new column:

This adds a join_date column to store the employee’s joining date.

2. Deleting a column:

This removes the age column from the table.

3. Modifying a column:

This changes the salary column from DECIMAL to FLOAT (useful for approximate
. values).
c) DROP TABLE (Deleting a Table)

The DROP TABLE command completely removes a table and all its data from the
database.
Example:

This will delete the employees table and all its records permanently.
4. DML (Data Manipulation Language)
DML is a set of SQL commands used to insert, update, delete, and retrieve data from
database tables.

a) INSERT INTO (Adding Data to a Table)


The INSERT INTO statement is used to add new records (rows) to a table.

Example:

Explanation:

• Adds a new employee with ID = 1, Name = John Doe, Department = HR, and
Salary = 50,000.

b) UPDATE (Modifying Existing Data)

The UPDATE statement is used to change existing values in the table.

Example:

Explanation:

• Updates John Doe’s salary to 55,000 for the employee with id = 1.

• The WHERE condition ensures that only one specific record is updated

c) DELETE (Removing Data)

The DELETE statement is used to remove specific records from the table.

Example:

Explanation:

• This removes the employee with ID = 1 from the table.

• If we don’t use the WHERE clause, it will delete all records from the table!
5. DQL (Data Query Language)
DQL commands help us retrieve and view data from the database.

a) SELECT (Fetching Data from a Table)


The SELECT statement is used to retrieve specific data from a table.

Examples:

1. Select all columns from a table:

• Fetches all columns (id, name, department, salary, etc.) for all employees.

2. Select specific columns:

• Fetches only the name and salary of all employees.

3. Select unique values (DISTINCT):

• Returns a list of unique departments (removes duplicates).

b) WHERE (Filtering Data Based on Conditions)


The WHERE clause is used to filter records based on a condition.

Examples:

1. Find employees with a salary greater than 50,000:

• Retrieves all employees earning more than 50,000.


2. Find employees from the HR department earning more than 50,000:

• Retrieves only HR employees who earn more than 50,000.

c) ORDER BY (Sorting Data in Ascending or Descending


Order)
The ORDER BY clause is used to sort the results based on a specific column.

Example:

Explanation:

• Fetches all employees, sorted by salary in descending order (highest salary first).
• To sort in ascending order, use ORDER BY salary ASC.
6. FULL OUTER JOIN
Joins are used to combine data from two or more tables based on a common column.

What is FULL OUTER JOIN?

• A FULL OUTER JOIN returns all records from both tables, even if there is no
match between them.
• If there is no matching record, NULL values are returned for missing data.

Example Query:

Explanation:

• employees table has employee names and their department_id.


• departments table has department names and their id.
• The FULL OUTER JOIN ensures that:
o Employees without a matching department still appear (with NULL for
department).
o Departments without employees still appear (with NULL for employee
name).

7. Aggregate Functions & GROUP BY


Aggregate functions perform calculations on a group of values and return a single
result.

Common Aggregate Functions:


Using HAVING with GROUP BY

• The HAVING clause filters grouped results (like WHERE, but for grouped data).

Example 3: Find departments where total salary is more than 100,000

• This filters only departments where the total salary exceeds 100,000.

8. Subqueries
A subquery is a query inside another query. It helps break down complex queries into
smaller, easier parts.

Example: Find employees earning more than the average salary

Explanation:

• The inner query (SELECT AVG(salary) FROM employees) calculates the average
salary.
• The outer query retrieves employees earning more than this average.

9. Indexes
Indexes help speed up searches by allowing the database to find records faster, just like
a table of contents in a book.

Creating an Index
How it Helps?

• When you search for employees with a specific salary (WHERE salary = 60000), the
database quickly finds the matching records instead of scanning the whole table.

Removing an Index

10. Views
A view is like a virtual table based on a query. It doesn’t store data but allows you to
use saved queries as if they were tables.

Creating a View

Using the View

• This retrieves all employees earning more than 60,000, without needing to rewrite the
query every time.

Deleting a View
11. Stored Procedures
A stored procedure is a set of SQL commands saved in the database, which can be
executed anytime.

Creating a Stored Procedure

Running (Calling) the Procedure

12. Transactions
A transaction ensures that multiple SQL commands either complete together or fail
together.

Why Use Transactions?


Imagine transferring money between accounts:

1. Subtract money from one account.

2. Add money to another account.


If one step fails, the database must not save changes!

Example of a Transaction
Key Commands:

• START TRANSACTION; → Begins a transaction.

• COMMIT; → Saves all changes.

• ROLLBACK; → Undoes all changes (if something goes wrong).


Example with ROLLBACK (Undo Changes)

13. Triggers
A Trigger is a special SQL command that automatically runs when a certain event
happens in a database, such as INSERT, UPDATE, or DELETE.
Why Use Triggers?

• Ensures automatic actions when data changes.


• Maintains data integrity (e.g., setting minimum salaries).
• Logs or audits changes in a table.

Example: Preventing Low Salaries with a Trigger

Explanation:

• This trigger runs before a new row is inserted into the employees table.

• If the salary is less than 30,000, it automatically sets it to 30,000.

• This ensures no employee gets a salary below 30,000.


Deleting a Trigger

• This removes the trigger if it's no longer needed.

Types of Triggers in SQL

14. Common Table Expressions (CTEs)


A Common Table Expression (CTE) is a temporary, named result set that makes
queries easier to read and reuse.

Why Use CTEs?

• Makes queries clearer and more organized.


• Allows reuse of temporary results within the same query.
• Improves performance by breaking large queries into smaller parts.
Example: Using a CTE to Calculate Average Salary by Department
Explanation:

• The WITH statement creates a temporary table (CTE) called DepartmentSalary.

• This CTE calculates the average salary for each department.

• The final SELECT retrieves data from the CTE instead of rewriting the whole query.

Using CTEs in Complex Queries

CTEs can also be used in JOINs and filters for more advanced queries.

Example: Find Employees Earning Above Their Department's Average

What This Does:

1. The CTE (DepartmentSalary) calculates the average salary per department.

2. The main query finds employees who earn more than their department’s average.

Key Differences: CTEs vs. Subqueries vs. Views

You might also like