Window Functions
The highest-frequency interview topic: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and running sums.
Core Learning Objectives
- •Differentiate ROW_NUMBER(), RANK(), and DENSE_RANK() tie-breaking behaviors
- •Calculate previous and next event intervals with LAG() and LEAD()
- •Compute running cumulative sums and moving averages with ROWS BETWEEN
Interactive Cheatsheet
PostgreSQL SyntaxSELECT employee_id, department_id, salary, DENSE_RANK() OVER(PARTITION BY department_id ORDER BY salary DESC) AS salary_rank, LAG(salary) OVER(PARTITION BY department_id ORDER BY salary DESC) AS next_higher_salary, SUM(salary) OVER(PARTITION BY department_id ORDER BY hire_date ROWS UNBOUNDED PRECEDING) AS running_spend FROM employees;
Curated Practice Problems (11)
Detect Rapid Multi‑Zip Card Activity with Window Functions
A fintech unicorn wants to flag potentially fraudulent credit cards that exhibit a velocity anomaly: more than three transactions occurring in different zip codes within any rolling 20‑minute window. For each flagged transaction you must return the card identifier, transaction timestamp, the zip code of that transaction, and the count of distinct zip codes seen in the preceding 20 minutes (including the current one). The solution must: - Use PostgreSQL‑compatible window functions. - Correctly handle NULL zip codes by treating them as a distinct placeholder (e.g., 'UNKNOWN') using COALESCE. - Properly rank ties when multiple transactions have the same distinct‑zip count (use DENSE_RANK or similar). - Return only rows where the distinct‑zip count exceeds 3. Schema (presented as markdown tables for clarity): | Table | Columns | |-------|----------| | cards | `card_id` INTEGER PK, `card_number` VARCHAR(16), `holder_name` VARCHAR(100) | | transactions | `txn_id` INTEGER PK, `card_id` INTEGER FK → cards(card_id), `transaction_ts` TIMESTAMP NOT NULL, `amount` DECIMAL(10,2), `zip_code` VARCHAR(10) (may be NULL) | Write a single SQL query that solves the problem using window functions, handling the edge cases described.
Median Google Search Query Frequency
Google's Search Quality team provides a frequency distribution table showing how many searches users conducted per day. Given a table `search_frequency` where: - `searches` is the number of searches performed by a user. - `num_users` is the count of users who conducted that exact number of searches. Write a query to calculate the median number of searches conducted per user, rounded to 1 decimal place. Table: - `search_frequency` (`searches` INT, `num_users` INT)
AWS Server Utilization Time
Amazon Web Services (AWS) tracks uptime logs for ec2 instances. A server is started with a `start` event and subsequently stopped with a `stop` event. Each start has a matching stop event. Write a query to calculate the total uptime in full days across all servers in the fleet. Convert the total seconds or hours of uptime into whole days (i.e. `FLOOR(total_seconds / 86400)` or `total_hours / 24`). Table: - `server_utilization` (`server_id` INT, `status_time` TIMESTAMP, `session_status` VARCHAR)
Highest-Grossing Items in Each Category
You are given a table of product transactions from Amazon's retail store in year 2026. Write a query to identify the top 2 highest-grossing products within each `category`. For each product, output: - `category` - `product` - `total_spend` Results should be ordered by `category` ascending, and then by `total_spend` descending. Table: - `product_spend` (`category` VARCHAR, `product` VARCHAR, `user_id` INT, `spend` DECIMAL, `transaction_date` TIMESTAMP)
User's Third Transaction
Uber wants to study customer habits on their platform. Specifically, they want to examine the third transaction of every user who has made at least 3 transactions. Write a query to obtain the: - `user_id` - `spend` - `transaction_date` for each user's third transaction. Sort the output by `user_id` ascending. Table: - `transactions` (`user_id` INT, `spend` DECIMAL, `transaction_date` TIMESTAMP)
Repeated Payments Within 10 Minutes
Stripe's Risk & Fraud engineering team wants to identify potential double-charging bugs or fraudulent card attacks. A repeated payment is defined as a transaction that has the same merchant_id, credit_card_id, and amount, occurring within 10 minutes or less of an immediately preceding transaction with those same attributes. Write a query to count the total number of repeated payments across the entire dataset. Table: - `transactions` (`transaction_id` INT, `merchant_id` INT, `credit_card_id` INT, `amount` DECIMAL, `transaction_timestamp` TIMESTAMP)
Listing Price vs Neighborhood Average
Airbnb wants to identify listings that are priced significantly higher than other homes in the same neighborhood. Write a query to calculate the price difference between each listing's price and the average price of listings in that same neighborhood. Return: - `listing_id` - `neighborhood` - `price` - `price_diff_vs_neighborhood` (rounded to 2 decimal places) Order results by `price_diff_vs_neighborhood` descending. Table: - `listings` (`listing_id` INT, `neighborhood` VARCHAR, `price` DECIMAL)
Top 5 Streaming Artists by Hours Listened
Spotify wants to recognize the top 5 artists with the highest total listening time across all users in February 2026. Write a query to determine the top 5 artists ranked by total streaming hours. If multiple artists have the exact same total streaming hours, they should receive the same rank (dense rank). Output: - `artist_name` - `artist_rank` Order by `artist_rank` ascending, then `artist_name` ascending. Tables: - `artists` (`artist_id` INT, `artist_name` VARCHAR) - `songs` (`song_id` INT, `artist_id` INT) - `global_streams` (`stream_id` INT, `song_id` INT, `duration_seconds` INT, `stream_date` DATE)
Customer Churn Preceding Event
*(AI Generated Practice Question — Generated by Groq Llama 3.3 and validated by PGlite engine)* A subscription company wants to analyze user activity right before they cancel their membership. For each user who has a `cancel_subscription` event, find the most recent event they performed prior to canceling. Output: - `user_id` - `last_action` - `cancel_time` Order by `user_id` ascending. Table: - `customer_audit` (`audit_id` INT, `user_id` INT, `action_name` VARCHAR, `action_time` TIMESTAMP)
Top 3 Selling Products by Department (DENSE_RANK)
Amazon Retail analytics needs to determine the top 3 revenue-generating products within each retail department. Write a SQL query using `DENSE_RANK()` to find the top 3 products by revenue within each `department`. In case of tied revenue, both products should share the same rank without skipping subsequent ranks. Return `department`, `product_name`, `total_revenue`, and `rank`. Sort by `department` ascending, then by `rank` ascending. Tables: - `product_sales` (`product_id` INT, `product_name` VARCHAR, `department` VARCHAR, `total_revenue` DECIMAL)
Rolling 7-Day Cumulative Payout Volume
Stripe's Treasury team monitors rolling 7-day cumulative payout volumes to ensure liquidity reserves. Write a SQL query using window frames (`ROWS BETWEEN`) to calculate the 7-day rolling total payout amount for each calendar date. Return `payout_date`, daily payout amount (`daily_amount`), and the 7-day rolling cumulative total (`rolling_7d_total`). Sort by `payout_date` ascending. Tables: - `daily_payouts` (`payout_date` DATE PRIMARY KEY, `amount` DECIMAL)