SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP


SQL Select Top N or Top N Random Rows, SQL TOP


You may need a sql query that will select top n records or random n records for each category in a table. The t-sql query that will solve this problem may be difficult for first timers, especially if you are working on MS SQL Server 2000. Now, with the t-sql enhancements in Microsoft SQL Server 2005 the problem of selecting a definite number of records grouped or categorized according to a column is easier to create.



Select Top 1 row or select only first record


If you need to select top 1 row or select only the first record from a SQL Server database table, you can use the below t-sql syntax.

SELECT TOP 1 * FROM dbo.Customers
Code

We can want to select first record from customes ordered by alphabetically, in this case for a solution we will use an ORDER BY clause.

SELECT TOP 1 * FROM dbo.Customers ORDER BY [Customer Name] ASC

SELECT TOP 1 * FROM dbo.Customers ORDER BY [Customer Name] DESC
Code




Select Top 10 rows or select first 10 records


If you need to select top 10 rows or select first 10 rows of a sql database table, you can use the below t-sql syntax.

SELECT TOP 10 * FROM dbo.Customers
Code


Select Top N rows or select first N records


If you need to select top n rows or select first n rows from a database table, you can use the below t-sql syntax.
Here the important point is the N rows is dynamically set so we need to declare a variable for the first N rows and then select the first group among others.

DECLARE @N int
SET @N = 3

SELECT TOP (@N) * FROM dbo.Customers
Code

If you do not place @N among paranthesis, the SQL Server engine will throw the following error.
Incorrect syntax near '@N'.



SELECT TOP Random n Rows From a Table For Each Category or Group


Refer to SELECT TOP Random n Rows From a Table For Each Category or Group



Random Sorting using NEWID()


Refer to Random Ordering using NEWID()



SQL Server

SQL Server 2019 Installation
download SQL Server 2019
download SQL Server 2017
download SQL Server 2016
download SQL Server 2014
download SQL Server 2012
MacOS ve SQL Server 2019


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.