SQLite Window Functions
What are Window Functions?
GROUP BY puts many rows together into one row. A window function also calculates from many rows, but every row stays in the result.
This example shows each product, with the average price of its category:
Example
SELECT ProductName, CategoryID, Price,
AVG(Price) OVER (PARTITION BY CategoryID)
AS CategoryAverage
FROM Products;
Try it Yourself »
These are the parts of a window function:
OVERmakes a function a window functionPARTITION BYsplits the rows into groups. Without it, all the rows are one groupORDER BYsets the order of the rows in each group
Note: Window functions work in SQLite 3.25.0 and later.
ROW_NUMBER()
ROW_NUMBER() gives each row a number. This example numbers the products from the most expensive:
Example
SELECT ROW_NUMBER() OVER (ORDER BY Price DESC)
AS Place, ProductName, Price
FROM Products;
Try it Yourself »
RANK() and DENSE_RANK()
RANK() gives rows with the same value the same number, and then skips numbers. DENSE_RANK() does not skip numbers:
Example
SELECT ProductName, Price,
RANK() OVER (ORDER BY Price DESC) AS Rnk,
DENSE_RANK() OVER (ORDER BY Price DESC) AS DenseRnk
FROM Products;
Try it Yourself »
Number Each Group
With PARTITION BY, the numbering starts again in each category:
Example
SELECT CategoryID, ProductName, Price,
ROW_NUMBER() OVER (
PARTITION BY CategoryID
ORDER BY Price DESC
) AS PlaceInCategory
FROM Products;
Try it Yourself »
Running Total
SUM() with ORDER BY in the window gives a running total. Each row shows the sum of all the rows up to that row:
Example
SELECT OrderDetailID, Quantity,
SUM(Quantity) OVER (ORDER BY OrderDetailID)
AS RunningTotal
FROM OrderDetails;
Try it Yourself »
LAG() and LEAD()
LAG() gets a value from the row before, and LEAD() from the row after. This example shows each order with the date of the order before it:
Example
SELECT OrderID, OrderDate,
LAG(OrderDate) OVER (ORDER BY OrderID)
AS PreviousOrderDate
FROM Orders;
Try it Yourself »
Top 2 in Each Category
Together with a CTE, window functions can find the top rows in each group. This example finds the two most expensive products in each category:
Example
WITH Ranked AS (
SELECT CategoryID, ProductName, Price,
ROW_NUMBER() OVER (
PARTITION BY CategoryID
ORDER BY Price DESC
) AS Place
FROM Products
)
SELECT * FROM Ranked
WHERE Place <= 2;
Try it Yourself »
Tip: See all the window functions in our SQLite Functions Reference.