0% found this document useful (0 votes)
3 views29 pages

CRUD

The document provides a comprehensive overview of CRUD operations (Create, Read, Update, Delete) in SQL, detailing their syntax and examples. It also covers advanced SQL techniques such as filtering, ordering, limiting data, grouping, aggregation, and various types of joins, along with practical use cases for each concept. Additionally, it emphasizes best practices for using SQL effectively in data analysis.

Uploaded by

seifmagdy972
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 views29 pages

CRUD

The document provides a comprehensive overview of CRUD operations (Create, Read, Update, Delete) in SQL, detailing their syntax and examples. It also covers advanced SQL techniques such as filtering, ordering, limiting data, grouping, aggregation, and various types of joins, along with practical use cases for each concept. Additionally, it emphasizes best practices for using SQL effectively in data analysis.

Uploaded by

seifmagdy972
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/ 29

CRUD: Detailed Explanation

CRUD is an acronym for the four basic operations performed on a database:

 Create: Add new records to a table.

 Read: Retrieve existing records.

 Update: Modify existing records.

 Delete: Remove records from a table.

Here’s a detailed explanation of each operation with SQL examples.

1. CREATE
This operation adds new data (rows) to a database table. In SQL, the INSERT INTO statement is used for
this purpose.

Syntax:

INSERT INTO table_name (column1, column2, column3, ...)

VALUES (value1, value2, value3, ...);

Example:

Suppose we have a table called Customers:

CustomerID Name Age City

1 Alice 30 New York

Add a new customer:

INSERT INTO Customers (CustomerID, Name, Age, City)

VALUES (2, 'Bob', 25, 'Chicago');

After execution, the table becomes:

CustomerID Name Age City

1 Alice 30 New York

2 Bob 25 Chicago

2. READ

This operation retrieves data from the database. In SQL, the SELECT statement is used for reading.
Syntax:

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Example:

Retrieve all data from the Customers table:

SELECT * FROM Customers;

Result:

CustomerID Name Age City

1 Alice 30 New York

2 Bob 25 Chicago

Retrieve customers who live in Chicago:

SELECT Name, Age

FROM Customers

WHERE City = 'Chicago';

Result:

Name Age

Bob 25

3. UPDATE

This operation modifies existing data in the database. In SQL, the UPDATE statement is used.

Syntax:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

Example:

Change Bob's age to 26:

UPDATE Customers
SET Age = 26

WHERE Name = 'Bob';

After execution, the table becomes:

CustomerID Name Age City

1 Alice 30 New York

2 Bob 26 Chicago

4. DELETE

This operation removes data from the database. In SQL, the DELETE statement is used.

Syntax:

DELETE FROM table_name

WHERE condition;

Example:

Remove Bob from the Customers table:

DELETE FROM Customers

WHERE Name = 'Bob';

After execution, the table becomes:

CustomerID Name Age City

1 Alice 30 New York

Combining CRUD with a Practical Workflow

Let’s simulate a typical workflow for CRUD operations:

1. Create: Add a new customer:

2. INSERT INTO Customers (CustomerID, Name, Age, City)

3. VALUES (3, 'Charlie', 28, 'Los Angeles');

4. Read: Check all customers:

5. SELECT * FROM Customers;

6. Update: Change Charlie's city to San Francisco:


7. UPDATE Customers

8. SET City = 'San Francisco'

9. WHERE CustomerID = 3;

10. Delete: Remove a customer based on ID:

11. DELETE FROM Customers

12. WHERE CustomerID = 3;

Filtering, Ordering, and Limiting Data in SQL: Advanced Examples

These techniques help refine the data retrieved from a database to get meaningful insights. Here's an in-
depth look with advanced use cases.

1. Filtering Data

Filtering is done using the WHERE clause, allowing you to retrieve specific rows based on conditions.

Advanced Filtering

 Multiple Conditions: Combine conditions using AND and OR.

 Pattern Matching: Use LIKE with wildcards.

 Range Filters: Use BETWEEN for range conditions.

Examples:

a) Filter Customers Based on Multiple Conditions Retrieve customers from Customers table who are
older than 25 and live in either New York or Chicago:

SELECT *

FROM Customers

WHERE Age > 25

AND (City = 'New York' OR City = 'Chicago');

b) Filter Using Wildcards Find all customers whose name starts with 'A':

SELECT *

FROM Customers

WHERE Name LIKE 'A%';


c) Filter Within a Range Get customers aged between 20 and 30:

SELECT *

FROM Customers

WHERE Age BETWEEN 20 AND 30;

2. Ordering Data

Ordering allows you to sort query results using the ORDER BY clause.

Advanced Ordering

 Sort by multiple columns.

 Use custom sorting logic.

Examples:

a) Order by Multiple Columns Sort customers first by City (alphabetically) and then by Age (descending):

SELECT *

FROM Customers

ORDER BY City ASC, Age DESC;

b) Order by Calculated Fields Sort by the length of customer names:

SELECT *, LENGTH(Name) AS NameLength

FROM Customers

ORDER BY NameLength DESC;

3. Limiting Data

Limiting reduces the number of rows returned, often combined with ORDER BY.

Advanced Limiting

 Pagination: Fetch subsets of data for use in pages.

 Top-N Queries: Fetch only the top results based on a condition.

Examples:

a) Top 3 Oldest Customers Fetch the top 3 oldest customers:


SELECT *

FROM Customers

ORDER BY Age DESC

LIMIT 3;

b) Pagination Fetch data for page 2 where each page has 5 rows:

SELECT *

FROM Customers

ORDER BY CustomerID

LIMIT 5 OFFSET 5;

Combining Filtering, Ordering, and Limiting

Retrieve the top 2 youngest customers from Chicago or New York, sorted by age:

SELECT *

FROM Customers

WHERE City IN ('Chicago', 'New York')

ORDER BY Age ASC

LIMIT 2;

Practical Use Case

Question:

Find the top 5 cities with the most customers and their total age sum, sorted by the total age sum in
descending order.

Solution:

SELECT City, COUNT(*) AS CustomerCount, SUM(Age) AS TotalAge

FROM Customers

GROUP BY City

ORDER BY TotalAge DESC

LIMIT 5;
Complex Filtering with Subqueries

Retrieve customers whose age is above the average age of all customers:

SELECT *

FROM Customers

WHERE Age > (

SELECT AVG(Age)

FROM Customers

);

Grouping and Aggregation in SQL: Advanced Examples and Explanation

Grouping and aggregation are essential for analyzing data by categorizing it into groups and applying
aggregate functions like COUNT, SUM, AVG, MAX, and MIN.

1. GROUP BY Clause

The GROUP BY clause is used to group rows with the same values in specified columns into summary
rows, such as totals or averages.

Basic Syntax:

SELECT column1, aggregate_function(column2)

FROM table_name

GROUP BY column1;

Example:

Get the total number of customers in each city:

SELECT City, COUNT(*) AS CustomerCount

FROM Customers

GROUP BY City;

2. Aggregate Functions

These functions perform calculations on a set of values and return a single result.

 COUNT(): Counts rows.


 SUM(): Adds values.

 AVG(): Computes the average.

 MAX() / MIN(): Finds the highest/lowest value.

Example:

Find the average age of customers in each city:

SELECT City, AVG(Age) AS AverageAge

FROM Customers

GROUP BY City;

3. Advanced Grouping and Aggregation

a) Using HAVING for Filtered Groups

The HAVING clause filters groups after aggregation (similar to WHERE but for grouped data).

Example: Find cities with more than 2 customers:

SELECT City, COUNT(*) AS CustomerCount

FROM Customers

GROUP BY City

HAVING COUNT(*) > 2;

b) Multiple Columns in GROUP BY

Group by more than one column to create subgroups.

Example: Find the total number of customers grouped by city and age:

SELECT City, Age, COUNT(*) AS CustomerCount

FROM Customers

GROUP BY City, Age;

c) Calculating Ratios or Percentages

Calculate the percentage of customers in each city relative to the total number of customers.

Example:

SELECT City,
COUNT(*) AS CustomerCount,

(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM Customers)) AS Percentage

FROM Customers

GROUP BY City;

d) Using Aggregates in Expressions

Combine aggregate functions in calculations.

Example: Find the difference between the maximum and minimum ages of customers in each city:

SELECT City, MAX(Age) - MIN(Age) AS AgeRange

FROM Customers

GROUP BY City;

4. Combining GROUP BY with JOINs

Use GROUP BY with JOIN to aggregate data across multiple tables.

Example:

Assume we have another table, Orders:

OrderID CustomerID Amount

1 1 100

2 2 200

3 1 150

Find the total order amount for each customer:

SELECT c.Name, SUM(o.Amount) AS TotalSpent

FROM Customers c

JOIN Orders o ON c.CustomerID = o.CustomerID

GROUP BY c.Name;

‫دعنا نشرح هذه الجملة خطوة بخطوة بالتفصيل‬:

‫ الجملة‬SQL
SELECT c.Name, SUM(o.Amount) AS TotalSpent

FROM Customers c

JOIN Orders o ON c.CustomerID = o.CustomerID

GROUP BY c.Name;
‫بيانات افتراضية‬

‫جدول‬Customers:

CustomerID Name Age City

CustomerID Name Age City

1 Alice 30 New York

2 Bob 25 Chicago

3 Charlie 28 Boston

‫جدول‬Orders:

OrderID CustomerID Amount

1 1 100

2 1 200

3 2 150

4 3 300

5 1 50

‫نتيجة الجملة‬

‫ وحساب المجموع اإلجمالي للمبالغ التي أنفقها كل عميل‬،‫ يتم تجميع الطلبات حسب العمالء‬،‫بعد تطبيق الجملة‬.

Name TotalSpent

Alice 350

Bob 150

Charlie 300
5. GROUP BY with Subqueries

Combine subqueries for more advanced grouping logic.

Example:

Find the top city with the highest average customer age:

SELECT City, AVG(Age) AS AverageAge

FROM Customers

GROUP BY City

HAVING AVG(Age) = (

SELECT MAX(AVG(Age))

FROM Customers

GROUP BY City

);

6. Aggregating with Window Functions

Window functions allow performing aggregate calculations without collapsing rows, which provides a
more flexible alternative to GROUP BY.

Example:

Add a column showing the total number of customers in the same city:

SELECT Name, City, COUNT(*) OVER (PARTITION BY City) AS CustomerCountInCity

FROM Customers;

7. Practical Use Case

Question:

Find the city with the highest total order amount, and list its total along with the number of customers.

Solution:

SELECT c.City,

SUM(o.Amount) AS TotalOrderAmount,
COUNT(DISTINCT c.CustomerID) AS CustomerCount

FROM Customers c

JOIN Orders o ON c.CustomerID = o.CustomerID

GROUP BY c.City

ORDER BY TotalOrderAmount DESC

LIMIT 1;

SQL Joins for Data Analysis: A Detailed Explanation

In SQL, joins are used to combine rows from two or more tables based on a related column between
them. They are a cornerstone of relational database operations, enabling users to extract meaningful
insights from data spread across multiple tables.

Types of Joins in SQL

There are several types of joins, each serving a specific purpose depending on the analysis requirements:

1. INNER JOIN

 Definition: Returns only the rows where there is a match in both tables.

 Use Case: When you need data that exists in both tables.

 Example: Suppose you have two tables:

o employees: Contains employee details.

o departments: Contains department information.

 SELECT employees.employee_id, employees.name, departments.department_name

 FROM employees

 INNER JOIN departments

 ON employees.department_id = departments.department_id;

Output: Only employees who are assigned to a department.

2. LEFT JOIN (LEFT OUTER JOIN)

 Definition: Returns all rows from the left table and matched rows from the right table. If no
match exists, NULLs are returned for columns from the right table.
 Use Case: When you want to include all records from the left table, regardless of whether
there's a match in the right table.

 Example:

 SELECT employees.employee_id, employees.name, departments.department_name

 FROM employees

 LEFT JOIN departments

 ON employees.department_id = departments.department_id;

Output: All employees, including those not assigned to any department.

3. RIGHT JOIN (RIGHT OUTER JOIN)

 Definition: Returns all rows from the right table and matched rows from the left table. If no
match exists, NULLs are returned for columns from the left table.

 Use Case: When you want to include all records from the right table, regardless of whether
there's a match in the left table.

 Example:

 SELECT employees.employee_id, employees.name, departments.department_name

 FROM employees

 RIGHT JOIN departments

 ON employees.department_id = departments.department_id;

Output: All departments, including those with no employees.

4. FULL OUTER JOIN

 Definition: Combines the results of both LEFT JOIN and RIGHT JOIN. Returns all rows when
there's a match in either table, and NULLs for unmatched rows in both.

 Use Case: When you need a comprehensive dataset showing all records from both tables,
regardless of matches.

 Example:

 SELECT employees.employee_id, employees.name, departments.department_name

 FROM employees

 FULL OUTER JOIN departments


 ON employees.department_id = departments.department_id;

Output: All employees and all departments, showing NULLs where there is no match.

5. CROSS JOIN

 Definition: Returns the Cartesian product of the two tables, meaning every row in the first table
is paired with every row in the second table.

 Use Case: Rarely used directly but helpful for scenarios like generating test datasets or
combining every combination of items.

 Example:

 SELECT employees.name, departments.department_name

 FROM employees

 CROSS JOIN departments;

Output: A row for every combination of employee and department.

6. SELF JOIN

 Definition: A table is joined with itself. Used when the table has a hierarchical or relational
structure within itself.

 Use Case: To compare rows within the same table.

 Example:

 SELECT e1.employee_id AS Employee, e2.name AS Manager

 FROM employees e1

 INNER JOIN employees e2

 ON e1.manager_id = e2.employee_id;

Output: Shows employees and their corresponding managers.

Practical Tips for Using Joins in Data Analysis

1. Use Aliases: Simplifies queries and improves readability.

2. SELECT e.name AS Employee, d.department_name AS Department

3. FROM employees e

4. INNER JOIN departments d


5. ON e.department_id = d.department_id;

6. Optimize for Performance:

o Index columns used in join conditions to speed up queries.

o Use EXPLAIN or EXPLAIN PLAN to analyze query performance.

7. Handle NULLs: Be cautious with NULL values, especially in outer joins. Use COALESCE to replace
NULLs with default values.

8. SELECT employee_id, COALESCE(department_name, 'No Department') AS department

9. FROM employees

10. LEFT JOIN departments

11. ON employees.department_id = departments.department_id;

12. Filter Results: Use WHERE or ON conditions to refine your data.

13. SELECT e.name, d.department_name

14. FROM employees e

15. LEFT JOIN departments d

16. ON e.department_id = d.department_id

17. WHERE d.department_name IS NOT NULL;

Real Example: SQL Joins for Data Analysis

Suppose we have the following two tables:

employees Table

employee_id name department_id

1 Alice 101

2 Bob 102

3 Charlie NULL

4 David 103

departments Table

department_id department_name

101 Sales
department_id department_name

102 Marketing

103 IT

104 Human Resources

1. INNER JOIN

Query: Find all employees with their respective departments.

SELECT e.employee_id, e.name, d.department_name

FROM employees e

INNER JOIN departments d

ON e.department_id = d.department_id;

Output:

employee_id name department_name

1 Alice Sales

2 Bob Marketing

4 David IT

Explanation: Only employees with a matching department_id in the departments table are included.

2. LEFT JOIN

Query: Get all employees, including those without a department.

SELECT e.employee_id, e.name, d.department_name

FROM employees e

LEFT JOIN departments d

ON e.department_id = d.department_id;

Output:

employee_id name department_name

1 Alice Sales
employee_id name department_name

2 Bob Marketing

3 Charlie NULL

4 David IT

Explanation: All employees are listed, but Charlie has no matching department, so department_name is
NULL.

3. RIGHT JOIN

Query: List all departments, including those without employees.

SELECT e.employee_id, e.name, d.department_name

FROM employees e

RIGHT JOIN departments d

ON e.department_id = d.department_id;

Output:

employee_id name department_name

1 Alice Sales

2 Bob Marketing

4 David IT

NULL NULL Human Resources

Explanation: All departments are listed, even if no employees are assigned to them, as seen with
"Human Resources."

4. FULL OUTER JOIN

Query: List all employees and departments, showing unmatched rows from both tables.

SELECT e.employee_id, e.name, d.department_name

FROM employees e

FULL OUTER JOIN departments d

ON e.department_id = d.department_id;
Output:

employee_id name department_name

1 Alice Sales

2 Bob Marketing

3 Charlie NULL

4 David IT

NULL NULL Human Resources

Explanation: Shows all employees and all departments. Missing matches are represented by NULLs.

5. CROSS JOIN

Query: Pair every employee with every department.

SELECT e.name AS employee_name, d.department_name

FROM employees e

CROSS JOIN departments d;

Output:

employee_name department_name

Alice Sales

Alice Marketing

Alice IT

Alice Human Resources

Bob Sales

Bob Marketing

Bob IT

Bob Human Resources

Charlie Sales

Charlie Marketing
employee_name department_name

Charlie IT

Charlie Human Resources

David Sales

David Marketing

David IT

David Human Resources

Explanation: Produces a Cartesian product (all combinations).

6. SELF JOIN

Query: Find employees and their managers (assuming manager_id is stored in employees table).

Updated employees Table:

employee_id name department_id manager_id

1 Alice 101 3

2 Bob 102 1

3 Charlie NULL NULL

4 David 103 1

Query:

SELECT e1.name AS employee_name, e2.name AS manager_name

FROM employees e1

LEFT JOIN employees e2

ON e1.manager_id = e2.employee_id;

Output:

employee_name manager_name

Alice Charlie

Bob Alice
employee_name manager_name

Charlie NULL

David Alice

Explanation: Each employee is paired with their manager using a self-join.

Subqueries in SQL: A Detailed Explanation with Real Examples

A subquery (or nested query) is a query embedded within another SQL query. It allows you to perform
operations on the result of one query and use it in another query. Subqueries are often used in WHERE,
HAVING, FROM, or SELECT clauses to break down complex problems into manageable steps.

Types of Subqueries

1. Single-Row Subquery: Returns a single value (e.g., one row and one column).

2. Multi-Row Subquery: Returns multiple rows for one column.

3. Correlated Subquery: References a column from the outer query and is evaluated repeatedly.

4. Nested Subquery in SELECT Clause: Embeds a query as a column in the result.

Real Examples

Example Tables:

employees Table:

employee_id name salary department_id

1 Alice 50000 101

2 Bob 60000 102

3 Charlie 70000 101

4 David 45000 103

departments Table:

department_id department_name

101 Sales
department_id department_name

102 Marketing

103 IT

1. Single-Row Subquery

Problem: Find employees earning more than the average salary.

SELECT name, salary

FROM employees

WHERE salary > (SELECT AVG(salary) FROM employees);

Subquery:

SELECT AVG(salary) FROM employees;

 Returns the average salary (56250).

Main Query: Find employees with a salary greater than 56250.

Output:

name salary

Bob 60000

Charlie 70000

2. Multi-Row Subquery

Problem: List all employees who work in departments with more than one employee.

SELECT name, department_id

FROM employees

WHERE department_id IN (

SELECT department_id

FROM employees

GROUP BY department_id

HAVING COUNT(*) > 1

);
Subquery:

SELECT department_id

FROM employees

GROUP BY department_id

HAVING COUNT(*) > 1;

 Returns departments with more than one employee (101).

Main Query: Find employees who work in those departments.

Output:

name department_id

Alice 101

Charlie 101

3. Correlated Subquery

Problem: Find employees whose salary is higher than the average salary of their respective department.

SELECT name, salary, department_id

FROM employees e1

WHERE salary > (

SELECT AVG(salary)

FROM employees e2

WHERE e1.department_id = e2.department_id

);

How It Works:

 For each row in the outer query (e1), the subquery calculates the average salary of the
respective department (e2).

Output:

name salary department_id

Charlie 70000 101


4. Subquery in SELECT Clause

Problem: Show employees along with their department names.

SELECT e.name, e.salary,

(SELECT d.department_name

FROM departments d

WHERE e.department_id = d.department_id) AS department_name

FROM employees e;

Subquery: For each employee, fetch the corresponding department name.

Output:

name salary department_name

Alice 50000 Sales

Bob 60000 Marketing

Charlie 70000 Sales

David 45000 IT

5. Subquery in FROM Clause (Derived Table)

Problem: Find the average salary for each department and list departments where the average salary
exceeds 55000.

SELECT department_name, avg_salary

FROM (

SELECT d.department_name, AVG(e.salary) AS avg_salary

FROM employees e

JOIN departments d

ON e.department_id = d.department_id

GROUP BY d.department_name

) AS dept_avg

WHERE avg_salary > 55000;

Derived Table:
SELECT d.department_name, AVG(e.salary) AS avg_salary

FROM employees e

JOIN departments d

ON e.department_id = d.department_id

GROUP BY d.department_name;

 Returns average salaries for departments:

o Sales: 60000

o Marketing: 60000

o IT: 45000

Main Query: Filter for departments where the average salary exceeds 55000.

Output:

department_name avg_salary

Sales 60000

Marketing 60000

6. EXISTS Subquery

Problem: Find all departments that have employees.

SELECT department_name

FROM departments d

WHERE EXISTS (

SELECT 1

FROM employees e

WHERE e.department_id = d.department_id

);

Subquery:

SELECT 1

FROM employees e

WHERE e.department_id = d.department_id;


 Checks if there are employees for each department.

Output:

department_name

Sales

Marketing

IT

Summary of Use Cases for Subqueries

 Single-Row Subqueries: Compare a value to a single result, such as averages or sums.

 Multi-Row Subqueries: Use with IN, ANY, or ALL to match multiple values.

 Correlated Subqueries: Use when the subquery depends on data from the outer query.

 Subqueries in SELECT: Fetch related data directly as columns.

 Subqueries in FROM: Organize subquery results into temporary tables for further processing.

 EXISTS Subqueries: Check the existence of related data.

Types of Window Functions

1. Ranking Functions

 ROW_NUMBER(): Assigns a unique number to each row in the window, starting from 1.

 RANK(): Assigns a rank to each row, with gaps for ties.

 DENSE_RANK(): Assigns a rank without gaps for ties.

 NTILE(n): Divides rows into n buckets and assigns a bucket number.

2. Aggregate Window Functions

 SUM(), AVG(), MIN(), MAX(), COUNT(): Perform aggregations over the window.

3. Value Functions

 FIRST_VALUE(), LAST_VALUE(): Fetch the first or last value in the window.

 LEAD(), LAG(): Fetch the next or previous value relative to the current row.

Example Tables
sales Table:

sale_id employee_name department amount sale_date

1 Alice Sales 500 2023-12-01

2 Bob Sales 700 2023-12-02

3 Charlie Sales 450 2023-12-03

4 David Marketing 800 2023-12-01

5 Eve Marketing 650 2023-12-02

1. ROW_NUMBER()

Problem: Assign a unique number to each sale within each department, ordered by amount
(descending).

SELECT employee_name, department, amount,

ROW_NUMBER() OVER (PARTITION BY department ORDER BY amount DESC) AS row_num

FROM sales;

Output:

employee_name department amount row_num

Bob Sales 700 1

Alice Sales 500 2

Charlie Sales 450 3

David Marketing 800 1

Eve Marketing 650 2

2. RANK() and DENSE_RANK()

Problem: Rank sales within each department, with ties handled differently.

SELECT employee_name, department, amount,

RANK() OVER (PARTITION BY department ORDER BY amount DESC) AS rank,

DENSE_RANK() OVER (PARTITION BY department ORDER BY amount DESC) AS dense_rank


FROM sales;

Output:

employee_name department amount rank dense_rank

Bob Sales 700 1 1

Alice Sales 500 2 2

Charlie Sales 450 3 3

David Marketing 800 1 1

Eve Marketing 650 2 2

Explanation:

 RANK(): Gaps appear if there are ties.

 DENSE_RANK(): No gaps in the ranking sequence.

3. NTILE(n)

Problem: Divide all sales into 2 equal-sized buckets, ordered by amount.

SELECT employee_name, department, amount,

NTILE(2) OVER (ORDER BY amount DESC) AS bucket

FROM sales;

Output:

employee_name department amount bucket

David Marketing 800 1

Bob Sales 700 1

Eve Marketing 650 2

Alice Sales 500 2

Charlie Sales 450 2

4. SUM()

Problem: Calculate a running total of sales for each department, ordered by sale_date.
SELECT employee_name, department, amount, sale_date,

SUM(amount) OVER (PARTITION BY department ORDER BY sale_date) AS running_total

FROM sales;

Output:

employee_name department amount sale_date running_total

Alice Sales 500 2023-12-01 500

Bob Sales 700 2023-12-02 1200

Charlie Sales 450 2023-12-03 1650

David Marketing 800 2023-12-01 800

Eve Marketing 650 2023-12-02 1450

5. LEAD() and LAG()

Problem: Compare each employee's sale with the next and previous sales in their department.

SELECT employee_name, department, amount,

LAG(amount) OVER (PARTITION BY department ORDER BY sale_date) AS prev_sale,

LEAD(amount) OVER (PARTITION BY department ORDER BY sale_date) AS next_sale

FROM sales;

Output:

employee_name department amount prev_sale next_sale

Alice Sales 500 NULL 700

Bob Sales 700 500 450

Charlie Sales 450 700 NULL

David Marketing 800 NULL 650

Eve Marketing 650 800 NULL

6. FIRST_VALUE() and LAST_VALUE()

Problem: Show the first and last sale amount in each department.
SELECT employee_name, department, amount,

FIRST_VALUE(amount) OVER (PARTITION BY department ORDER BY sale_date) AS first_sale,

LAST_VALUE(amount) OVER (PARTITION BY department ORDER BY sale_date

ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS


last_sale

FROM sales;

Output:

employee_name department amount first_sale last_sale

Alice Sales 500 500 450

Bob Sales 700 500 450

Charlie Sales 450 500 450

David Marketing 800 800 650

Eve Marketing 650 800 650

Summary

 Window functions add new insights while preserving the original rows.

 Key functions include:

o Ranking: ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE().

o Aggregates: SUM(), AVG(), COUNT(), etc.

o Value functions: LEAD(), LAG(), FIRST_VALUE(), LAST_VALUE().

You might also like