Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

sql server - What does "ORDER BY (SELECT NULL)" mean?

The following SQL is from Itzik Ben-Gan that is used to generate a numbers table. What does the order by (select null) part mean? Thanks.

DECLARE @number_of_numbers INT;
SELECT @number_of_numbers = 100000;

WITH    a AS ( SELECT   1 AS i
               UNION ALL
               SELECT   1
             ),
        b AS ( SELECT   1 AS i
               FROM     a AS x ,
                        a AS y
             ),
        c AS ( SELECT   1 AS i
               FROM     b AS x ,
                        b AS y
             ),
        d AS ( SELECT   1 AS i
               FROM     c AS x ,
                        c AS y
             ),
        e AS ( SELECT   1 AS i
               FROM     d AS x ,
                        d AS y
             ),
        f AS ( SELECT   1 AS i
               FROM     e AS x ,
                        e AS y
             ),
        numbers
          AS ( SELECT TOP ( @number_of_numbers )
                        ROW_NUMBER() OVER ( ORDER BY ( SELECT   NULL
                                                     ) ) AS number
               FROM     f
             )
    SELECT  *
    FROM    numbers;

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ROW_NUMBER requires an ORDER BY clause syntactically. You cannot use it without one. SELECT NULL is a hack to shut up the error while not enforcing any particular order. In this case we don't need to enforce any order, so the fastest option is to use SELECT NULL.

The optimizer sees through this trick, so it has no runtime cost (this claim is easily verified by looking at the execution plan).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...