📜  ms sql skip take - SQL (1)

📅  最后修改于: 2023-12-03 15:17:44.520000             🧑  作者: Mango

Introduction to MS SQL-server - SKIP and TAKE

Overview

MS SQL-server is a relational database management system developed by Microsoft. It provides various features to manipulate and retrieve data. The SKIP and TAKE operators are used to control the result set returned by a query. SKIP is used to skip a specific number of rows from the beginning of the result set, while TAKE is used to retrieve a specific number of rows from the result set.

Syntax

The syntax for using SKIP and TAKE in MS SQL-server is as follows:

SELECT column1, column2, ...
FROM table
ORDER BY columnX
OFFSET skipRows ROWS
FETCH NEXT takeRows ROWS ONLY;
  • column1 and column2 are the columns that you want to retrieve.
  • table is the table from which you want to retrieve the data.
  • columnX is the column used for sorting, if required.
  • skipRows is the number of rows to skip.
  • takeRows is the number of rows to retrieve.
Examples
Example 1: Retrieve the first 10 records from a table
SELECT *
FROM employees
ORDER BY employee_id
FETCH NEXT 10 ROWS ONLY;
Example 2: Retrieve the 11th to 20th records from a table
SELECT *
FROM employees
ORDER BY employee_id
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;
Example 3: Retrieve the top 5 highest paid employees
SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC
FETCH NEXT 5 ROWS ONLY;
Example 4: Retrieve all records excluding the first 5 rows
SELECT *
FROM employees
ORDER BY employee_id
OFFSET 5 ROWS;
Conclusion

The SKIP and TAKE operators in MS SQL-server are useful for controlling the result set returned by a query. They allow you to skip a given number of rows and retrieve a specific number of rows from the result set. These operators are commonly used in pagination and result set manipulation scenarios.