{"id":3993,"date":"2026-11-23T21:46:59","date_gmt":"2026-11-23T16:16:59","guid":{"rendered":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions"},"modified":"2026-11-23T22:51:51","modified_gmt":"2026-11-23T17:21:51","slug":"sql-window-functions","status":"publish","type":"post","link":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions","title":{"rendered":"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More"},"content":{"rendered":"<p>A window function calculates a value across a set of rows related to the current row, and returns that value on every row instead of collapsing the rows into one. That is the whole difference from GROUP BY: SUM with GROUP BY gives you one row per group, while SUM() OVER (PARTITION BY region) keeps every row and adds the region total beside it. Ranking, running totals, month-on-month change and moving averages are all window functions.<\/p>\n<p>They are also the topic that separates a fresher SQL interview from a mid-level one. If you can explain why RANK skips a number and DENSE_RANK does not, and write a top-N-per-group query without looking anything up, you are ahead of most candidates.<\/p>\n<h2>The anatomy of a window function<\/h2>\n<p>Every window function has the same shape: a function, the keyword OVER, and inside the brackets up to three optional parts that define the window.<\/p>\n<table>\n<thead>\n<tr>\n<th>Part<\/th>\n<th>What it does<\/th>\n<th>Syntax<\/th>\n<th>Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Function<\/td>\n<td>The calculation to run<\/td>\n<td>function_name(column)<\/td>\n<td>SUM(revenue)<\/td>\n<\/tr>\n<tr>\n<td>OVER<\/td>\n<td>Marks it as a window function<\/td>\n<td>function OVER (&#8230;)<\/td>\n<td>SUM(revenue) OVER ()<\/td>\n<\/tr>\n<tr>\n<td>PARTITION BY<\/td>\n<td>Splits rows into groups; the function restarts in each<\/td>\n<td>PARTITION BY column<\/td>\n<td>PARTITION BY region<\/td>\n<\/tr>\n<tr>\n<td>ORDER BY<\/td>\n<td>Sets the order inside each partition<\/td>\n<td>ORDER BY column<\/td>\n<td>ORDER BY revenue DESC<\/td>\n<\/tr>\n<tr>\n<td>Frame<\/td>\n<td>Limits which rows around the current one are used<\/td>\n<td>ROWS BETWEEN start AND end<\/td>\n<td>ROWS BETWEEN 2 PRECEDING AND CURRENT ROW<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>An empty OVER () means the window is the entire result. PARTITION BY without ORDER BY gives you a group total on every row. ORDER BY without PARTITION BY ranks or accumulates across the whole table.<\/p>\n<h2>The window functions you will actually use<\/h2>\n<p>The table below lists the functions that turn up in analyst work and interviews, grouped by what they do.<\/p>\n<table>\n<thead>\n<tr>\n<th>Function<\/th>\n<th>Family<\/th>\n<th>What it returns<\/th>\n<th>Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>ROW_NUMBER()<\/td>\n<td>Ranking<\/td>\n<td>1, 2, 3, 4 with no ties, ever<\/td>\n<td>ROW_NUMBER() OVER (ORDER BY revenue DESC)<\/td>\n<\/tr>\n<tr>\n<td>RANK()<\/td>\n<td>Ranking<\/td>\n<td>Ties share a rank, then the next rank is skipped (1, 2, 2, 4)<\/td>\n<td>RANK() OVER (ORDER BY revenue DESC)<\/td>\n<\/tr>\n<tr>\n<td>DENSE_RANK()<\/td>\n<td>Ranking<\/td>\n<td>Ties share a rank, no gap after (1, 2, 2, 3)<\/td>\n<td>DENSE_RANK() OVER (ORDER BY revenue DESC)<\/td>\n<\/tr>\n<tr>\n<td>NTILE(n)<\/td>\n<td>Ranking<\/td>\n<td>Splits rows into n roughly equal buckets<\/td>\n<td>NTILE(4) OVER (ORDER BY revenue DESC)<\/td>\n<\/tr>\n<tr>\n<td>SUM, AVG, COUNT, MIN, MAX<\/td>\n<td>Aggregate<\/td>\n<td>The aggregate over the window, on every row<\/td>\n<td>SUM(revenue) OVER (PARTITION BY region)<\/td>\n<\/tr>\n<tr>\n<td>LAG(col, n)<\/td>\n<td>Offset<\/td>\n<td>The value n rows before the current one<\/td>\n<td>LAG(revenue) OVER (ORDER BY month)<\/td>\n<\/tr>\n<tr>\n<td>LEAD(col, n)<\/td>\n<td>Offset<\/td>\n<td>The value n rows after the current one<\/td>\n<td>LEAD(revenue) OVER (ORDER BY month)<\/td>\n<\/tr>\n<tr>\n<td>FIRST_VALUE(col)<\/td>\n<td>Offset<\/td>\n<td>The first value in the window<\/td>\n<td>FIRST_VALUE(rep_name) OVER (PARTITION BY region ORDER BY revenue DESC)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>The data used throughout<\/h2>\n<p>The examples follow one scenario: a Bengaluru D2C skincare brand with seven sales reps across two regions. This is their October revenue, in rupees.<\/p>\n<table>\n<thead>\n<tr>\n<th>rep_name<\/th>\n<th>region<\/th>\n<th>revenue<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Asha<\/td>\n<td>North<\/td>\n<td>420000<\/td>\n<\/tr>\n<tr>\n<td>Bhavesh<\/td>\n<td>North<\/td>\n<td>380000<\/td>\n<\/tr>\n<tr>\n<td>Chitra<\/td>\n<td>North<\/td>\n<td>380000<\/td>\n<\/tr>\n<tr>\n<td>Deepak<\/td>\n<td>North<\/td>\n<td>310000<\/td>\n<\/tr>\n<tr>\n<td>Farah<\/td>\n<td>South<\/td>\n<td>510000<\/td>\n<\/tr>\n<tr>\n<td>Gopal<\/td>\n<td>South<\/td>\n<td>460000<\/td>\n<\/tr>\n<tr>\n<td>Harini<\/td>\n<td>South<\/td>\n<td>460000<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>There are two deliberate ties: Bhavesh and Chitra at 3,80,000, and Gopal and Harini at 4,60,000. Ties are where the three ranking functions stop agreeing.<\/p>\n<h2>RANK vs DENSE_RANK vs ROW_NUMBER<\/h2>\n<p>This is the single most asked window-function question, so here are all three side by side on the same ordering.<\/p>\n<p>Query: SELECT rep_name, revenue, ROW_NUMBER() OVER (ORDER BY revenue DESC, rep_name) AS row_num, RANK() OVER (ORDER BY revenue DESC) AS rnk, DENSE_RANK() OVER (ORDER BY revenue DESC) AS dense_rnk FROM rep_sales<\/p>\n<table>\n<thead>\n<tr>\n<th>rep_name<\/th>\n<th>revenue<\/th>\n<th>row_num<\/th>\n<th>rnk<\/th>\n<th>dense_rnk<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Farah<\/td>\n<td>510000<\/td>\n<td>1<\/td>\n<td>1<\/td>\n<td>1<\/td>\n<\/tr>\n<tr>\n<td>Gopal<\/td>\n<td>460000<\/td>\n<td>2<\/td>\n<td>2<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>Harini<\/td>\n<td>460000<\/td>\n<td>3<\/td>\n<td>2<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>Asha<\/td>\n<td>420000<\/td>\n<td>4<\/td>\n<td>4<\/td>\n<td>3<\/td>\n<\/tr>\n<tr>\n<td>Bhavesh<\/td>\n<td>380000<\/td>\n<td>5<\/td>\n<td>5<\/td>\n<td>4<\/td>\n<\/tr>\n<tr>\n<td>Chitra<\/td>\n<td>380000<\/td>\n<td>6<\/td>\n<td>5<\/td>\n<td>4<\/td>\n<\/tr>\n<tr>\n<td>Deepak<\/td>\n<td>310000<\/td>\n<td>7<\/td>\n<td>7<\/td>\n<td>5<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Read the Asha row. ROW_NUMBER gives her 4 because she is the fourth row. RANK also gives her 4, because two people tied at rank 2 and RANK leaves a gap for them, so rank 3 does not exist. DENSE_RANK gives her 3, because it never leaves gaps: she has the third-highest distinct revenue.<\/p>\n<p>How to choose:<\/p>\n<ul>\n<li><strong>ROW_NUMBER<\/strong> when you need exactly one row per position, for example picking the single latest order per customer. Add a tie-breaker column to the ORDER BY (rep_name above), or the database is free to number tied rows in any order and your result can change between runs.<\/li>\n<li><strong>RANK<\/strong> when the gap carries meaning, as in a sports table: if two people tie for second, nobody came third.<\/li>\n<li><strong>DENSE_RANK<\/strong> when you want the Nth highest distinct value, which is the classic &#8220;find the second highest salary&#8221; interview question. DENSE_RANK equal to 2 answers it correctly even when the top salary is shared.<\/li>\n<\/ul>\n<h2>PARTITION BY: ranking inside each group<\/h2>\n<p>Add PARTITION BY and the ranking restarts for every region. Combined with a CTE, this gives you the top-N-per-group query that every analyst writes weekly.<\/p>\n<p>Query, in two parts. First: WITH ranked AS (SELECT rep_name, region, revenue, DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS region_rank FROM rep_sales). Then: SELECT rep_name, region, revenue, region_rank FROM ranked WHERE region_rank &lt;= 2<\/p>\n<table>\n<thead>\n<tr>\n<th>rep_name<\/th>\n<th>region<\/th>\n<th>revenue<\/th>\n<th>region_rank<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Asha<\/td>\n<td>North<\/td>\n<td>420000<\/td>\n<td>1<\/td>\n<\/tr>\n<tr>\n<td>Bhavesh<\/td>\n<td>North<\/td>\n<td>380000<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>Chitra<\/td>\n<td>North<\/td>\n<td>380000<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>Farah<\/td>\n<td>South<\/td>\n<td>510000<\/td>\n<td>1<\/td>\n<\/tr>\n<tr>\n<td>Gopal<\/td>\n<td>South<\/td>\n<td>460000<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>Harini<\/td>\n<td>South<\/td>\n<td>460000<\/td>\n<td>2<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>You asked for the top two per region and got three in each, because of the ties. That is correct behaviour for DENSE_RANK and RANK. If the business wants exactly two names per region, switch to ROW_NUMBER and decide the tie-breaker deliberately, for example the rep with more orders wins.<\/p>\n<p>Why the CTE? Because you cannot filter on a window function in the WHERE clause of the same query. The database computes window functions after WHERE has already run, so WHERE region_rank &lt;= 2 fails with an error saying the column does not exist or that window functions are not allowed there. Wrap the ranking in a CTE or subquery and filter outside it. Snowflake, BigQuery and Databricks offer a QUALIFY clause that filters window results directly; MySQL, PostgreSQL and SQL Server do not.<\/p>\n<h2>Aggregate window functions: a total on every row<\/h2>\n<p>An aggregate with OVER keeps every row and attaches the aggregate to it. That makes &#8220;what share of the region did each rep bring in&#8221; a one-step query.<\/p>\n<p>Query: SELECT rep_name, region, revenue, SUM(revenue) OVER (PARTITION BY region) AS region_total, ROUND(100.0 * revenue \/ SUM(revenue) OVER (PARTITION BY region), 1) AS pct_of_region FROM rep_sales<\/p>\n<table>\n<thead>\n<tr>\n<th>rep_name<\/th>\n<th>region<\/th>\n<th>revenue<\/th>\n<th>region_total<\/th>\n<th>pct_of_region<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Asha<\/td>\n<td>North<\/td>\n<td>420000<\/td>\n<td>1490000<\/td>\n<td>28.2<\/td>\n<\/tr>\n<tr>\n<td>Bhavesh<\/td>\n<td>North<\/td>\n<td>380000<\/td>\n<td>1490000<\/td>\n<td>25.5<\/td>\n<\/tr>\n<tr>\n<td>Chitra<\/td>\n<td>North<\/td>\n<td>380000<\/td>\n<td>1490000<\/td>\n<td>25.5<\/td>\n<\/tr>\n<tr>\n<td>Deepak<\/td>\n<td>North<\/td>\n<td>310000<\/td>\n<td>1490000<\/td>\n<td>20.8<\/td>\n<\/tr>\n<tr>\n<td>Farah<\/td>\n<td>South<\/td>\n<td>510000<\/td>\n<td>1430000<\/td>\n<td>35.7<\/td>\n<\/tr>\n<tr>\n<td>Gopal<\/td>\n<td>South<\/td>\n<td>460000<\/td>\n<td>1430000<\/td>\n<td>32.2<\/td>\n<\/tr>\n<tr>\n<td>Harini<\/td>\n<td>South<\/td>\n<td>460000<\/td>\n<td>1430000<\/td>\n<td>32.2<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>With GROUP BY region you would get two rows and lose the reps. To get this without a window function you would need a subquery joined back to the table, which is longer and easier to get wrong. Note the 100.0 rather than 100: in SQL Server and PostgreSQL, an integer divided by an integer is an integer, and every percentage would come out as 0.<\/p>\n<h2>Running totals, LAG and moving averages<\/h2>\n<p>The second big use of window functions is time series. Here is the brand&#8217;s monthly revenue for four months.<\/p>\n<table>\n<thead>\n<tr>\n<th>month<\/th>\n<th>revenue<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>2026-07<\/td>\n<td>1240000<\/td>\n<\/tr>\n<tr>\n<td>2026-08<\/td>\n<td>1310000<\/td>\n<\/tr>\n<tr>\n<td>2026-09<\/td>\n<td>1185000<\/td>\n<\/tr>\n<tr>\n<td>2026-10<\/td>\n<td>1460000<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>One query gives a running total, the previous month&#8217;s figure, the change, and a three-month moving average. Each clause is on its own row so you can read it:<\/p>\n<table>\n<thead>\n<tr>\n<th>Column<\/th>\n<th>Expression<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>running_total<\/td>\n<td>SUM(revenue) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)<\/td>\n<\/tr>\n<tr>\n<td>prev_month<\/td>\n<td>LAG(revenue) OVER (ORDER BY month)<\/td>\n<\/tr>\n<tr>\n<td>change<\/td>\n<td>revenue &#8211; LAG(revenue) OVER (ORDER BY month)<\/td>\n<\/tr>\n<tr>\n<td>moving_avg_3m<\/td>\n<td>AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<table>\n<thead>\n<tr>\n<th>month<\/th>\n<th>revenue<\/th>\n<th>running_total<\/th>\n<th>prev_month<\/th>\n<th>change<\/th>\n<th>moving_avg_3m<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>2026-07<\/td>\n<td>1240000<\/td>\n<td>1240000<\/td>\n<td>NULL<\/td>\n<td>NULL<\/td>\n<td>1240000<\/td>\n<\/tr>\n<tr>\n<td>2026-08<\/td>\n<td>1310000<\/td>\n<td>2550000<\/td>\n<td>1240000<\/td>\n<td>70000<\/td>\n<td>1275000<\/td>\n<\/tr>\n<tr>\n<td>2026-09<\/td>\n<td>1185000<\/td>\n<td>3735000<\/td>\n<td>1310000<\/td>\n<td>-125000<\/td>\n<td>1245000<\/td>\n<\/tr>\n<tr>\n<td>2026-10<\/td>\n<td>1460000<\/td>\n<td>5195000<\/td>\n<td>1185000<\/td>\n<td>275000<\/td>\n<td>1318333<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>LAG returns NULL for July because there is no earlier row. If you want 0 instead, LAG takes a default as its third argument: LAG(revenue, 1, 0). The moving average for July and August is built from fewer than three months because there are not three months yet; decide whether to show those rows or filter them out before you put the number on a dashboard.<\/p>\n<p>LEAD is the same as LAG in the other direction. It is useful for &#8220;days until the customer&#8217;s next order&#8221; when you order by order_date within PARTITION BY customer_id.<\/p>\n<h2>The frame clause, and the running-total trap<\/h2>\n<p>The frame decides which rows the function sees. You can skip it most of the time, but the default is the cause of a well-known bug.<\/p>\n<table>\n<thead>\n<tr>\n<th>Frame<\/th>\n<th>Rows used<\/th>\n<th>Typical use<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<\/td>\n<td>Everything from the first row up to this one<\/td>\n<td>Running total<\/td>\n<\/tr>\n<tr>\n<td>ROWS BETWEEN 2 PRECEDING AND CURRENT ROW<\/td>\n<td>This row and the two before<\/td>\n<td>Three-period moving average<\/td>\n<\/tr>\n<tr>\n<td>ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING<\/td>\n<td>The whole partition<\/td>\n<td>LAST_VALUE that actually returns the last value<\/td>\n<\/tr>\n<tr>\n<td>RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<\/td>\n<td>Up to this row, including every row tied with it<\/td>\n<td>The default when ORDER BY is present<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The trap: if you write SUM(revenue) OVER (ORDER BY revenue) with no frame, the default is RANGE, not ROWS. RANGE treats tied rows as one step, so Bhavesh and Chitra, both at 3,80,000, would show the same running total, including each other&#8217;s revenue. A daily running total ordered by order_date has the same problem whenever two orders share a date. Write ROWS explicitly whenever you mean row by row.<\/p>\n<p>The same default explains why LAST_VALUE so often returns the current row&#8217;s value instead of the last one. With ORDER BY and the default frame, the window ends at the current row. Give it ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or use FIRST_VALUE with the order reversed.<\/p>\n<h2>Where MySQL, PostgreSQL and SQL Server differ<\/h2>\n<p>Window functions are standard SQL and the syntax above runs on all three, with a few differences worth knowing before an interview or a migration.<\/p>\n<table>\n<thead>\n<tr>\n<th>Point<\/th>\n<th>MySQL<\/th>\n<th>PostgreSQL<\/th>\n<th>SQL Server<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Support<\/td>\n<td>From version 8.0; MySQL 5.7 has none<\/td>\n<td>Since 8.4<\/td>\n<td>Ranking since 2005; full frames since 2012<\/td>\n<\/tr>\n<tr>\n<td>QUALIFY to filter ranks<\/td>\n<td>No<\/td>\n<td>No<\/td>\n<td>No<\/td>\n<\/tr>\n<tr>\n<td>Integer division in pct<\/td>\n<td>Returns a decimal<\/td>\n<td>Truncates to integer<\/td>\n<td>Truncates to integer<\/td>\n<\/tr>\n<tr>\n<td>Named windows (WINDOW w AS &#8230;)<\/td>\n<td>Yes<\/td>\n<td>Yes<\/td>\n<td>From SQL Server 2022<\/td>\n<\/tr>\n<tr>\n<td>FILTER clause on aggregates<\/td>\n<td>No<\/td>\n<td>Yes<\/td>\n<td>No<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The MySQL version point matters in India more than you would expect. Plenty of company databases and shared hosting setups still run 5.7, and on those the queries in this article fail outright. The workaround there is a self-join or a correlated subquery, which is exactly why window functions were added.<\/p>\n<h2>Mistakes that produce wrong answers<\/h2>\n<p><strong>Using ROW_NUMBER without a tie-breaker.<\/strong> Two rows with the same value get numbers 2 and 3 in an order the database chooses, and that order can change. Your &#8220;latest order per customer&#8221; picks a different order next week.<\/p>\n<p><strong>Filtering the rank in WHERE.<\/strong> It errors in MySQL, PostgreSQL and SQL Server. Rank in a CTE, filter outside.<\/p>\n<p><strong>Forgetting PARTITION BY.<\/strong> A rank that should restart per city runs across the whole country instead, and every city after the first starts at some number other than 1.<\/p>\n<p><strong>Trusting the default frame for running totals.<\/strong> RANGE groups ties together. Use ROWS.<\/p>\n<p><strong>Reaching for GROUP BY when you need the detail rows.<\/strong> If the answer needs both the individual row and its group&#8217;s total, that is a window function, not GROUP BY and a join back.<\/p>\n<p>Window functions build directly on aggregates and on GROUP BY, so if PARTITION BY still feels slippery, get comfortable with grouping first. Joins come up constantly alongside them; our guide to <a href=\"https:\/\/www.skillovilla.com\/blogs\/sql-joins\">SQL joins<\/a> uses the same style of worked examples. For how these questions are framed in hiring rounds, see the advanced section of our <a href=\"https:\/\/www.skillovilla.com\/blogs\/sql-interview-questions\">SQL interview questions<\/a>.<\/p>\n<h2>Frequently asked questions<\/h2>\n<h3>What is a window function in SQL?<\/h3>\n<p>A window function performs a calculation across a set of rows that are related to the current row, and returns the result on every row rather than collapsing them. It is written with the OVER clause, for example SUM(revenue) OVER (PARTITION BY region). Ranking, running totals, moving averages and comparisons with the previous row are all done with window functions.<\/p>\n<h3>What is the difference between RANK and DENSE_RANK?<\/h3>\n<p>Both give tied rows the same rank. RANK then skips the following numbers, so a tie for second place is followed by fourth. DENSE_RANK does not skip, so the next row is third. Use DENSE_RANK when you want the Nth highest distinct value, such as the second highest salary.<\/p>\n<h3>What is the difference between ROW_NUMBER and RANK?<\/h3>\n<p>ROW_NUMBER gives every row a unique number even when values tie, so two equal salaries get 1 and 2. RANK gives tied rows the same number. Use ROW_NUMBER when you need exactly one row per position, such as removing duplicates or picking the latest record per customer, and always add a tie-breaker to its ORDER BY.<\/p>\n<h3>What is the difference between GROUP BY and PARTITION BY?<\/h3>\n<p>GROUP BY collapses rows, returning one row per group. PARTITION BY, used inside a window function, divides rows into groups for the calculation but keeps every original row in the result. If you need each order alongside its customer&#8217;s total, use PARTITION BY.<\/p>\n<h3>Can I use a window function in the WHERE clause?<\/h3>\n<p>No. Window functions are evaluated after WHERE, GROUP BY and HAVING, so the value does not exist yet when WHERE runs. Compute the window function inside a CTE or subquery, then filter on it in the outer query. Some cloud warehouses such as Snowflake and BigQuery provide QUALIFY for this, but MySQL, PostgreSQL and SQL Server do not.<\/p>\n<h3>Does MySQL support window functions?<\/h3>\n<p>Yes, from MySQL 8.0 onwards. MySQL 5.7 and earlier have no window functions, so ROW_NUMBER, RANK and the OVER clause all fail there. Check your version with SELECT VERSION() before debugging a query that looks correct.<\/p>\n<h2>Practise window functions on real data<\/h2>\n<p>Window functions read easily and go wrong quietly, through a missing tie-breaker or a default frame nobody noticed. The way to get them right is to write a lot of them against real tables and have someone point out why a running total is off by a tied row.<\/p>\n<p>SkilloVilla&#8217;s <a href=\"https:\/\/www.skillovilla.com\/courses\/sql-beginner-to-advanced\">SQL: Beginner to Advanced course<\/a> goes from the fundamental statements through aggregation, joins and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. If you want SQL as part of a full analyst path with Python and placement support, look at the <a href=\"https:\/\/www.skillovilla.com\/tracks\/data-analytics-python\">Data Analytics with Python track<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>SQL window functions explained with examples: RANK vs DENSE_RANK vs ROW_NUMBER, PARTITION BY, running totals, LAG and LEAD, and moving averages.<\/p>\n","protected":false},"author":27,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[200],"tags":[],"class_list":["post-3993","post","type-post","status-publish","format-standard","hentry","category-data-analytics"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v23.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More\" \/>\n<meta property=\"og:description\" content=\"SQL window functions explained with examples: RANK vs DENSE_RANK vs ROW_NUMBER, PARTITION BY, running totals, LAG and LEAD, and moving averages.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions\" \/>\n<meta property=\"og:site_name\" content=\"SkilloVilla\" \/>\n<meta property=\"article:published_time\" content=\"2026-11-23T16:16:59+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-23T17:21:51+00:00\" \/>\n<meta name=\"author\" content=\"SkilloVilla Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"SkilloVilla Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions\"},\"author\":{\"name\":\"SkilloVilla Team\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943\"},\"headline\":\"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More\",\"datePublished\":\"2026-11-23T16:16:59+00:00\",\"dateModified\":\"2026-11-23T17:21:51+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions\"},\"wordCount\":2399,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#organization\"},\"articleSection\":[\"Data analytics\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions\",\"name\":\"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More\",\"isPartOf\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#website\"},\"datePublished\":\"2026-11-23T16:16:59+00:00\",\"dateModified\":\"2026-11-23T17:21:51+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.skillovilla.com\/blogs\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#website\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/\",\"name\":\"SkilloVilla\",\"description\":\"Data careers, taught live\",\"publisher\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.skillovilla.com\/blogs\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#organization\",\"name\":\"SkilloVilla\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png\",\"contentUrl\":\"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png\",\"width\":1200,\"height\":627,\"caption\":\"SkilloVilla\"},\"image\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943\",\"name\":\"SkilloVilla Team\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g\",\"caption\":\"SkilloVilla Team\"},\"url\":\"https:\/\/www.skillovilla.com\/blogs\/author\/sankalp_agarwal\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions","og_locale":"en_US","og_type":"article","og_title":"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More","og_description":"SQL window functions explained with examples: RANK vs DENSE_RANK vs ROW_NUMBER, PARTITION BY, running totals, LAG and LEAD, and moving averages.","og_url":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions","og_site_name":"SkilloVilla","article_published_time":"2026-11-23T16:16:59+00:00","article_modified_time":"2026-11-23T17:21:51+00:00","author":"SkilloVilla Team","twitter_card":"summary_large_image","twitter_misc":{"Written by":"SkilloVilla Team","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#article","isPartOf":{"@id":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions"},"author":{"name":"SkilloVilla Team","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943"},"headline":"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More","datePublished":"2026-11-23T16:16:59+00:00","dateModified":"2026-11-23T17:21:51+00:00","mainEntityOfPage":{"@id":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions"},"wordCount":2399,"commentCount":0,"publisher":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#organization"},"articleSection":["Data analytics"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions","url":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions","name":"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More","isPartOf":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#website"},"datePublished":"2026-11-23T16:16:59+00:00","dateModified":"2026-11-23T17:21:51+00:00","breadcrumb":{"@id":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.skillovilla.com\/blogs\/sql-window-functions"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.skillovilla.com\/blogs\/sql-window-functions#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.skillovilla.com\/blogs"},{"@type":"ListItem","position":2,"name":"SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More"}]},{"@type":"WebSite","@id":"https:\/\/www.skillovilla.com\/blogs\/#website","url":"https:\/\/www.skillovilla.com\/blogs\/","name":"SkilloVilla","description":"Data careers, taught live","publisher":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.skillovilla.com\/blogs\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.skillovilla.com\/blogs\/#organization","name":"SkilloVilla","url":"https:\/\/www.skillovilla.com\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png","contentUrl":"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png","width":1200,"height":627,"caption":"SkilloVilla"},"image":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943","name":"SkilloVilla Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g","caption":"SkilloVilla Team"},"url":"https:\/\/www.skillovilla.com\/blogs\/author\/sankalp_agarwal"}]}},"_links":{"self":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts\/3993","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/users\/27"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/comments?post=3993"}],"version-history":[{"count":2,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts\/3993\/revisions"}],"predecessor-version":[{"id":4066,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts\/3993\/revisions\/4066"}],"wp:attachment":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/media?parent=3993"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/categories?post=3993"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/tags?post=3993"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}