Skip to content
Advertisement

Is it possible to select multiple offsets with SQL

I’d like to select multiple offsets with a single SELECT SQL query. Is this possible?

For example, let’s say I have a table of non-continuous dates called dates.

I’d like to select the 1st, 4th and 7th offsets from the most recent date. In this example, the query should return:

Ideally, I would like to write the query as follows:

Obviously, this does not compile due to the LIMIT/OFFSET clause.

I could try a UNION, but not only is this extremely verbose it does not work because the LIMIT/OFFSET clause must come after the last UNION.

FAIL:

Is there an elegant query to do this? The other option I can think of is to use row_number() with a window function, and then do something like SELECT * WHERE row_number IN (1, 4, 7). HOWEVER, in some cases I am forced to use an older version of SQLite that does not support window functions.

Advertisement

Answer

For earlier version of SQLite you can use a correlated query in the WHERE clause:

See the demo.
Results:

If you also want the offset column:

See the demo.
Results:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement