Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 'FETCH FIRST 1 ROWS ONLY' Invalid usage

I am trying to convert a Db2 query to SQL Server, I came across a construct I am not familiar with: FETCH FIRST 1 ROWS ONLY.

This is the query working on db2:

select * from products.series where state = 'xxx' order by id 
FETCH FIRST 1 ROWS ONLY

and the error I am getting on SQL Server:

Invalid usage of the option FIRST in the FETCH statement.

I have tried replacing FIRST with NEXT which seems to be admitted in SQL Server, but with no success.

I am using SQL Sever 2014

like image 745
Argentina Avatar asked Apr 26 '17 15:04

Argentina


People also ask

What is SQL offset 1?

Offset in SQL is used to eliminate a set of records from a given table in a database in order to retrieve a set of records according to the requirement of the database. Basically, it is used to find a starting point to display a set of rows as a final output.

What is offset fetch in SQL?

OFFSET and FETCH Clause are used in conjunction with SELECT and ORDER BY clause to provide a means to retrieve a range of records. OFFSET. The OFFSET argument is used to identify the starting point to return rows from a result set. Basically, it exclude the first set of records.

What is SQL offset 0?

When OFFSET is 0, then no rows are skipped. If OFFSET is greater than the number of rows in the ordered results, then no rows are returned.

How do I select the last row in SQL?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table.


2 Answers

Try with OFFSET clause

select * from products.series where state = 'xxx' order by id 
OFFSET 0 ROWS
FETCH NEXT 1 ROWS ONLY
like image 138
Oto Shavadze Avatar answered Oct 03 '22 18:10

Oto Shavadze


use top:

select top 1 * from products.series where state = 'xxx' order by id 
like image 43
SqlZim Avatar answered Oct 03 '22 16:10

SqlZim