SQL Puzzle.. Sorting results without using ORDER BY
http://blogs.lessthandot.com/index.php/datamgmt/dbprogramming/mssqlserver/sql-puzzle-sorting-results-without/
CREATE TABLE Puzzle (Col1 varchar(20) NOT NULL PRIMARY KEY CLUSTERED, Col2 varchar(20) NOT NULL UNIQUE NONCLUSTERED); INSERT INTO Puzzle (Col1, Col2) SELECT 'Z', 'AA' UNION ALL SELECT 'A', 'BB' UNION ALL SELECT 'B', 'CC' UNION ALL SELECT 'C', 'DD' UNION ALL SELECT 'M', 'EE'; SELECT Col1 FROM Puzzle; DROP TABLE Puzzle; |
you get these results
Col1
Z
A
B
C
M
Z
A
B
C
M
What I want to see is the following
Col1
A
B
C
M
Z
A
B
C
M
Z
Without using ORDER BY, how would you make the SELECT query return Col1 in ascending order? You can’t make changes to the table, all that you are allowed to modify is this part
SELECT TOP 5 p1.col1 FROM Puzzle p1 INNER JOIN Puzzle p2 ON p1.col1 <> p2.col2
SELECT Col1 FROM Puzzle WITH(INDEX(1));
If a clustered index exists, INDEX(0) forces a clustered index scan and INDEX(1) forces a clustered index scan or seek. If no clustered index exists, INDEX(0) forces a table scan and INDEX(1) is interpreted as an error.
select Col1 from Puzzle a
union
select Col1 from Puzzle b
union
select Col1 from Puzzle b
No comments:
Post a Comment