WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

SQL & Databases · Intermediate · question 23 of 100

How do you use the different types of window functions in SQL, such as ROW_NUMBER(), RANK(), and DENSE_RANK()?

📕 Buy this interview preparation book: 100 SQL & Databases questions & answers — PDF + EPUB for $5

In SQL, window functions are used to perform calculations across a set of rows that are related to the current row. Window functions are similar to aggregate functions, but they do not group the rows into a single result row. Instead, they perform calculations on a "window" of rows that are specified using the OVER clause.

Here are some of the most common window functions in SQL:

ROW_NUMBER(): The ROW_NUMBER() function assigns a unique number to each row in the result set based on the order specified in the OVER clause. For example, the following query assigns a row number to each row in the employees table based on the hire_date column:

SELECT employee_id, first_name, last_name, hire_date, 
ROW_NUMBER() OVER (ORDER BY hire_date) AS row_num
FROM employees;

RANK(): The RANK() function assigns a rank to each row in the result set based on the order specified in the OVER clause. Rows with the same value are assigned the same rank, and the next rank is skipped. For example, the following query assigns a rank to each row in the employees table based on the salary column:

SELECT employee_id, first_name, last_name, salary, 
RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;

DENSE_RANK(): The DENSE_RANK() function is similar to RANK(), but it assigns a rank to each row in the result set based on the order specified in the OVER clause. Rows with the same value are assigned the same rank, and the next rank is not skipped. For example, the following query assigns a dense rank to each row in the employees table based on the salary column:

SELECT employee_id, first_name, last_name, salary, 
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;

There are many other window functions available in SQL, including aggregate functions like SUM(), AVG(), and MAX(), as well as analytical functions like LEAD(), LAG(), and FIRST_VALUE(). By using window functions, you can perform powerful calculations on a set of related rows in a SQL query, making it a valuable tool for data analysis and reporting.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic SQL & Databases interview — then scores it.
📞 Practice SQL & Databases — free 15 min
📕 Buy this interview preparation book: 100 SQL & Databases questions & answers — PDF + EPUB for $5

All 100 SQL & Databases questions · All topics