Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LIMIT keyword in SQL Server 2005?

I have found a way to select random rows from a table in this post. A suggestion is to use the following query:

SELECT * FROM employee ORDER BY RAND() LIMIT 1

But when I run this query in MS SQL 2005, I get the following error message

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'LIMIT'.

Can anyone tell me where am I wrong? Doesn't MS SQL support LIMIT? If so, then how can I do this?

like image 895
user11445 Avatar asked Jan 18 '09 11:01

user11445


People also ask

Can we use limit in SQL Server?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

How do you use limits in SQL?

The LIMIT clause is used to set an upper limit on the number of tuples returned by SQL. It is important to note that this clause is not supported by all SQL versions. The LIMIT clause can also be specified using the SQL 2008 OFFSET/FETCH FIRST clauses. The limit/offset expressions must be a non-negative integer.

How do I limit records in SQL Server?

The SQL SELECT LIMIT statement is used to retrieve records from one or more tables in a database and limit the number of records returned based on a limit value. TIP: SELECT LIMIT is not supported in all SQL databases. For databases such as SQL Server or MSAccess, use the SELECT TOP statement to limit your results.

How do you use limits in database?

The SQL LIMIT clause restricts how many rows are returned from a query. The syntax for the LIMIT clause is: SELECT * FROM table LIMIT X;. X represents how many records you want to retrieve. For example, you can use the LIMIT clause to retrieve the top five players on a leaderboard.


3 Answers

If you take a look at the SELECT statement in SQL Server Books Online, then you'll see that you can limit the resultset by using the TOP keyword.

SELECT TOP 1 * FROM employee
like image 136
Frederik Gheysels Avatar answered Oct 01 '22 21:10

Frederik Gheysels


SELECT TOP 1 * FROM Employee ORDER BY newid()

You have to use newid() for it to be evaluated once per row.

like image 6
Jonas Lincoln Avatar answered Oct 01 '22 20:10

Jonas Lincoln


I'm using this fairly simple one (SQL2005) to limit the number of rows returned, which will work with a value provided by a stored procedure parameter as well.

DECLARE @Limit int
SET @Limit = 10
SELECT TOP (@Limit) Col1, Col2 FROM SomeTable
like image 1
Stuntbeaver Avatar answered Oct 01 '22 21:10

Stuntbeaver