Published
- 1 min read
Think and solve SQL queries using sql functions
SQL Functions
LEAD LEAD: Accesses a row after the current row. LEAD(column_name, offset, default_value) OVER (PARTITION BY … ORDER BY …) offset: The number of rows to look ahead (LEAD) or behind (LAG). A value of 1 means the next/previous row Example
date region sales_amt
What are sales on the next day
select date,
region,
sales_amt
LEAD(sales_amt, 1, 0) over(partition by date order by sales_amt) as sales_next_day
from sales;
*LAG LAG: Accesses a row before the current row. LAG(column_name, offset, default_value) OVER (PARTITION BY … ORDER BY …) offset: The number of rows to look ahead (LEAD) or behind (LAG). A value of 1 means the next/previous row
What are the sales on previous day
SELECT date,
region,
sales_amt
LAG(sales_amt, 1, 0) OVER(PARTITION BY region ORDER BY sales_amt)
FROM sales;
Example queries
You have a table called stock_prices with columns date, symbol, and price.
Write a SQL query using the LAG function to show the price of each stock on the previous day.
If there’s no previous day’s data (e.g., for the first day), display 0.