Microsoft SQL Server, PostgreSQL, SQL

PostgreSQL и MSSQLServer: Ограничение количества отображаемых строк выборки

Вывести первые 100 строк запроса:

[pastacode lang=»sql» manual=»select%20*%20from%20table_name%0Aorder%20by%20id%0Alimit%20100″ message=»PostgreSQL limit» highlight=»3″ provider=»manual»/]

[pastacode lang=»sql» manual=»select%20*%20from%20table_name%20%0Afetch%20next%20100%20rows%20only» message=»PostgreSQL fetch» highlight=»2″ provider=»manual»/]

[pastacode lang=»sql» manual=»select%20*%20from%20table_name%0Aorder%20by%20id%0Aoffset%200%20rows%20fetch%20next%20100%20rows%20only» message=»Microsoft SQL Server offset…fetch» highlight=»3″ provider=»manual»/]

Вывести 100 строк выборки, пропустив 20 строк:

[pastacode lang=»sql» manual=»select%20*%20from%20table_name%0Aorder%20by%20id%0Alimit%20100%20offset%2020″ message=»PostgreSQL limit…offset» highlight=»3″ provider=»manual»/]

[pastacode lang=»sql» manual=»select%20*%20from%20table_name%20%0Aoffset%2020%20rows%20fetch%20next%20100%20rows%20only» message=»PostgreSQL offset…fetch» highlight=»2″ provider=»manual»/]

[pastacode lang=»sql» manual=»select%20*%20from%20table_name%0Aorder%20by%20id%0Aoffset%2020%20rows%20fetch%20next%20100%20rows%20only» message=»Microsoft SQL Server offset…fetch» highlight=»3″ provider=»manual»/]

Стоит отметить, что для использования предложения OFFSET и FETCH в MSSQLServer требуется ORDER BY. В PostgreSQL — нет. В MS SQL Server использование offset без fetch запрещено. В PostgreSQL — нет.

Для ограничения количества выводимых строк без сдвига для Microsoft SQL Server можно воспользоваться оператором top:

[pastacode lang=»sql» manual=»select%20top%20100%20*%0Afrom%20table_name%0Aorder%20by%20id» message=»Microsoft SQL Server top» highlight=»1″ provider=»manual»/]

Документация: PostgreSQL, MSSQLServer (offset…fetch, top).