SQL Server BasicsWhat is SQL Server database?What is RDBMS?What is Normalization?Why we use Denormalization?What_is_SQL?What is PL/SQL?Difference between SQL and PL/SQLDatabase TableOne to One RelationshipOne to Many RelationshipMany to Many RelationshipMany to One RelationshipString Data TypesNumber Data TypesDate Data TypesOther Data TypesCreate DatabaseDrop DatabaseCreating and Managing Users in SQL ServerCreate TableAlter TableDrop TableConstraints in SQL serverPrimary KeyForeign KeyUnique KeyCandidate KeyComposite KeyDifference between primary key and candidate keyPrimary key and foreign key relationshipSurrogate KeyCascading Referential Integrity ConstraintsSelf Referential Integrity ConstraintsInsert into statementInsert multiple recordsUpdate statementDelete statementTruncate statementDifference between Delete and TruncateAlias in SQL ServerSelect statementSelect DistinctSelect TopSelect IntoNull Functions(ISNULL(),NULLIF(),COALESCE())Sub QueryIdentity ColumnSequence objectDifference between sequence and identity columnSQL Server ClausesWHERE ClauseOrder By ClauseTop N ClauseGroup By ClauseHaving ClauseDifference between Where and HavingSQL Server OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAny OperatorsAll OperatorsUnion OperatorsUnion All OperatorsDifference between Union and Union AllIntersect OperatorExcept OperatorDifference between Except and IntersectJoinsInner JoinLeft JoinRight JoinFull JoinSelf JoinCross JoinViewsWhat are views?Create views using SSMSIndexed ViewsComplex ViewsCheck Option in ViewCheck Encryption in ViewSchema Binding Option in ViewRead-only ViewsUpdatable ViewsAdvantages and disadvantages of viewsCreate multiple views on one tableCan we implement index on views?Can we Perform Insert, update, delete operation on views?Stored Procedure and FunctionsWhat are Stored Procedures?Why we use stored procedures?Passing parameters to Stored procedureUser-Defined FunctionsDifference between UDF and Stored procedurePre-Defined Functions@@Indentity and Scope_IndentityNULLIF, ISNULL and COALESCE

SQL - Top N

In SQL Server, the TOP clause is used to limit the number of rows returned by a query. It allows you to specify the maximum number of rows you want to retrieve from a result set. Here's the syntax for using the TOP clause:


SELECT TOP (N) column1, column2, ...
FROM table_name
ORDER BY column1, column2, ...;

In the above syntax, N represents the number of rows you want to retrieve, column1, column2, ... represent the columns you want to select, and the ORDER BY clause is optional. If you want the result set to be ordered, you can specify one or more columns in the ORDER BY clause.

For example, let's say you have a table called "Employees" with columns such as "EmployeeID", "FirstName", "LastName" and "Email":

Table: Customers
CustomerID FirstName LastName Email
1 John Smith john.smith@email.com
2 Sarah Johnson sarah@email.com
3 Michael Brown michael@email.com
4 Emma Davis emma@email.com
5 Olivia Wilson olivia@email.com
6 James jones james@email.com
7 Sophia Clark sophia@email.com
8 William White william@email.com
9 Ava Martinez ava@email.com
10 Benjamin Anderson benjamin@email.com

Now, let's use the TOP clause to retrieve the top 5 customers based on their first names in alphabetical order:


SELECT TOP 5
    CustomerID,
    FirstName,
    LastName,
    Email
FROM
    Customers
ORDER BY
    FirstName;

The output result of this query would be:

CustomerID FirstName LastName Email
9 Ava Martinez ava@email.com
10 Benjamin Anderson benjamin@email.com
4 Emma Davis emma@email.com
6 James jones james@email.com
1 John Smith john.smith@email.com

In this result, you can see that it includes the top 5 customers based on their first names in alphabetical order. The TOP 5 clause limited the result set to only those 5 rows, and they are sorted by the "FirstName" column.

It's important to note that if you specify the TOP clause without an ORDER BY clause, the result set will be returned in an arbitrary order. To ensure a consistent order, you should always use the ORDER BY clause when using the TOP clause.

Additionally, you can use the TOP clause with a percentage value instead of an absolute number. For example, SELECT TOP (10 PERCENT) ... will retrieve the top 10 percent of rows from the result set.

Lastly, starting from SQL Server 2012, you can also use the OFFSET-FETCH clause to achieve similar functionality to the TOP clause. The OFFSET-FETCH clause allows you to skip a specified number of rows and fetch a specified number of rows from the result set. This can be useful for pagination purposes.