views:

155

answers:

4

In SQL server I can say:

Select top 50 percent

How can I say bottom 50 percent?

EDIT - for the sake of an interesting question, if we assume he has a table with a primary key but wants the bottom 50% ordered in ascending primary key order. What would be the most efficient way of achieving that?

+7  A: 

why not just change the sort order and keep TOP. Wouldn't that accomplish the same thing?

Cody C
+8  A: 
    SELECT * FROM
    (
        SELECT TOP 50 PERCENT *

        FROM [Table]

        ORDER BY [Field] DESC
   )
   ORDER BY [Field] ASC
Developer Art
Funny you got no credit for providing solution which returns the bottom half in the original sorting order. +1 from me.
mjv
+1 for providing the solution to the extension of the question I was adding *before I had completed it* :-)
Cruachan
50 minutes later: Wow! The answer made up for lost time ;-), 7 reps for this is now... well "paid". Funny to see the dynamics of all this.
mjv
A: 

Your question as stated is technically meaningless because without an order by clause the order in which your data is returned is undefined (in practice most databases will return in primary key order, or if you don't have a primary key then in insertion order, but that is not guaranteed)

Assuming however you have an order by clause but just haven't included it, just would use DESC instead of ASC.

Cruachan
A: 

I dunno whether this would work:

SELECT * FROM <table> EXCEPT TOP 50 PERCENT...;

And I'm pretty sure something like this would be OK too:

SELECT * FROM <table> WHERE (ID NOT IN (SELECT TOP 50 PERCENT ...));

Just check the syntax, as I'm only beginning to learn SQL and can't form correct queries without modifying the a million times first ;)

mingos

related questions