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

SQL Cheat Sheet for Beginners

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)
34 views15 pages

SQL Cheat Sheet for Beginners

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

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 [Link] (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: [Link] (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

Common questions

Powered by AI

COMMIT and ROLLBACK play critical roles in maintaining data integrity within transactions. COMMIT saves all changes made during the transaction, ensuring they are permanently applied to the database. Conversely, ROLLBACK undoes all changes if an error occurs, restoring the database to its previous stable state. This ensures either complete execution of all operations within a transaction or none, thereby maintaining atomicity and consistency .

A FULL OUTER JOIN is appropriate when needing to retrieve all records from two tables regardless of matches. This is useful when both complete sets of data are required for analysis, including unmatched rows which are filled with NULLs for missing data from either table. This approach is beneficial in comprehensive reports or when integrating disparate datasets where understanding both present and absent relationships is necessary .

Views simplify data management by allowing the use of saved queries as virtual tables, enabling complex query abstraction and simplification. They provide a layer of security by encapsulating the logic of the query and restricting direct access to the base tables. However, a major limitation is that views do not store physical data, impacting performance for frequently accessed or complex views, as each access requires re-execution of the underlying query logic .

CTEs improve query clarity and organization by allowing queries to be broken down into modular, named result sets that are defined separately from the main query logic. Unlike subqueries, CTEs can be referenced multiple times within the same query, enhancing readability and maintainability. They also facilitate recursive queries, making them more powerful in certain contexts compared to subqueries, which are less flexible for similar tasks .

CHAR is used for storing fixed-length text, meaning it always reserves a set amount of spaces (e.g., CHAR(10) always uses 10 spaces). VARCHAR, on the other hand, is for variable-length text and uses only as much space as needed (e.g., VARCHAR(10) storing 'Hello' uses 5 spaces). These characteristics affect storage efficiency and data retrieval performance .

The GROUP BY clause, combined with aggregate functions like SUM, AVG, COUNT, etc., is used to organize data into subsets, upon which calculations can be performed to generate insights. For example, grouping data by department and using aggregate functions can summarize payroll costs or headcounts per department. The HAVING clause can further refine these insights by filtering groups based on aggregate criteria, such as filtering departments where total salary exceeds a threshold .

The ALTER TABLE statement provides flexibility by allowing changes to an existing table's structure, such as adding, deleting, or modifying columns. This adaptability helps manage evolving data needs without requiring a complete redesign of tables. For instance, adding a 'join_date' column, removing an 'age' column, or changing the 'salary' column type enhances schema adaptability and efficient data management .

A stored procedure allows the encapsulation of SQL commands to be reused, which is beneficial for code reusability, reduced development time, and improved security. Stored procedures are precompiled, which can enhance execution performance compared to ad-hoc queries. They also allow for encapsulating business logic within the database, rather than application code, facilitating maintenance and consistency across different parts of an application .

SQL is primarily used for managing and working with databases by creating tables, retrieving data, updating existing data, and deleting data. It is widely used in popular database systems such as MySQL, PostgreSQL, SQL Server, and Oracle .

A database administrator might choose to remove an index if it is rarely used and its maintenance overhead outweighs its performance benefits. Indexes can slow down data input operations like INSERT, UPDATE, and DELETE because they require additional updates for each data modification. Removing unused or inefficient indexes can improve overall database performance by reducing input operation costs and conserving system resources .

You might also like