0% found this document useful (0 votes)
3 views

SQL Notes

This document provides comprehensive notes on SQL, covering fundamental concepts such as data, databases, and DBMS, along with SQL commands, data types, and constraints. It explains various SQL operations, including joins, aggregation functions, and window functions, while also discussing advantages and disadvantages of DBMS. Additionally, it highlights the importance of SQL constraints for data integrity and includes examples of SQL syntax for practical understanding.

Uploaded by

ayushmaurya54321
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)
3 views

SQL Notes

This document provides comprehensive notes on SQL, covering fundamental concepts such as data, databases, and DBMS, along with SQL commands, data types, and constraints. It explains various SQL operations, including joins, aggregation functions, and window functions, while also discussing advantages and disadvantages of DBMS. Additionally, it highlights the importance of SQL constraints for data integrity and includes examples of SQL syntax for practical understanding.

Uploaded by

ayushmaurya54321
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/ 66

SQL NOTES

By - Gaurav Narwal Sir


SQL Notes

What is Data?

Data refers to raw facts, figures, or information that can be processed or analyzed to derive
meaningful insights.

What is a Database?

A database is an organized collection of data that allows efficient storage, retrieval, and
management.

What is DBMS (Database Management System)?

A DBMS is software that manages and controls databases, ensuring data integrity, security,
and efficient processing. Examples include MySQL, PostgreSQL, and Oracle.

DBMS Operations:

1. Data Storage
2. Data Retrieval
3. Data Modification
4. Data Security
5. Backup & Recovery

Advantages & Disadvantages of DBMS

Advantages:

• Data Consistency and Integrity


• Efficient Data Management
• Multi-User Access
• Data Security
• Backup and Recovery

Disadvantages:

• Complex Implementation
• Expensive Hardware & Software
• Requires Skilled Personnel
• Performance Issues with Large Databases
What is RDBMS?

An RDBMS stores data in tabular form with relationships between tables. Examples:
MySQL, SQL Server, PostgreSQL.

What is SQL?

SQL (Structured Query Language) is a standard language for interacting with RDBMS
databases.

SQL Data Types

1. Numeric: INT, FLOAT, DECIMAL


2. Character: CHAR, VARCHAR, TEXT
3. Date/Time: DATE, TIME, DATETIME
4. Boolean: BOOLEAN

Difference Between CHAR and VARCHAR

• CHAR: Fixed-length string (e.g., CHAR(10) always stores 10 characters, padding if


necessary).
• VARCHAR: Variable-length string (e.g., VARCHAR(10) stores only required
characters up to 10).
SQL Command Groups

SQL commands are categorized into five major groups:

1. Data Definition Language (DDL)

• CREATE - Creates a new database or table.


Syntax:

• ALTER - Modifies an existing table.


Syntax:

• DROP - Deletes a table.


Syntax:

• TRUNCATE - Removes all records but keeps structure.


Syntax:

• RENAME - Renames a table.


Syntax:
2. Data Manipulation Language (DML)

• INSERT - Adds new records.


Syntax:

• UPDATE - Modifies existing records.


Syntax:

• DELETE - Removes records.


Syntax:

3. Data Query Language (DQL)

• SELECT - Fetches data from a database.


Syntax:

4. Data Control Language (DCL)

• GRANT - Provides privileges.


Syntax:

• REVOKE - Removes privileges.


Syntax:
5. Transaction Control Language (TCL)

• COMMIT - Saves changes.


Syntax:

• ROLLBACK - Reverts changes.


Syntax:

• SAVEPOINT - Sets a checkpoint in a transaction.


Syntax:

WHERE Clause

The WHERE clause is used to filter records based on specific conditions.

Syntax:

SQL Operators
SQL provides various operators to use with the WHERE clause.

1. Comparison Operators
o = (Equal to)
o != or <> (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
2. Logical Operators
o AND (Both conditions must be true)
o OR (Either condition can be true)
o NOT (Negates a condition)
3. Special Operators
o BETWEEN (Range condition)
o LIKE (Pattern matching)
o IS NULL (Checks if value is NULL)
o IN (Matches values in a list)
o DISTINCT (Removes duplicate values)
Special Operators

BETWEEN

Used to filter values within a specific range.

Syntax:

LIKE Operator

Used for pattern matching in string values.

Syntax:

IS NULL

Checks if a column contains NULL values.

Syntax:
IN

Checks if a value exists in a list.

Syntax:

DISTINCT

Returns unique values.

Syntax:
Aggregation Functions

Aggregation functions perform calculations on multiple rows and return a single value.

1. COUNT() - Counts records


2. SUM() - Adds values
3. AVG() - Finds average
4. MIN() - Finds minimum
5. MAX() - Finds maximum

Usage with SELECT:

GROUP BY Clause - The GROUP BY clause groups rows with the same values in specified
columns and applies aggregation functions.
HAVING Clause

Used to filter aggregated results (similar to WHERE, but for grouped data).

Filters groups after aggregation.

Syntax:

Difference Between HAVING and WHERE


What are SQL Constraints?

SQL constraints are rules applied to table columns to enforce data integrity and ensure the
accuracy and reliability of data. Constraints prevent invalid data entry and maintain database
consistency.

Types of SQL Constraints

SQL provides the following constraints:

1. NOT NULL – Ensures a column cannot have NULL values.


2. UNIQUE – Ensures all values in a column are unique.
3. PRIMARY KEY – Uniquely identifies each record in a table.
4. FOREIGN KEY – Enforces referential integrity between tables.
5. CHECK – Ensures that column values meet a specific condition.
6. DEFAULT – Provides a default value when no value is specified.
7. AUTO_INCREMENT – Automatically generates unique values for a column.
8. COMPOSITE KEY – A primary key consisting of multiple columns.
9. INDEX – Improves query performance (not a constraint but used for optimization).

1. NOT NULL Constraint

The NOT NULL constraint ensures that a column cannot store NULL values.

Syntax (During Table Creation):

Syntax (Adding NOT NULL to an Existing Column):

2. UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are distinct (no duplicate values).

Syntax (During Table Creation):


Syntax (Adding UNIQUE to an Existing Column):

OR

3. PRIMARY KEY Constraint

The PRIMARY KEY uniquely identifies each record in a table. It combines the NOT
NULL and UNIQUE constraints.

Syntax (Single Column Primary Key):

Syntax (Multiple Columns as Primary Key - Composite Key):

Syntax (Adding a PRIMARY KEY to an Existing Table):


4. FOREIGN KEY Constraint

The FOREIGN KEY constraint ensures that values in a column match values in the
referenced table. It maintains referential integrity between tables.

Syntax (Defining a Foreign Key During Table Creation):

Syntax (Adding a FOREIGN KEY to an Existing Table):

Syntax (Dropping a FOREIGN KEY Constraint):

5. CHECK Constraint

The CHECK constraint ensures that values meet a specified condition.

Syntax (During Table Creation):

Syntax (Adding a CHECK Constraint to an Existing Table):

Syntax (Dropping a CHECK Constraint):


6. DEFAULT Constraint

The DEFAULT constraint assigns a default value to a column when no value is provided.

Syntax (During Table Creation):

Syntax (Adding a DEFAULT Constraint to an Existing Column):

Syntax (Removing a DEFAULT Constraint):

7. AUTO_INCREMENT Constraint

The AUTO_INCREMENT constraint automatically generates unique values for a column


(usually for primary keys).

Syntax (Creating an Auto-Increment Column):

Syntax (Adding AUTO_INCREMENT to an Existing Column):


8. COMPOSITE KEY Constraint

A Composite Key is a primary key that consists of multiple columns to uniquely identify
each record.

Syntax (Defining a Composite Key):

Syntax (Adding a Composite Key to an Existing Table):

9. INDEX (For Optimization - Not a Constraint)

An INDEX is used to improve query performance. It does not enforce data integrity but helps
in faster retrieval of records.

Syntax (Creating an Index):

Syntax (Creating a Unique Index):

Syntax (Dropping an Index):


Summary of Constraints
ORDER BY, UNION, and UNION ALL in SQL

ORDER BY Clause

The ORDER BY clause is used to sort the result set in either ascending (ASC) or descending (DESC)
order. By default, it sorts the results in ascending order.

Syntax:

Example 1: Sorting in Ascending Order (Default)

This query sorts the student records by age in ascending order (smallest to largest).

Example 2: Sorting in Descending Order

This query sorts the student records by age in descending order (largest to smallest).

Example 3: Sorting by Multiple Columns

First, it sorts by age in ascending order. If multiple students have the same age, it sorts by
marks in descending order.
UNION and UNION ALL in SQL

The UNION and UNION ALL operators are used to combine the results of multiple SELECT queries.

Key Points to Remember:

1. Both SELECT statements must have the same number of columns.


2. The columns must have the same data types.
3. The order of columns must be the same in both queries.

1. UNION (Removes Duplicates)

The UNION operator merges results from two queries and removes duplicates.

Syntax:

Example:

Tables:

students_2023
students_2024

Query Using UNION

Result:

Duplicates (Charlie, ID 3) were removed.

2. UNION ALL (Keeps Duplicates)

The UNION ALL operator merges results from two queries and keeps duplicates.

Syntax:

Example:

Query Using UNION ALL


Result:

Duplicates (Charlie, ID 3) were not removed.

Conclusion

MySQL Joins - Comprehensive Guide


Joins in MySQL are used to combine data from multiple tables based on related columns. There are
different types of joins, each serving a specific purpose.

Types of MySQL Joins

1. INNER JOIN – Returns matching records from both tables.


2. LEFT JOIN (LEFT OUTER JOIN) – Returns all records from the left table and matching records
from the right table.
3. RIGHT JOIN (RIGHT OUTER JOIN) – Returns all records from the right table and matching
records from the left table.
4. FULL JOIN (FULL OUTER JOIN) – Returns all records when there is a match in either table
(MySQL doesn’t support FULL JOIN directly).
5. CROSS JOIN – Returns the Cartesian product (combination) of both tables.
6. SELF JOIN – A table joins itself.
1. INNER JOIN

Returns records that have matching values in both tables.

Syntax:

Example:

Tables:

employees

departments
Query:

Result:

Charlie is excluded because his dept_id does not match.

2. LEFT JOIN (LEFT OUTER JOIN)

Returns all records from the left table and matching records from the right table. If there is no
match, NULL is returned.

Syntax:

Example:
Result:

Charlie is included with NULL because no matching dept_id was found.

3. RIGHT JOIN (RIGHT OUTER JOIN)

Returns all records from the right table and matching records from the left table. If there is no
match, NULL is returned.

Syntax:

Example:
Result:

Sales department is included even though no employee belongs to it.

4. FULL JOIN (FULL OUTER JOIN) - Alternative in MySQL

Returns all records from both tables, with NULLs where there is no match.
MySQL does not support FULL JOIN directly, but we can use UNION of LEFT JOIN and RIGHT
JOIN.

Syntax (Workaround for MySQL)


5. CROSS JOIN

Returns the Cartesian product of both tables (every row from table1 is paired with every row
from table2).

Syntax:

Example:

Result (All possible combinations):

Each employee is paired with every department.


6. SELF JOIN

A table joins itself. Useful for hierarchical data like employees and managers.

Syntax:

Example:

Result:

This query finds each employee’s manager from the same table.
Summary of MySQL Joins

Conclusion

• Use INNER JOIN for matching data.


• Use LEFT JOIN when you want all records from the first table.
• Use RIGHT JOIN when you want all records from the second table.
• Use FULL JOIN (via UNION) when you need all data from both tables.
• Use CROSS JOIN when you need combinations of all rows.
• Use SELF JOIN for hierarchical relationships.
CASE Expression

The CASE expression in MySQL is used to implement conditional logic within SQL queries. It works
like an IF-ELSE statement in programming.

Types of CASE Expressions

1. Simple CASE (Matches a specific value)


2. Searched CASE (Uses conditions instead of matching a specific value)

Simple CASE Expression

Compares an expression to a set of values and returns a result.

Syntax:

Example:

Result:
Searched CASE Expression

Uses conditions rather than matching values.

Syntax:

Example:

Result:

Common Table Expressions (CTE)


CTE (Common Table Expression) is a temporary result set that improves query readability and
reusability.

Why Use CTE?

Improves readability
Can be referenced multiple times in a query
Useful for recursive queries
CTE Syntax

Example 1: Using CTE to Get High-Salary Employees

Result:

Example 2: Recursive CTE (Hierarchical Data)

Recursive CTEs are useful for hierarchical data like employee-manager relationships.

Syntax:
Example: Employee Hierarchy

Result:

Alice is the top manager, Bob reports to Alice, and Charlie reports to Bob.

Summary
Window Functions in MySQL 🚀
Window functions allow performing calculations across a specific range of rows without collapsing
them into a single result (unlike aggregate functions).

Syntax

✅Types of Window Functions

Ranking Functions

1. ROW_NUMBER()
2. RANK()
3. DENSE_RANK()
4. PERCENT_RANK()
5. NTILE(n)

Aggregate Functions as Window Functions

1. SUM()
2. AVG()
3. COUNT()
4. MAX()
5. MIN()

Value Functions

1. LEAD()
2. LAG()
3. FIRST_VALUE()
4. LAST_VALUE()
✅ Ranking Functions

(a) ROW_NUMBER()

Assigns a unique number to each row within a partition based on the specified ORDER BY.

Example

Result

(b) RANK()

Assigns a rank to each row, but skips numbers when there are ties.

Example

Result

Alice and Charlie have the same salary, so they both get Rank 1. The next rank is 3 (skipping 2).
(c) DENSE_RANK()

Similar to RANK(), but does not skip numbers for ties.

Example

Result

Here, the next rank after (1,1) is 2, not 3.

(d) PERCENT_RANK()

Calculates the relative rank of a row as a percentage of the total rows. The formula is:

Example :-

Result :-

Alice and Charlie have the same salary, so they share the lowest rank (0.00). Dave has the
highest percentage rank (1.00).
(e) NTILE(n)

Divides the result set into n equal parts.

Example

Result

Splits the result into 2 groups (NTILE(2)).

✅ Aggregate Functions as Window Functions

(a) SUM()

Calculates running total.

(b) AVG()

Finds the average salary of a department.


✅ Value Functions

(a) LEAD()

Gets the next row's value.

(b) LAG()

Gets the previous row's value.

(c) First Value()

• Returns the first value in an ordered partition of a result set.


• Uses OVER() with ORDER BY to determine the first row.

Syntax

Example

Scenario: Retrieve the highest salary (first in order) for each department.

Sample Data
Result

Explanation:

• PARTITION BY department ensures employees are grouped by department.


• ORDER BY salary DESC ensures the highest salary appears first.
• FIRST_VALUE(name) returns the name of the highest-paid employee in each department.

(d) Last Value()

• Returns the last value in an ordered partition.


• Requires ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to
avoid unexpected results.

Syntax

Example

Scenario: Retrieve the lowest salary (last in order) for each department.

Result
Explanation:

• ORDER BY salary DESC orders employees from highest to lowest salary.


• LAST_VALUE(name) retrieves the last employee in the ordered partition (the lowest-paid
employee).
• ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ensures the
function evaluates all rows in the partition.

Difference Between Window and Aggregate Functions

7. Summary

• Window functions process a subset of rows in a table without collapsing them.


• Used for ranking, running totals, and previous/next value retrieval.
• PARTITION BY groups data before applying the function.
• ORDER BY defines row processing order.
➢ Understanding Window Function Row Specifications in SQL

Window functions in SQL allow you to perform calculations across a set of rows related to the
current row within a partition. The ROWS BETWEEN clause helps define which rows to consider for
the calculation.

1. What Does "UNBOUNDED" Mean?

• UNBOUNDED PRECEDING → The window starts from the first row of the partition.
• UNBOUNDED FOLLOWING → The window extends to the last row of the partition.

Effect → The function considers all rows within the partition.

2. Meaning of "CURRENT ROW"

• CURRENT ROW refers to the row currently being processed.


• In ordered window functions, the current row is determined by the ORDER BY clause.
• It includes all rows that share the same ordering value.

Example:

This creates a cumulative sum from the first row to the current row.

3. Cumulative Sum

A cumulative sum (running total) is the sum of values from the first row up to the current row.

Example Query (Cumulative Salary)

Sample Data
Result

Explanation

• For each row, the sum accumulates from the first row to the current row.

4. ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING

• Defines a moving window centered around the current row.


• It includes 2 rows before and 2 rows after the current row.

Example Query (Average Salary in Moving Window)

Sample Data

Result
Explanation

• The AVG(salary) function considers 2 previous rows, the current row, and 2 next rows.

Explanation of Window Function


• SUM(Sales) OVER (...) → This calculates a rolling sum of sales.
• ORDER BY TD → Ensures calculations are done sequentially by TD.
• ROWS BETWEEN 4 PRECEDING AND CURRENT ROW → Takes the current row and the
previous 4 rows into account.
Definitions of ROWS BETWEEN Options
1. ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
o This means the window includes all rows in the dataset.
o Example: SUM(Sales) OVER (ORDER BY TD ROWS BETWEEN UNBOUNDED
PRECEDING AND UNBOUNDED FOLLOWING)
o Effect: Computes the total sum across all rows.
2. ROWS BETWEEN CURRENT ROW AND CURRENT ROW
o The window function applies only to the current row.
o Example: SUM(Sales) OVER (ORDER BY TD ROWS BETWEEN CURRENT ROW AND
CURRENT ROW)
o Effect: Returns the value of the current row.
3. ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
o This includes the previous row, the current row, and the next row.
o Example: SUM(Sales) OVER (ORDER BY TD ROWS BETWEEN 1 PRECEDING AND 1
FOLLOWING)
o Effect: Computes a rolling sum of three rows at a time.
4. Cumulative Sum (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
o This creates a running total from the first row to the current row.
o Example: SUM(Sales) OVER (ORDER BY TD ROWS BETWEEN UNBOUNDED
PRECEDING AND CURRENT ROW)
o Effect: Computes the cumulative sum of sales.
5. Summary Table

NTILE() – Dividing Data into Equal Groups

The NTILE(n) function is a window function that distributes rows into n number of approximately
equal groups. This is useful when dividing data into percentiles, quartiles, or rankings.

Example: Divide Employees into 4 Equal Salary Groups

Explanation:

• The NTILE(4) function creates 4 groups based on salary ranking.


• The highest salaries get group 1, and the lowest salaries get group 4.
GROUP_CONCAT() and STRING_AGG() – String Aggregation

Both GROUP_CONCAT() (MySQL) and STRING_AGG() (PostgreSQL, SQL Server) concatenate


multiple column values into a single string within a group.

Example: List of Employee Names by Department

LIMIT & OFFSET – Pagination in SQL

The LIMIT and OFFSET clauses are used to control the number of rows returned and skip rows
when fetching results.

Example: Get Top 3 Highest Salaries

Example: Get Next 3 Salaries After Skipping Top 3

Explanation:

• LIMIT 3 returns only the top 3 rows.


• OFFSET 3 skips the first 3 rows and returns the next 3 rows.
Order of Execution in SQL Queries

SQL executes queries in the following order, which is different from how we write them:

Example Query

Explanation:

• FROM employees – Selects the table.


• WHERE salary > 5000 – Filters salaries greater than 5000.
• GROUP BY department – Groups by department.
• HAVING avg_salary > 6000 – Filters departments with avg salary above 6000.
• ORDER BY avg_salary DESC – Sorts highest salaries first.
• LIMIT 5 – Returns only 5 results.

NATURAL JOIN – Automatically Joining on Common Columns

A NATURAL JOIN automatically joins tables based on columns with the same name.

Example: Auto-Join Employees and Departments


Explanation:

• If both tables have a department_id column, NATURAL JOIN automatically joins on that
column.
• No need to write ON employees.department_id = departments.department_id.

Subqueries – Queries Inside Queries

A subquery is a query inside another query. It's used to fetch data dynamically.

Example: Get Employees with Salary Higher than the Company’s Average

Explanation:

• The subquery (SELECT AVG(salary) FROM employees) calculates the average salary.
• The outer query selects employees who earn more than the average salary.

Numeric Functions in SQL


String Functions in SQL
Date Functions in SQL
Views – Virtual Tables in SQL

A View is a stored SQL query that acts as a virtual table.

Example: Create a View for Active Employees

Using the View

Views help simplify queries and improve security!


Stored Procedures – Reusable SQL Functions

A Stored Procedure is a saved SQL function that can be executed multiple times.

Example: Procedure to Get Employees by Department

Execute Procedure

Stored Procedures improve performance and modularity!


Practice Data
--Practice Database
create database practice_table;

use practice_table;

--Employees Table
CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

EmployeeName VARCHAR(100),

DepartmentID INT,

HireDate DATE

);

--Employees Table Data


INSERT INTO Employees (EmployeeID, EmployeeName, DepartmentID, HireDate)

VALUES

(1, 'John Doe', 1, '2022-01-10'),

(2, 'Jane Smith', 2, '2023-02-15'),

(3, 'Samuel Green', 1, '2021-11-20'),

(4, 'Emily White', 3, '2024-03-05'),

(5, 'Michael Brown', 2, '2020-08-25');

--Department Table
CREATE TABLE Departments (

DepartmentID INT PRIMARY KEY,

DepartmentName VARCHAR(100)

);

--Department Table Data


INSERT INTO Departments (DepartmentID, DepartmentName)

VALUES
(1, 'Sales'),

(2, 'Customer Service'),

(3, 'Logistics');

--Orders Table
CREATE TABLE orders (

order_id INT NOT NULL,

order_date DATE,

customer_id INT NOT NULL,

total_amount DECIMAL(10, 2),

status VARCHAR(50),

shipping_address VARCHAR(255),

PRIMARY KEY (order_id)

);

--Orders Table Data


INSERT INTO orders (order_id, order_date, customer_id, total_amount, status, shipping_address)

VALUES

(1, '2024-08-01', 1, 100.00, 'Pending', '123 Main St, New York'),

(2, '2024-08-02', 2, 150.00, 'Shipped', '456 Elm St, Los Angeles'),

(3, '2024-08-03', 3, 200.00, 'Delivered', '789 Oak St, Chicago'),

(4, '2024-08-04', 4, 175.50, 'Pending', '101 Maple St, Houston'),

(5, '2024-08-05', 5, 120.75, 'Shipped', '202 Birch St, Phoenix'),

(6, '2024-08-06', 6, 250.00, 'Delivered', '303 Cedar St, Philadelphia'),

(7, '2024-08-07', 7, 300.25, 'Pending', '404 Walnut St, San Antonio'),

(8, '2024-08-08', 8, 85.50, 'Shipped', '505 Chestnut St, San Diego'),

(9, '2024-08-09', 9, 199.99, 'Delivered', '606 Pine St, Dallas'),

(10, '2024-08-10', 10, 225.00, 'Pending', '707 Spruce St, San Jose'),

(11, '2024-08-11', 11, 110.00, 'Shipped', '808 Fir St, Austin'),

(12, '2024-08-12', 12, 99.99, 'Delivered', '909 Redwood St, Jacksonville'),

(13, '2024-08-13', 13, 149.49, 'Pending', '1010 Oak St, Fort Worth'),
(14, '2024-08-14', 14, 135.00, 'Shipped', '1111 Maple St, Columbus'),

(15, '2024-08-15', 15, 220.00, 'Delivered', '1212 Birch St, Charlotte'),

(16, '2024-08-16', 16, 180.75, 'Pending', '1313 Cedar St, San Francisco'),

(17, '2024-08-17', 17, 210.00, 'Shipped', '1414 Walnut St, Indianapolis'),

(18, '2024-08-18', 18, 130.25, 'Delivered', '1515 Chestnut St, Seattle'),

(19, '2024-08-19', 19, 95.99, 'Pending', '1616 Pine St, Denver'),

(20, '2024-08-20', 20, 175.00, 'Shipped', '1717 Spruce St, Washington'),

(21, '2024-08-21', 21, 140.50, 'Delivered', '1818 Fir St, Boston'),

(22, '2024-08-22', 22, 160.00, 'Pending', '1919 Redwood St, El Paso'),

(23, '2024-08-23', 23, 115.75, 'Shipped', '2020 Oak St, Nashville'),

(24, '2024-08-24', 24, 199.99, 'Delivered', '2121 Maple St, Detroit'),

(25, '2024-08-25', 25, 180.00, 'Pending', '2222 Birch St, Oklahoma City');

--Customers Table
CREATE TABLE customers (

customer_id INT NOT NULL,

name VARCHAR(100),

email VARCHAR(100),

phone_number VARCHAR(15),

address VARCHAR(255),

city VARCHAR(100),

created_at DATE,

PRIMARY KEY (customer_id)

);
--Customer Table Data
INSERT INTO customers (customer_id, name, email, phone_number, address, city, created_at)

VALUES

(1, 'Customer 1', '[email protected]', '123-456-7890', '123 Main St', 'New York', '2024-01-
01'),

(2, 'Customer 2', '[email protected]', '234-567-8901', '456 Elm St', 'Los Angeles', '2024-01-
02'),

(3, 'Customer 3', '[email protected]', '345-678-9012', '789 Oak St', 'Chicago', '2024-01-03'),

(4, 'Customer 4', '[email protected]', '456-789-0123', '101 Maple St', 'Houston', '2024-01-
04'),

(5, 'Customer 5', '[email protected]', '567-890-1234', '202 Birch St', 'Phoenix', '2024-01-05'),

(6, 'Customer 6', '[email protected]', '678-901-2345', '303 Cedar St', 'Philadelphia', '2024-01-
06'),

(7, 'Customer 7', '[email protected]', '789-012-3456', '404 Walnut St', 'San Antonio', '2024-
01-07'),

(8, 'Customer 8', '[email protected]', '890-123-4567', '505 Chestnut St', 'San Diego', '2024-
01-08'),

(9, 'Customer 9', '[email protected]', '901-234-5678', '606 Pine St', 'Dallas', '2024-01-09'),

(10, 'Customer 10', '[email protected]', '012-345-6789', '707 Spruce St', 'San Jose', '2024-
01-10'),

(11, 'Customer 11', '[email protected]', '123-456-7890', '808 Fir St', 'Austin', '2024-01-11'),

(12, 'Customer 12', '[email protected]', '234-567-8901', '909 Redwood St', 'Jacksonville',


'2024-01-12'),

(13, 'Customer 13', '[email protected]', '345-678-9012', '1010 Oak St', 'Fort Worth', '2024-
01-13'),

(14, 'Customer 14', '[email protected]', '456-789-0123', '1111 Maple St', 'Columbus', '2024-
01-14'),

(15, 'Customer 15', '[email protected]', '567-890-1234', '1212 Birch St', 'Charlotte', '2024-
01-15'),

(16, 'Customer 16', '[email protected]', '678-901-2345', '1313 Cedar St', 'San Francisco',
'2024-01-16'),

(17, 'Customer 17', '[email protected]', '789-012-3456', '1414 Walnut St', 'Indianapolis',


'2024-01-17'),

(18, 'Customer 18', '[email protected]', '890-123-4567', '1515 Chestnut St', 'Seattle', '2024-
01-18'),
(19, 'Customer 19', '[email protected]', '901-234-5678', '1616 Pine St', 'Denver', '2024-01-
19'),

(20, 'Customer 20', '[email protected]', '012-345-6789', '1717 Spruce St', 'Washington',


'2024-01-20'),

(21, 'Customer 21', '[email protected]', '123-456-7890', '1818 Fir St', 'Boston', '2024-01-
21'),

(22, 'Customer 22', '[email protected]', '234-567-8901', '1919 Redwood St', 'El Paso', '2024-
01-22'),

(23, 'Customer 23', '[email protected]', '345-678-9012', '2020 Oak St', 'Nashville', '2024-01-
23'),

(24, 'Customer 24', '[email protected]', '456-789-0123', '2121 Maple St', 'Detroit', '2024-
01-24'),

(25, 'Customer 25', '[email protected]', '567-890-1234', '2222 Birch St', 'Oklahoma City',
'2024-01-25'),

(26, 'Customer 26', '[email protected]', '678-901-2345', '2323 Cedar St', 'Portland', '2024-
01-26'),

(27, 'Customer 27', '[email protected]', '789-012-3456', '2424 Walnut St', 'Las Vegas',
'2024-01-27'),

(28, 'Customer 28', '[email protected]', '890-123-4567', '2525 Chestnut St', 'Memphis',


'2024-01-28'),

(29, 'Customer 29', '[email protected]', '901-234-5678', '2626 Pine St', 'Louisville', '2024-
01-29'),

(30, 'Customer 30', '[email protected]', '012-345-6789', '2727 Spruce St', 'Baltimore',


'2024-01-30');

--Cinema Table
Create table If Not Exists cinema (id int, movie varchar(255), description varchar(255), rating float(2,
1));

--Cinema Table Data


insert into cinema (id, movie, description, rating) values ('1', 'War', 'great 3D', '8.9');

insert into cinema (id, movie, description, rating) values ('2', 'Science', 'fiction', '8.5');

insert into cinema (id, movie, description, rating) values ('3', 'irish', 'boring', '6.2');

insert into cinema (id, movie, description, rating) values ('4', 'Ice song', 'Fantacy', '8.6');

insert into cinema (id, movie, description, rating) values ('5', 'House card', 'Interesting', '9.1');
--Sales_data Table
CREATE TABLE sales_data (

customer_id INT,

product_id INT,

quantity INT,

sale_date DATE,

sale_amount DECIMAL(10, 2)

);

--Sales_data Table Data


INSERT INTO sales_data (customer_id, product_id, quantity, sale_date, sale_amount)

VALUES

(1, 101, 2, '2024-01-01', 50.00),

(2, 102, 1, '2024-01-02', 100.00),

(1, 101, 3, '2024-01-03', 75.00),

(3, 103, 5, '2024-01-04', 200.00),

(2, 104, 2, '2024-01-05', 150.00),

(1, 105, 1, '2024-01-06', 60.00),

(3, 103, 2, '2024-01-07', 80.00),

(2, 102, 3, '2024-01-08', 120.00),

(4, 106, 4, '2024-02-01', 300.00),

(5, 107, 2, '2024-02-02', 50.00),

(4, 108, 1, '2024-02-03', 100.00),

(5, 109, 3, '2024-02-04', 75.00),

(6, 110, 5, '2024-02-05', 200.00),

(7, 111, 2, '2024-02-06', 150.00),

(8, 112, 1, '2024-02-07', 60.00),

(9, 113, 2, '2024-02-08', 80.00),

(4, 106, 3, '2024-03-01', 120.00),

(5, 107, 2, '2024-03-02', 50.00),

(6, 108, 1, '2024-03-03', 100.00),


(7, 109, 4, '2024-03-04', 300.00),

(8, 110, 3, '2024-03-05', 75.00),

(9, 111, 5, '2024-03-06', 200.00),

(4, 112, 2, '2024-03-07', 150.00),

(5, 113, 1, '2024-03-08', 60.00),

(6, 101, 2, '2024-04-01', 80.00),

(7, 102, 3, '2024-04-02', 120.00),

(8, 103, 1, '2024-04-03', 50.00),

(9, 104, 2, '2024-04-04', 100.00),

(1, 105, 3, '2024-04-05', 75.00),

(2, 106, 5, '2024-04-06', 200.00),

(3, 107, 2, '2024-04-07', 150.00),

(4, 108, 1, '2024-04-08', 60.00),

(5, 109, 2, '2024-05-01', 80.00),

(6, 110, 3, '2024-05-02', 120.00),

(7, 111, 1, '2024-05-03', 50.00),

(8, 112, 2, '2024-05-04', 100.00),

(9, 113, 3, '2024-05-05', 75.00),

(1, 101, 5, '2024-05-06', 200.00),

(2, 102, 2, '2024-05-07', 150.00),

(3, 103, 1, '2024-05-08', 60.00),

(4, 104, 2, '2024-06-01', 80.00),

(5, 105, 3, '2024-06-02', 120.00),

(6, 106, 1, '2024-06-03', 50.00),

(7, 107, 2, '2024-06-04', 100.00),

(8, 108, 3, '2024-06-05', 75.00),

(9, 109, 5, '2024-06-06', 200.00),

(1, 110, 2, '2024-06-07', 150.00),

(2, 111, 1, '2024-06-08', 60.00),

(3, 112, 2, '2024-07-01', 80.00),


(4, 113, 3, '2024-07-02', 120.00),

(5, 101, 1, '2024-07-03', 50.00),

(6, 102, 2, '2024-07-04', 100.00),

(7, 103, 3, '2024-07-05', 75.00),

(8, 104, 5, '2024-07-06', 200.00),

(9, 105, 2, '2024-07-07', 150.00),

(1, 106, 1, '2024-07-08', 60.00),

(2, 107, 2, '2024-08-01', 80.00),

(3, 108, 3, '2024-08-02', 120.00),

(4, 109, 1, '2024-08-03', 50.00),

(5, 110, 2, '2024-08-04', 100.00),

(6, 111, 3, '2024-08-05', 75.00),

(7, 112, 5, '2024-08-06', 200.00),

(8, 113, 2, '2024-08-07', 150.00),

(9, 101, 1, '2024-08-08', 60.00);

--Data_for_sorting Table
CREATE TABLE data_for_sorting (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

gender VARCHAR(10),

city VARCHAR(50),

salary DECIMAL(10, 2),

join_date DATE,

department VARCHAR(50)

);
--Data_for_sorting Table Data
INSERT INTO data_for_sorting (id, name, age, gender, city, salary, join_date, department) VALUES

(1, 'Alice', 30, 'Female', 'New York', 60000.00, '2020-01-15', 'HR'),

(2, 'Bob', 25, 'Male', 'Los Angeles', 55000.00, '2021-03-10', 'IT'),

(3, 'Charlie', 35, 'Male', 'Chicago', 70000.00, '2019-06-20', 'Finance'),

(4, 'Diana', 28, 'Female', 'Miami', 65000.00, '2022-08-30', 'Marketing'),

(5, 'Ethan', 40, 'Male', 'Seattle', 80000.00, '2018-11-12', 'IT'),

(6, 'Fiona', 32, 'Female', 'Houston', 62000.00, '2020-05-05', 'HR'),

(7, 'George', 45, 'Male', 'Dallas', 85000.00, '2017-02-22', 'Finance'),

(8, 'Hannah', 29, 'Female', 'San Francisco', 59000.00, '2021-04-14', 'Marketing'),

(9, 'Ian', 38, 'Male', 'Boston', 72000.00, '2019-12-18', 'Sales'),

(10, 'Jane', 27, 'Female', 'Atlanta', 63000.00, '2020-07-30', 'HR'),

(11, 'Kyle', 33, 'Male', 'Denver', 67000.00, '2021-01-05', 'IT'),

(12, 'Laura', 36, 'Female', 'Phoenix', 61000.00, '2018-09-15', 'Finance'),

(13, 'Mike', 41, 'Male', 'Philadelphia', 78000.00, '2020-10-21', 'Marketing'),

(14, 'Nina', 24, 'Female', 'San Diego', 54000.00, '2023-02-10', 'Sales'),

(15, 'Oscar', 29, 'Male', 'Dallas', 57000.00, '2021-05-25', 'HR'),

(16, 'Paula', 37, 'Female', 'Miami', 64000.00, '2019-11-30', 'IT'),

(17, 'Quinn', 30, 'Male', 'Seattle', 72000.00, '2022-01-18', 'Finance'),

(18, 'Rita', 34, 'Female', 'Boston', 59000.00, '2020-06-02', 'Marketing'),

(19, 'Sam', 39, 'Male', 'Los Angeles', 83000.00, '2017-03-07', 'Sales'),

(20, 'Tina', 26, 'Female', 'New York', 60000.00, '2021-08-15', 'HR'),

(21, 'Ursula', 31, 'Female', 'Chicago', 62000.00, '2022-09-20', 'IT'),

(22, 'Victor', 44, 'Male', 'Phoenix', 79000.00, '2018-04-04', 'Finance'),

(23, 'Wendy', 29, 'Female', 'Denver', 64000.00, '2020-12-12', 'Marketing'),

(24, 'Xander', 42, 'Male', 'Miami', 85000.00, '2016-07-11', 'Sales'),

(25, 'Yvonne', 28, 'Female', 'San Francisco', 59000.00, '2021-10-01', 'HR'),

(26, 'Zach', 39, 'Male', 'Seattle', 75000.00, '2018-03-23', 'IT'),

(27, 'Anita', 34, 'Female', 'Houston', 66000.00, '2019-01-09', 'Finance'),

(28, 'Ben', 29, 'Male', 'Boston', 62000.00, '2020-04-16', 'Marketing'),


(29, 'Clara', 36, 'Female', 'Dallas', 64000.00, '2019-12-05', 'Sales'),

(30, 'Daniel', 32, 'Male', 'Los Angeles', 73000.00, '2021-06-30', 'HR'),

(31, 'Eva', 30, 'Female', 'Chicago', 58000.00, '2022-07-12', 'IT'),

(32, 'Fred', 41, 'Male', 'Phoenix', 81000.00, '2017-11-14', 'Finance'),

(33, 'Gina', 27, 'Female', 'San Diego', 65000.00, '2021-09-09', 'Marketing'),

(34, 'Harry', 35, 'Male', 'Denver', 70000.00, '2020-03-18', 'Sales'),

(35, 'Isla', 29, 'Female', 'New York', 59000.00, '2021-02-25', 'HR'),

(36, 'Jake', 38, 'Male', 'Seattle', 74000.00, '2019-05-10', 'IT'),

(37, 'Kara', 32, 'Female', 'Miami', 62000.00, '2020-08-22', 'Finance'),

(38, 'Liam', 40, 'Male', 'Houston', 80000.00, '2018-10-30', 'Marketing'),

(39, 'Mona', 26, 'Female', 'Dallas', 57000.00, '2022-11-05', 'Sales'),

(40, 'Nate', 34, 'Male', 'Boston', 71000.00, '2019-04-15', 'HR'),

(41, 'Olivia', 31, 'Female', 'Los Angeles', 64000.00, '2020-12-28', 'IT'),

(42, 'Paul', 43, 'Male', 'Phoenix', 79000.00, '2017-08-19', 'Finance'),

(43, 'Quincy', 29, 'Male', 'San Diego', 65000.00, '2021-07-11', 'Marketing'),

(44, 'Rachel', 37, 'Female', 'Chicago', 69000.00, '2022-01-30', 'Sales'),

(45, 'Steve', 36, 'Male', 'Miami', 72000.00, '2019-11-11', 'HR'),

(46, 'Tara', 33, 'Female', 'Dallas', 65000.00, '2020-05-21', 'IT'),

(47, 'Uri', 42, 'Male', 'Houston', 80000.00, '2018-03-17', 'Finance'),

(48, 'Vera', 28, 'Female', 'Boston', 58000.00, '2021-06-22', 'Marketing'),

(49, 'Walter', 39, 'Male', 'Seattle', 77000.00, '2017-12-01', 'Sales'),

(50, 'Zara', 27, 'Female', 'San Francisco', 59000.00, '2023-09-10', 'Sales');


--Employee Table
Create table If Not Exists Employee (id int, name varchar(255), department varchar(255), managerId
int);

--Employee Table Data


insert into Employee (id, name, department, managerId) values ('101', 'John', 'A', NULL);

insert into Employee (id, name, department, managerId) values ('102', 'Dan', 'A', '101');

insert into Employee (id, name, department, managerId) values ('103', 'James', 'A', '101');

insert into Employee (id, name, department, managerId) values ('104', 'Amy', 'A', '101');

insert into Employee (id, name, department, managerId) values ('105', 'Anne', 'A', '101');

insert into Employee (id, name, department, managerId) values ('106', 'Ron', 'B', '101');

--Project Table
Create table If Not Exists Project (project_id int, employee_id int);

--Employee Table
Create table If Not Exists Employee (employee_id int, name varchar(10), experience_years int);

--Project Table Data


insert into Project (project_id, employee_id) values ('1', '1');

insert into Project (project_id, employee_id) values ('1', '2');

insert into Project (project_id, employee_id) values ('1', '3');

insert into Project (project_id, employee_id) values ('2', '1');

insert into Project (project_id, employee_id) values ('2', '4');

--Employee Table Data


insert into Employee (employee_id, name, experience_years) values ('1', 'Khaled', '3');

insert into Employee (employee_id, name, experience_years) values ('2', 'Ali', '2');

insert into Employee (employee_id, name, experience_years) values ('3', 'John', '1');

insert into Employee (employee_id, name, experience_years) values ('4', 'Doe', '2');
--Emp Table
CREATE TABLE emp (

empid INT PRIMARY KEY,

name VARCHAR(120) NOT NULL,

salary INT NOT NULL,

phonenum VARCHAR(15) UNIQUE

);

--Emp Table Data


INSERT INTO emp (empid, name, salary, phonenum) VALUES

(1, 'Alice Johnson', 60000, '9876543210'),

(2, 'Bob Smith', 55000, '9876543211'),

(3, 'Charlie Brown', 70000, '9876543212'),

(4, 'Daisy Clark', 48000, '9876543213'),

(5, 'Edward Green', 75000, '9876543214'),

(6, 'Fiona White', 62000, '9876543215'),

(7, 'George Black', 67000, '9876543216'),

(8, 'Hannah Blue', 53000, '9876543217'),

(9, 'Ian Silver', 59000, '9876543218'),

(10, 'Jane Gold', 72000, '9876543219'),

(11, 'Kyle Brown', 56000, '9876543220'),

(12, 'Lily Scott', 64000, '9876543221'),

(13, 'Mike Davis', 68000, '9876543222'),

(14, 'Nina Adams', 63000, '9876543223'),

(15, 'Oscar Evans', 71000, '9876543224'),

(16, 'Penny Lewis', 52000, '9876543225'),

(17, 'Quinn Hill', 76000, '9876543226'),

(18, 'Rachel King', 50000, '9876543227'),

(19, 'Sam Young', 54000, '9876543228'),

(20, 'Tina Allen', 58000, '9876543229');


Table for SQL Joins
--Join_table Database
create database join_table;

--Select join_table Database


use join_table;

--Employees Table
CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

Name VARCHAR(50),

DepartmentID INT,

Position VARCHAR(50),

Salary DECIMAL(10, 2)

);

--Employees Table Data


INSERT INTO Employees (EmployeeID, Name, DepartmentID, Position, Salary) VALUES

(1, 'Alice', 101, 'Manager', 80000),

(2, 'Bob', 999, 'Analyst', 65000), -- No matching department (999)

(3, 'Charlie', 102, 'Developer', 70000),

(4, 'Daisy', 104, 'Developer', 60000),

(5, 'Edward', 105, 'Manager', 90000),

(6, 'Frank', 106, 'Designer', 62000), -- No matching department (106)

(7, 'Grace', 107, 'Intern', 35000), -- No matching department (107)

(8, 'Helen', 103, 'Consultant', 95000),

(9, 'Ian', 101, 'Analyst', 67000),

(10, 'Jane', 108, 'Developer', 75000), -- No matching department (108)

(11, 'Kevin', 102, 'Manager', 99000),

(12, 'Laura', 999, 'Intern', 32000), -- No matching department (999)


(13, 'Michael', 104, 'Tester', 58000),

(14, 'Nina', 101, 'Analyst', 62000),

(15, 'Oscar', 103, 'Designer', 64000),

(16, 'Paul', 101, 'Manager', 81000),

(17, 'Quincy', 999, 'Developer', 76000),-- No matching department (999)

(18, 'Rachel', 105, 'Manager', 88000),

(19, 'Steve', 108, 'Developer', 69000), -- No matching department (108)

(20, 'Tina', 102, 'Consultant', 93000),

(21, 'Uma', 106, 'Developer', 77000), -- No matching department (106)

(22, 'Victor', 103, 'Consultant', 80000),

(23, 'Wendy', 102, 'Analyst', 72000),

(24, 'Xander', 107, 'Intern', 34000), -- No matching department (107)

(25, 'Yara', 104, 'Manager', 90000),

(26, 'Zane', 105, 'Analyst', 76000);

--Departments Table
CREATE TABLE Departments (

DepartmentID INT PRIMARY KEY,

DepartmentName VARCHAR(50),

Location VARCHAR(50)

);

--Departments Table Data


INSERT INTO Departments (DepartmentID, DepartmentName, Location) VALUES

(101, 'IT', 'New York'),

(102, 'Finance', 'Chicago'),

(103, 'HR', 'Los Angeles'),

(104, 'Sales', 'Houston'),

(105, 'Consulting', 'San Francisco'),


(109, 'Marketing', 'Miami'); -- Department with no matching employees

--Projects Table
CREATE TABLE Projects (

ProjectID INT PRIMARY KEY,

ProjectName VARCHAR(50),

DepartmentID INT

);

--Projects Table Data


INSERT INTO Projects (ProjectID, ProjectName, DepartmentID) VALUES

(1, 'Project Alpha', 101),

(2, 'Project Beta', 102),

(3, 'Project Gamma', 101),

(4, 'Project Delta', 104),

(5, 'Project Epsilon', 105),

(6, 'Project Zeta', 103),

(7, 'Project Eta', 109), -- Project with department ID 109, no matching employees

(8, 'Project Theta', 102),

(9, 'Project Iota', 105),

(10, 'Project Kappa', 101),

(11, 'Project Lambda', 103),

(12, 'Project Mu', 106); -- Project with department ID 106, no matching in Departments

--EmployeeProject Table
CREATE TABLE EmployeeProjects (

EmployeeID INT,

ProjectID INT,

HoursWorked INT,

FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID),

FOREIGN KEY (ProjectID) REFERENCES Projects(ProjectID)


);

--Employees Table Data


INSERT INTO EmployeeProjects (EmployeeID, ProjectID, HoursWorked) VALUES

(1, 1, 120),

(2, 2, 100),

(3, 3, 110),

(4, 4, 95),

(5, 5, 130),

(6, 6, 50),

(7, 1, 60),

(8, 3, 115),

(9, 2, 80),

(10, 5, 70),

(11, 9, 85),

(12, 8, 65),

(13, 10, 75),

(14, 11, 60),

(15, 12, 90),

(16, 4, 110),

(17, 7, 95), -- Project Eta (no matching Department)

(18, 6, 105),

(19, 1, 130),

(20, 9, 75),

(21, 10, 95),

(22, 11, 120),

(23, 3, 60),

(24, 2, 50),

(25, 12, 65);

You might also like