7 Advanced SQL Queries
7 Advanced SQL Queries
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:
Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
Advanced Joins:
Uzair Adamjee
Empowering Businesses with AI-Driven Insights
and Automation
ROLLUP AND CUBE:
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