ksssssq
ksssssq

Reputation: 33

SQL offset only

Is it possible to skip X first rows, and select all the other rows in one query? Like that:

abc
def
ghi
jkl
mno
========= start selecting all from here =========
pqr
stu
vwx
yz

And it will select: pqr, stu, vwx, yz

I've tried to accomplish that with LIMIT and OFFSET, but the problem is that the table is dynamic, and I don't know which LIMIT should I put (I don't know how many rows in the table).

Upvotes: 3

Views: 5399

Answers (1)

JYelton
JYelton

Reputation: 36512

If you just want the last N rows, try this:

SELECT field1, field2 FROM table
ORDER BY some_column DESC
LIMIT N;

This gives you the last few records based on the order of some_column.

You can use an auto-incrementing primary key (hopefully there is one) to establish the order of the rows if nothing else can be used.

If instead you want to skip the first X rows (which you indicate in the question) and get all rows until the end, try this:

SELECT field1, field2 FROM table
ORDER BY some_column ASC
LIMIT 18446744073709551615 OFFSET X;

For this latter case, see: MySQL Offset Infinite Rows

Though, if you do have an auto-incrementing primary key, and it corresponds with the rows you want to select, I recommend:

SELECT field1, field2 FROM table
WHERE id > X;

Upvotes: 8

Related Questions