Advanced SQL
Description
Collection of advanced SQL from different exercises for reference.
TOC
1. SQL Window Function Part 1
1.1. Fundamentals, the Over Clause and Partition By
From SQL Window Function. Documentation on Window Function. Documentation on Window Functions.
A window function performs a calculation across a set of (table) rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. However, window functions do not cause rows to become grouped into a single output row like non-window aggregate calls would. Instead, the rows retain their separate identities. For example these queries:
select max(salary) as max_salary
from employee
select dept_name, max(salary) as max_salary_per_department
from employee
group by dept_name
Become these:
select e.*, max(salary) over() as max_salary
from employee as e
-- the over clause with no parameter produces a window of the whole table
select e.*, max(salary) over( partition by dept_name ) as max_salary_per_dept
from employee as e
-- shows max salary per deparment in addition to employee data
Note that the rows considered by a window function are those of the “virtual table” produced by the query's FROM clause (as filtered by its WHERE, GROUP BY, and HAVING clauses if any). For example, a row removed because it does not meet the WHERE condition is not seen by any window function.
1.2. Other examples and Row Number and Order By (inside Over Clause)
select e.*, row_number() over() as rn
from employee e
-- gives each record a unique identifier; to use it, we can pass the query as a subquery
select e.*, row_number() over( partition by dept_name ) over() as rn
from employee e
-- gives each record per department an identifier
Note that You can also control the order in which rows are processed by window functions using ORDER BY within OVER. (The window ORDER BY does not even have to match the order in which the rows are returned). For example:
SELECT depname, empno, salary, rank() OVER (PARTITION BY depname ORDER BY salary DESC)
FROM empsalary
From our previous example
select e.*, row_number() over(partition by dept_name order by emp_id) as rn
from employee e
-- We make the assumption that emp_id reflects when the employee joined the company
We use this query as a subquery to fetch the first 2 employees from each department to join the company
select *
from
(select e.*, row_number() over(partition by dept_name order by emp_id) as rn from employee e) sq
where sq.rn < 3
1.3. Window Functions: Rank, Dense Rank
select e.*, rank() over(partition by dept_name order by salary desc) as rnk
from employee e
We use this subquery to determine the employees with the top 3 salaries per department
select *
from (select e.*, rank() over(partition by dept_name order by salary desc) as rnk
from employee e) sq
where sq.rnk < 4
select e.*, rank() over(partition by dept_name order by salary desc) as rnk, dense_rank() over(partition by dept_name order by salary desc) as dense_rnk
from employee e
Alternative:
select e.*, rank() over w as rnk, dense_rank() over w as dense_rnk
from employee e
window w as (partition by dept_name order by salary desc)
Note that when a query involves multiple window functions, it is possible to write out each one with a separate OVER clause, but this is duplicative and error-prone if the same windowing behavior is wanted for several functions. Instead, each windowing behavior can be named in a WINDOW clause and then referenced in OVER. For example:
SELECT sum(salary) OVER w, avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);
1.4. Window Functions: Lead and Lag
Task: Fetch a query to display if the salary of an employee is higher, lower or equal to the previous employee. Preparation:
select e.*, lag(salary) over (partition by dept_name order by emp_id) as prev_emp_salary
from employee e
We can pass some other arguments with the lag function (see Documentation).
select e.*, lag(salary,2,0) over (partition by dept_name order by emp_id) as prev_emp_salary
from employee e
Lead gives us the rows that are following the current row.
select e.*, lead(salary) over (partition by dept_name order by emp_id) as next_emp_salary
from employee e
Solution:
select
e.*,
lag(salary) over w as prev_emp_salary,
case
when e.salary > lag(salary) over w then 'Higher than previous employee'
when e.salary < lag(salary) over w then 'Lower than previous employee'
when e.salary = lag(salary) over w then 'Same as previous employee'
end sal_range
from employee e
window w as (partition by dept_name order by emp_id)
Another example from our database:
select
p.payment_id,
p.amount as current_amount,
lag(amount) over w as prev_amount,
case
when amount > lag(amount) over w then 'Higher than previous amount'
when amount < lag(amount) over w then 'Lower than previous amount'
when lag(amount) over w is null then 'No info'
else 'The same as previous amount'
end as amount_range
from
payment p window w as (
partition by customer_id
order by
payment_date
)
2. SQL Window Function Part 2
2.1. First and Last Value
From SQL Window Function Part 2. Documentation on Window Functions. Task: Write a query to display the most expensive product under each category (corresponding ot each record).
select p.*, first_value(product_name) over(partition by product_category order by price desc) as most_exp_per_category
from product p
Task: Write a query to display the least expensive product under each category (corresponding to each record)
select *, last_value(product_name) over(partition by product_category order by price desc) as least_exp_product
from product
This delivers the wrong result! The reason is the default frame clause.
Note: Ideally we would use the rank() window function to accomplish this task. For example:
with rk as
(
select
payment_id, customer_id, amount,
rank() over (partition by customer_id order by amount asc) from payment
)
select *
from rk
where rank = 1
order by customer_id
2.2. Frame Clause
Note that first_value, last_value, and nth_value consider only the rows within the "window frame", which by default contains the rows from the start of the partition through the last peer of the current row. This is likely to give unhelpful results for last_value and sometimes also nth_value. You can redefine the frame by adding a suitable frame specification (RANGE or ROWS) to the OVER clause. See Section 4.2.8 for more information about frame specifications. The default frame clause is:
select
p.*,
last_value(product_name) over(
partition by product_category
order by price desc
range between unbounded preceding and current row
)
from product p
To use the last_value window function, we need to adjust the frame clause:
select
p.*,
last_value(product_name) over(
partition by product_category
order by price desc
range between unbounded preceding and unbounded following
)
from product p
An alternative frame is the following:
To use the last_value window function, we need to adjust the frame clause:
select
p.*,
last_value(product_name) over(
partition by product_category
order by price desc
rows between unbounded preceding and unbounded following
)
from product p
This alternative becomes relevant when we have duplicates. rows considers the exact current row while range considers the last row of all duplicate values. range allows the current row to see ahead of itself into the last row with a duplicate value. We can also specify the number of rows:
select
p.*,
last_value(product_name) over(
partition by product_category
order by price desc
rows between 2 preceding and 2 following
)
from product p
An example from our database:
-- fetch lowest amount per customer
-- default frame: range between unbounded preceding and current row
select
p.*,
-- first_value(payment_id) over(partition by customer_id order by amount desc) as highest_payment,
last_value(amount) over(
partition by customer_id
order by amount desc
range between unbounded preceding and unbounded following
) as lowest_payment
from payment p
-- order by amount
2.3. Windows Clause
select
*,
first_value(product_name) over w as most_exp_product,
last_value(product_name) over w as least_exp_product
from product
window w as (partition by product_category order by price desc range between unbounded preceding and unbounded following)
-- order by
2.4. N-th Value
Fetch a value from any particular position. Task: Write a query to display the second most expensive product under each category. Note that dense_rank() is a better option here.
select
*,
nth_value(product_name, 2) over(partition by product_category order by price desc) as second_most_expensive
from product
If the number of records is less that the parameter, the nth_value function will return null. This query won't display correctly for the first record (see frame clause above). We can fix this:
select
*,
nth_value(product_name, 2) over w as second_most_expensive
from product
window w as (partition by product_category order by price desc range between unbounded preceding and unbounded following)
2.5. Ntile
Task: Write a query to segregate all the expensive phones, mid range and the cheaper phones.
with phone_bucket as (
select
*,
ntile(3) over (order by price desc) as bucket
from product
where product_category = 'Phone'
)
select
product_name,
case
when bucket = 1 then 'Expensive Phone'
when bucket = 2 then 'Mid Phone'
when bucket = 3 then 'Cheaper Phone'
end
from phone_bucket
2.6. Cumulative Distribution Cume_Dist
cume_dist = sum (# of rows with the same value as the current row / # of rows)
Task: Write a query to fetch all products which are constituting the first 30% of the data in products table based on price -> write a query to fetch the top 30% products based on price.
select
*,
cume_dist() over (order by price desc) as cume_dist_by_price
from product
-- cast cume_dist() to numeric to use round function
We can clean up the table:
select
*,
round(cume_dist() over (order by price desc)::numeric*100,2) as cume_dist_by_price
from product
-- cast cume_dist() to numeric to use round function
We can then use this query as a subquery and filter our data:
with cume_dist_t as (
select
*,
round(cume_dist() over (order by price desc)::numeric*100,2) as cume_dist_by_price
from product
)
select product_name, (cume_dist_by_price || '%') as cume_dist_pct
from cume_dist_t
where cume_dist_by_price <= 30
2.7. Percent Rank
Similar to cume_list. Relative rank of the current row. percent_rank = (# of current row - 1) / (# of rows -1)
Task: Write a query to identify how much percentage more expensive is the phone "Galaxy Z Fold 3" when compared to all products
select
*,
round(percent_rank() over(order by price)::numeric*100,2) as pct_rank
from product
We use this as our subquery:
with pct_rank as (
select
*,
round(percent_rank() over(order by price)::numeric*100,2) as pct_rank
from product
)
select product_name, pct_rank
from pct_rank
where product_name = 'Galaxy Z Fold 3'