0

So I can paginate a query with LIMIT and OFFSET

SELECT * 
FROM db.table
LIMIT 6
OFFSET 0

But if I try to ORDER BY this result I get the first n ordered rows, not the first n rows ordered.

SELECT * 
FROM db.table
LIMIT 6
OFFSET 0
ORDER BY first_name COLLATE NOCASE

So instead of

bob
charles
dave
dan
doug
durrand

I want to get

bob
doug
elliot
manny
ralph
xavier
Community
  • 1
  • 1
Daniel Lizik
  • 3,058
  • 2
  • 20
  • 42

2 Answers2

2

You want a subquery:

SELECT t.*
FROM (SELECT * 
      FROM db.table
      LIMIT 6 OFFSET 0
     ) t
ORDER BY first_name COLLATE NOCASE;

Note that this actually returns an indeterminate set of rows, which is then ordered.

Unless you use order by, then you are not necessarily guaranteed that the same set of rows is returned.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

"First n rows" doesn't make sense in this context. Tables don't have an intrinsic order; you have to specify it. Usually this is done with some ID column that increments automatically to track the order of insertion (which is probably what you mean).

You're specifying the order in your ORDER BY clause, which is why it's ordering that way. If you have an ID column, however, you can do a subselect like:

select name from (
    select name from foo
    order by id
    limit...
) order by name
BJ Black
  • 2,483
  • 9
  • 15