Advanced SQL Concepts
Advanced SQL Concepts
Advanced
SQL
Concepts
With Code Examples
Prepared by
Shruthi Annamaneni
Advanced Level
Window Functions
Window Functions are a powerful feature in SQL
that allows you to perform calculations across a set
of rows related to the current row. They provide a
way to compute running totals, moving averages,
rankings, and other analytical calculations.
Example
This query calculates the total sales for each
category using the SUM window function with the
PARTITION BY clause.
Recursive Queries with
CTEs
Example
This recursive CTE traverses the employee
hierarchy, starting from the top-level managers,
and retrieves all employees with their respective
levels in the hierarchy.
Advanced Joins and
Subqueries
Example
This query combines data from the products and
categories tables using an inner join and calculates
the total sales for each product using a correlated
subquery.
Window Functions:
Ranking Functions
This query ranks the products within each category
based on their sales, using the RANK window
function. (Use the sales_data table)
Recursive Queries:
Generating Hierarchical
Data
This recursive CTE generates a calendar table with
dates from January 1, 2023, to December 31, 2023.
Advanced Joins: Self-
Joins
This query uses a self-join on the employees
table to retrieve the employee names and their
corresponding manager names. (Use the
employees table from Slide 3.)
Subqueries in the FROM
Clause
This query uses a subquery in the FROM clause to
retrieve the product name, category, and sales
data, and then calculates the total sales for each
category. (Use the sales_data table)
Advanced Analytic Function
This query demonstrates the use of the LEAD, LAG,
FIRST_VALUE, LAST_VALUE, and NTH_VALUE,
which allow you to perform complex data analysis
and calculations based on the ordering and
partitioning of rows.
Example
Recursive Queries -
Generating Sequences
Recursive queries can be used to generate
sequences of numbers or dates, which can be
useful for various purposes, such as generating
test data or handling gaps in sequences.
Keep Learning !