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

7 Advanced SQL Queries

7 Advanced SQL Queries Empowering Businesses with AI-Driven Insights and Automation By Uzair Adamjee

Uploaded by

Woody Woodpecker
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

7 Advanced SQL Queries

7 Advanced SQL Queries Empowering Businesses with AI-Driven Insights and Automation By Uzair Adamjee

Uploaded by

Woody Woodpecker
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

7 ADVANCED

SQL QUERIES
Uzair Adamjee
Empowering Businesses with AI-Driven
Insights and Automation
Common Table Expressions
(CTEs):
WITH Sales_CTE AS (
SELECT product_id, SUM(quantity) AS total_sales
FROM Sales
GROUP BY product_id
)
SELECT * FROM Sales_CTE WHERE total_sales > 100;

Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
WINDOW FUNCTIONS:

SELECT employee_name, salary,


RANK() OVER (ORDER BY salary DESC) AS
salary_rank
FROM Employees;

Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
Advanced Joins:

SELECT t1.column_a, t2.column_b


FROM table_1 t1
INNER JOIN (SELECT column_a, column_b FROM
table_2) t2
ON t2.column_a = t1.column_a;

Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
ROLLUP AND CUBE:

SELECT department, month, SUM(sales)


FROM Sales
GROUP BY ROLLUP(department, month);

Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
Pivoting Data:
SELECT product_id,
SUM(CASE WHEN year = 2023 THEN sales END)
AS sales_2023,
SUM(CASE WHEN year = 2024 THEN sales END)
AS sales_2024
FROM Sales
GROUP BY product_id;

Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
SUBQUERIES:
SELECT employee_name
FROM Employees
WHERE salary > (SELECT AVG(salary) FROM
Employees);

Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
Recursive CTEs:
WITH RECURSIVE EmployeeHierarchy AS (
SELECT employee_id, manager_id,
employee_name
FROM Employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id,
e.employee_name
FROM Employees e
INNER JOIN EmployeeHierarchy eh ON
e.manager_id = eh.employee_id
)
SELECT * FROM EmployeeHierarchy;

Uzair Adamjee
Empowering Businesses with AI-Driven Insights and
Automation
REPOST TO YOUR
NETWORK
FOLLOW FOR MORE
TIPS IF YOU LIKE THIS
ONE.
Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation

You might also like