Question

SQL SERVER: How can I enumerate the rows of a select statement with union operator, but without restarting the count, without duplicity and without subselect? Is it possible? I need something with performance. I got it with subselect and the function ROW_NUMBER(), but I need something faster. Any idea? Thanks!

Was it helpful?

Solution

This is the fastest that I can think of:

select t.*, row_number() over (order by (select NULL)) as seqnum
from ((select * from A) union all
      (select * from B)
     ) t;

Two things. First this uses union all rather than union -- so duplicates are not removed. This speeds up the query if duplicate removal is not necessary.

Second, it uses order by (select NULL)). In my experience, this seems to assign a sequential number on output without actually incurring the overhead of a sort. This is strictly based on my experience. I have not yet found SQL Server documentation that explains this. But, I have used it in the past successfully.

OTHER TIPS

If you are using SQL Server 2012+, you could try this:

DECLARE @T TABLE (col1 INT, col2 INT);

INSERT INTO @T
VALUES (1, 2), (3, 4), (5, 6);

SELECT COUNT(*) OVER (
        ORDER BY col1 ROWS UNBOUNDED PRECEDING
        ) RN, col1, col2
FROM @T
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top