In this lesson, you will learn how to attach a temporary, unique sequence number to each row of your query results to help with auditing or front-end display.
Why Generate Identifiers on the Fly?
Sometimes, the data you pull from a database doesn't include a clean, sequential ID (like 1, 2, 3...). Perhaps you are pulling a filtered list of products, or you are joining several tables together and need a temporary reference number to help your front-end application keep track of the rows.
Since SQL is a set-based language, it doesn’t automatically assign a row number to every query result. To do this, we use a Window Function called ROW_NUMBER().
How it Works
A window function performs a calculation across a set of rows related to the current row. Think of ROW_NUMBER() as a counter that clicks up by one for every record it processes.
To use it, you must pair it with the OVER clause, which dictates the "window" or the order in which the numbers are assigned. Because SQL tables are sets without a natural order, you must use ORDER BY inside the OVER clause to ensure the numbers are assigned consistently.
SELECT
ROW_NUMBER() OVER (ORDER BY product_name) AS temp_id,
product_name,
price
FROM products
WHERE price > 50;
Breaking Down the Code
ROW_NUMBER(): This is the function that generates the unique integer for every row returned.OVER (ORDER BY product_name): This tells the database, "Sort these rows by the product name first, and then assign the number 1 to the first row, 2 to the second, and so on."AS temp_id: Since this generated column doesn't exist in your table, we use an alias to give it a readable name for your application or report.
Note that temp_id is volatile. If you run this query again, the numbers might change if the underlying data changes or if you change the ORDER BY criteria. This is why we call these "temporary" identifiers—they exist only for the duration of that specific query execution.
Key Takeaway: Use the ROW_NUMBER() OVER (ORDER BY ...) window function to dynamically assign unique, sequential identifiers to your result sets for easier auditing and tracking.