Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip first row in SQL Server 2005?

We can select Top 10 or Select Top 'N' row from SQL Server.

But is there any way to skip first row from the result of top??

I mean I get result from select top 5, then I skip the first row and get only next 4 rows?

like image 481
Abhishek Ranjan Avatar asked Aug 21 '11 11:08

Abhishek Ranjan


People also ask

How do I skip the first row in SQL Server?

The OFFSET FETCH clause allows you to skip N first rows in a result set before starting to return any rows. In this syntax: The ROW and ROWS , FIRST and NEXT are the synonyms. Therefore, you can use them interchangeably.

How do you skip a line in SQL?

We can use the following ASCII codes in SQL Server: Char(10) – New Line / Line Break. Char(13) – Carriage Return. Char(9) – Tab.

How do I SELECT all rows to except the first row in SQL?

The SQL EXCEPT operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The EXCEPT operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.

How do I limit the first 5 rows in SQL?

Example - Using LIMIT keywordSELECT contact_id, last_name, first_name FROM contacts WHERE website = 'TechOnTheNet.com' ORDER BY contact_id DESC LIMIT 5; This SQL SELECT LIMIT example would select the first 5 records from the contacts table where the website is 'TechOnTheNet.com'.


1 Answers

You can use OVER clause and a ranking function. You can't filter on this directly so you need to us a sub query or a common table expression, the example below uses the latter.

DECLARE @MyTable TABLE 
(
    ID INT,
    Name VARCHAR(15)
);
INSERT INTO @MyTable VALUES (1, 'Alice');
INSERT INTO @MyTable VALUES (2, 'Bob');
INSERT INTO @MyTable VALUES (3, 'Chris');
INSERT INTO @MyTable VALUES (4, 'David');
INSERT INTO @MyTable VALUES (5, 'Edgar');

WITH people AS 
(
    SELECT ID, Name, ROW_NUMBER() OVER (ORDER BY ID) RN
    FROM @MyTable
)
SELECT ID, Name
FROM people
WHERE RN > 1;

There will be better support for pagination in the next version of SQL Server (codename Denali) with the OFFSET and FETCH keywords.

like image 101
Chris Diver Avatar answered Oct 30 '22 16:10

Chris Diver