Skip to content
Advertisement

SQL paging with non-fixed-length page size

The table is simple: It has 2 columns, id and type. The type can be 1 or 2.
Now I want the first 10 entries with type 1, in a sequence ordered by id, and if there are type 2 entries somewhere in between then they should be included in the result set too. What is the SQL query?

It’s basically paging but the number of rows per page can vary so can’t use OFFSET and LIMIT.

Advertisement

Answer

For SQL Server you can use CTE to make request for type 1 records once and then union with records of Type 2.

I selected only 5 rows to use less test data.

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