5

I have this table in SQL Server:

ID   | videoid  | title
=========================
1    | id1      | title1
2    | id2      | title2
3    | id3      | title3

And I want to create select method that search in the title row with:

SELECT * FROM [movie].[dbo].[movies] 
WHERE title like '%' + '%s' + '%'

And I'm looking for something like Limit in MySQL that from the SELECT results I will be able to get the 0-20,21-40,41-60 results.

Any help with this query?

I tried to use LIMIT 0, 10 and I received this error:

Could not find stored procedure 'LIMIT'.
7
  • Also, you've got one too many '%', I think. Commented Mar 17, 2014 at 13:07
  • What is your goal with this sql and where are you planning to use it? Commented Mar 17, 2014 at 13:08
  • 1
    possible duplicate of SQL Server paging query Commented Mar 17, 2014 at 13:16
  • @RaimondKuipers I want to build webservice that get search string and return results from the sql database. but i want to return every time 20 results and not all the results. Commented Mar 17, 2014 at 13:16
  • @MTA, are you going to return 20 results every time or you want to returned result based on paging like 0-20 for the first call, then 20-40 for the second ? Commented Mar 17, 2014 at 13:28

6 Answers 6

6

You need to use TOP N with SQL SERVER.

SELECT TOP 10 * FROM [movie].[dbo].[movies] 
WHERE title like '%' + '%s' + '%'
ORDER BY SomeColumn -- Specify your column for ordering

See: TOP (Transact-SQL)

Limits the rows returned in a query result set to a specified number of rows or percentage of rows in SQL Server

Also look under Best Practices in docs.

In a SELECT statement, always use an ORDER BY clause with the TOP clause. This is the only way to predictably indicate which rows are affected by TOP.

If you are looking for Paging records then you will need ROW_NUMBER

Sign up to request clarification or add additional context in comments.

10 Comments

Yes for paging ROW_NUMBER should be used.
TOP has no meaning without ORDER BY.
@ThorstenDittmar, Are you sure about it ? Because I think SELECT just returns records in undetermined order , is it because of the TOP keyword that the returned results would be in order based on PK ?
@ThorstenDittmar "almost always" <> "always" ;)
@gvee That is true, but in some cases (as in one of our customer's database) I just need to get the first value from a set of rows, as it is equal for all rows, so there I don't need an ORDER BY. One could rightfully argue that the data model is a WTF in itself, but that's not the topic here :-D
|
3

In SQL Server 2012 a new feature was introduced that provides this functionality.

Look at the OFFSET part of the ORDER BY clause

SELECT *
FROM   your_table
ORDER
    BY some_column
       OFFSET 20 ROWS
       FETCH NEXT 10 ROWS ONLY

This will return the results 20-30 of your resultset (ordered by some_column)

For SQL Server 2005 - 2008R2 you can use windowed functions to perform the same action:

SELECT *
FROM   (
        SELECT *
             , Row_Number() OVER (ORDER BY some_column) As sequence
        FROM   your_table
       ) As a_subquery
WHERE  sequence >= 20
AND    sequence <= 30

For versions of SQL Server prior to SQL Server 2005 there is no efficient way of achieving this effect. Here's something that does the trick:

SELECT *
FROM   (
        SELECT *
             , (
                SELECT Count(*)
                FROM   your_table As x
                WHERE  x.some_column <= your_table.some_column
               ) As sequence
        FROM   your_table
       ) As a_subquery
WHERE  sequence >= 20
AND    sequence <= 30

Final notes: for your results to be deterministic some_column should be unique. If it isn't then you need to add extra column(s) in to the equation to provide a deterministic sort order for your sequence.

Also note that SELECT * ... should be avoided in all production code. Don't be lazy [like I was in this answer ;-)] - list out only the columns required.

Comments

3

There's no equivalent in T-SQL. TOP allows you to get only the first x results from the result set. You can use a trick. Using ROW_NUMBER you can add a new column that starts from 1 and is incremented automatically.

Like this:

SELECT ROW_NUMBER OVER (SomeExpression), Field FROM ...

Then you can use

SELECT TOP x FROM
(
    SELECT ROW_NUMBER OVER (ORDER BY ID) AS RowNumber, ID, videoid, title FROM ...
) tmp
WHERE RowNumber > Y ORDER BY RowNumber ASC

The trick is that this numbering is independent of the other fields, so using the same filter you'll always get the same RowNumbers and thus can filter again. This mimicks what LIMIT does.

For example, to get the entries 1 - 9 entries, you'd write:

SELECT TOP 9 FROM
(
    SELECT ROW_NUMBER OVER (ORDER BY ID) AS RowNumber, ID, videoid, title FROM ...
) tmp
WHERE RowNumber >= 1 ORDER BY RowNumber ASC

Next Page:

SELECT TOP 9 FROM
(
    SELECT ROW_NUMBER OVER (ORDER BY ID) AS RowNumber, ID, videoid, title FROM ...
) tmp
WHERE RowNumber >= 10 ORDER BY RowNumber ASC

Comments

2

Use Top:

SELECT TOP 1 * FROM [movie].[dbo].[movies] 
WHERE title like '%' + '%s' + '%'

When TOP is used in conjunction with the ORDER BY clause, the result set is limited to the first N number of ordered rows; otherwise, it returns the first N number of rows in an undefined order.

Read more here.

To get results like 10-20, use ROW_NUMBER:

SELECT TOP 10 * FROM 
 (SELECT ROW_NUMBER() OVER (id_field) as SlNo, ID, videoid, title 
  FROM TableName) T
WHERE SlNo>=10
ORDER BY id_field

2 Comments

This doesn't work exactly as LIMIT in that you can't get results 10 - 20.
TOP has no meaning without ORDER BY. example 1, example 2, example 3
1

I dont't think there's LIMIT in SQL server. Use TOP instead. TOP returns the first N rows of a query, so if it's TOP 10, even if you have a thousand rows, it will only return the first 10. Try this...

SELECT TOP 60 * 
FROM [movie].[dbo].[movies] 
WHERE title like '%' + '%s' + '%'

1 Comment

This does not allow for paging as LIMIT, however.
0

You can use following method for this purpose:

Method 1: ORDER BY

SELECT * 
FROM [movie].[dbo].[movies] 
WHERE title like '%' + '%s' + '%'
ORDER BY ID OFFSET 21 ROWS FETCH NEXT 20 ROWS ONLY

Method 2: ROW_NUMBER

SELECT *
FROM (  SELECT *,
                ROW_NUMBER()OVER (ORDER BY ID)row
        FROM [movie].[dbo].[movies]
        WHERE title like '%' + '%s' + '%'
    )z
WHERE row>20
    AND row<=40

Method 3: Top N

SELECT TOP 20 *
FROM (  SELECT TOP 40 *
        FROM [movie].[dbo].[movies] 
        WHERE title like '%' + '%s' + '%'
        ORDER BY ID
    )z
ORDER BY ID DESC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.