Paramclasses Academy - Blog

Tutorials Details

←
Post 14 of 40
→

SQL Server ORDER BY, DISTINCT and TOP Clauses Explained

SQL Server ORDER BY, DISTINCT and TOP Clauses Explained

November 17, 2026

SQL Server ORDER BY, DISTINCT and TOP Clauses Explained

Introduction

When working with SQL Server databases, retrieving records is not always enough. Developers often need to arrange records in a particular order, remove duplicate values, or display only a limited number of records.

SQL Server provides three important clauses to perform these operations:

  • ORDER BY: Sorts records in ascending or descending order.

  • DISTINCT: Removes duplicate records from query results.

  • TOP: Limits the number or percentage of records returned by a query.

For example, imagine that you are developing a Student Management System for a college. Your database contains hundreds of student records. You may want to display students according to their marks, retrieve a list of unique departments, or show only the top five students.

In this tutorial, we will learn how to use ORDER BY, DISTINCT, and TOP clauses in SQL Server with practical examples, SQL queries, and real-world applications.

1. What Is the ORDER BY Clause in SQL Server?

The ORDER BY clause is used to sort records returned by a SELECT statement.

It allows developers to arrange data in ascending or descending order based on one or more columns.

By default, SQL Server sorts records in ascending order when ASC or DESC is not specified.

Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column_name ASC;

Sorting Options:

  • ASC: Sorts records in ascending order (smallest to largest or A to Z).

  • DESC: Sorts records in descending order (largest to smallest or Z to A).

Example

Suppose we have a Students table containing student information.

SELECT *
FROM Students
ORDER BY StudentName ASC;

Explanation:

This query displays all student records in alphabetical order according to StudentName.

The ASC keyword sorts names from A to Z.

2. Understanding Ascending Order (ASC)

The ASC keyword is used to arrange records in ascending order.

It is commonly used for:

  • Alphabetical sorting (A to Z).

  • Numerical sorting (smallest to largest).

  • Date sorting (oldest to newest).

Example 1: Sort Students by Name

SELECT *
FROM Students
ORDER BY StudentName ASC;

This query displays student names in alphabetical order.

Example 2: Sort Students by Marks

SELECT *
FROM Students
ORDER BY Marks ASC;

This query displays students from the lowest marks to the highest marks.

Example 3: Sort Students by Age

SELECT *
FROM Students
ORDER BY Age ASC;

This query arranges students according to their age, starting with the youngest.

Important: ASC is the default sorting order in SQL Server. Therefore, the following queries produce the same sorting direction:

SELECT *
FROM Students
ORDER BY Marks;
SELECT *
FROM Students
ORDER BY Marks ASC;

3. Understanding Descending Order (DESC)

The DESC keyword is used to arrange records in descending order.

It is useful when you want to display the highest values or latest records first.

Example 1: Sort Students by Marks

SELECT *
FROM Students
ORDER BY Marks DESC;

This query displays students from the highest marks to the lowest marks.

Example 2: Sort Students by Name

SELECT *
FROM Students
ORDER BY StudentName DESC;

This query arranges student names in reverse alphabetical order (Z to A).

Example 3: Sort Students by Age

SELECT *
FROM Students
ORDER BY Age DESC;

This query displays the oldest students first.

Practical Use: DESC is commonly used in applications to display latest orders, highest salaries, top marks, and recently created records.

4. Sort Records Using Multiple Columns

SQL Server allows developers to sort records using multiple columns in a single ORDER BY clause.

This is useful when one column alone cannot provide the required sorting.

Syntax

SELECT *
FROM table_name
ORDER BY column1 ASC, column2 DESC;

Example

SELECT *
FROM Students
ORDER BY Department ASC, Marks DESC;

Explanation:

This query performs two sorting operations:

  1. First, students are arranged according to Department in ascending order.

  2. Within each department, students are arranged according to Marks in descending order.

For example, students belonging to the same department will appear from the highest marks to the lowest marks.

Important: SQL Server applies the second sorting column when values in the first sorting column are equal.

5. Sort Records Using Column Position

SQL Server also allows sorting using the position of a column in the SELECT list.

Example

SELECT StudentID, StudentName, Marks
FROM Students
ORDER BY 3 DESC;

Explanation:

In this query:

  • Column 1 is StudentID.

  • Column 2 is StudentName.

  • Column 3 is Marks.

Therefore, ORDER BY 3 DESC sorts the result according to Marks in descending order.

Best Practice: Using actual column names is generally easier to read and maintain than using column positions.

6. Sort Records Using Aliases

You can also use a column alias in the ORDER BY clause.

Example

SELECT
    StudentName,
    Marks AS TotalMarks
FROM Students
ORDER BY TotalMarks DESC;

This query displays students according to their TotalMarks from highest to lowest.

Column aliases make query results easier to understand.

7. What Is the DISTINCT Clause in SQL Server?

The DISTINCT keyword is used to remove duplicate rows from the result of a SELECT query.

It returns only unique combinations of the selected column values.

For example, suppose a Students table contains multiple students belonging to the same department. If you want to display each department only once, you can use DISTINCT.

Syntax

SELECT DISTINCT column_name
FROM table_name;

Example

SELECT DISTINCT Department
FROM Students;

Explanation:

This query displays each department only once, even if multiple students belong to the same department.

For example, if the Students table contains:

StudentName Department
Rahul Computer Science
Priya IT
Amit Computer Science
Sneha Mechanical
Rohit IT

The DISTINCT query returns:

Department
Computer Science
IT
Mechanical

Duplicate department values are removed from the result.

8. Use DISTINCT with Multiple Columns

DISTINCT can also be used with multiple columns.

In this case, SQL Server removes duplicate combinations of the selected column values.

Example

SELECT DISTINCT Department, City
FROM Students;

Explanation:

This query returns unique combinations of Department and City.

For example, if several students belong to the Computer Science department and live in Raipur, that combination will appear only once.

Important: DISTINCT considers the complete selected combination, not each column independently.

9. Difference Between DISTINCT and SELECT ALL

SQL Server supports ALL and DISTINCT as options in a SELECT statement.

  • DISTINCT: Removes duplicate result rows.

  • ALL: Returns all matching rows, including duplicates.

ALL is the default behavior when neither keyword is specified.

Example Using ALL

SELECT ALL Department
FROM Students;

This query returns every department value, including duplicates.

Example Using DISTINCT

SELECT DISTINCT Department
FROM Students;

This query returns only unique department values.

10. What Is the TOP Clause in SQL Server?

The TOP clause is used to limit the number of rows returned by a SELECT statement.

It is especially useful when working with large databases where displaying every record is unnecessary.

For example, you may want to display:

  • Top 5 students based on marks.

  • Latest 10 orders.

  • First 20 employee records.

  • Top 10 products based on price.

Syntax

SELECT TOP (number)
column1, column2, ...
FROM table_name;

Example

SELECT TOP (5) *
FROM Students;

This query returns only five rows from the Students table.

Important: Without ORDER BY, TOP does not guarantee which particular rows will be returned.

11. Use TOP with ORDER BY

One of the most common uses of TOP is combining it with ORDER BY.

This allows developers to retrieve a specific number of records according to a sorting condition.

Example 1: Find Top 5 Students

SELECT TOP (5) *
FROM Students
ORDER BY Marks DESC;

Explanation:

This query displays the five students with the highest marks.

First, records are sorted from highest to lowest marks. Then TOP (5) returns the first five rows.

Example 2: Find Lowest 3 Marks

SELECT TOP (3) *
FROM Students
ORDER BY Marks ASC;

This query retrieves the three students with the lowest marks.

Example 3: Find Latest 5 Records

Suppose you have an Employees table with a CreatedDate column.

SELECT TOP (5) *
FROM Employees
ORDER BY CreatedDate DESC;

This query displays the five most recently created employee records.

Best Practice: Always combine TOP with ORDER BY when you need specific highest, lowest, latest, or earliest records.

12. Use TOP with PERCENT

SQL Server also supports TOP with PERCENT.

This option returns a percentage of the total rows instead of a fixed number.

Syntax

SELECT TOP (percentage) PERCENT
*
FROM table_name
ORDER BY column_name DESC;

Example

SELECT TOP (10) PERCENT *
FROM Students
ORDER BY Marks DESC;

This query returns approximately the top 10 percent of student records according to marks.

Note: SQL Server rounds the calculated number of rows up when necessary to return a whole number of rows.

13. Use TOP WITH TIES

SQL Server provides another useful option called WITH TIES.

It allows additional rows to be returned when they have the same ORDER BY value as the last row selected by TOP.

Example

SELECT TOP (3) WITH TIES *
FROM Students
ORDER BY Marks DESC;

Explanation:

Suppose the third position has multiple students with the same marks.

WITH TIES includes all additional rows that have the same ORDER BY value as the last selected row.

Important: WITH TIES must be used with ORDER BY.

This is especially useful when identifying top-ranking students, employees, or products where multiple records share the same value.

14. Combine DISTINCT, TOP and ORDER BY

SQL Server allows developers to combine DISTINCT, TOP, and ORDER BY in a single query.

Example

SELECT DISTINCT TOP (3) Department
FROM Students
ORDER BY Department ASC;

Explanation:

This query performs the following operations:

  1. Retrieves unique department values.

  2. Arranges the departments in ascending order.

  3. Returns only the first three departments.

This is useful when you want a limited list of unique values.

15. Difference Between ORDER BY, DISTINCT and TOP

Although all three are used in SELECT queries, their purposes are different.

Clause Purpose
ORDER BY Sorts query results
DISTINCT Removes duplicate result rows
TOP Limits the number of returned rows

Example Using All Three

SELECT DISTINCT TOP (5) Department
FROM Students
ORDER BY Department ASC;

This query retrieves up to five unique department values in alphabetical order.

16. Real-World Example: Student Management System

Let's understand these clauses through a practical example at Param Classes.

Suppose Param Classes is developing a Student Management System where student information is stored in a SQL Server database.

The application needs to perform different operations.

Requirement 1: Display Students with Highest Marks

SELECT *
FROM Students
ORDER BY Marks DESC;

This query sorts students from highest marks to lowest marks.

Requirement 2: Display All Unique Departments

SELECT DISTINCT Department
FROM Students;

This query displays every department only once.

Requirement 3: Display Top 5 Students

SELECT TOP (5) *
FROM Students
ORDER BY Marks DESC;

This query retrieves the five students with the highest marks.

Requirement 4: Display Students Alphabetically

SELECT *
FROM Students
ORDER BY StudentName ASC;

This query arranges students according to their names from A to Z.

Requirement 5: Display Unique Cities

SELECT DISTINCT City
FROM Students
ORDER BY City ASC;

This query displays unique city names in alphabetical order.

Requirement 6: Display Top 10 Percent of Students

SELECT TOP (10) PERCENT *
FROM Students
ORDER BY Marks DESC;

This query retrieves approximately the top 10 percent of students according to their marks.

These examples demonstrate how ORDER BY, DISTINCT, and TOP can be used in real-world database applications.

17. Common Mistakes While Using ORDER BY, DISTINCT and TOP

Beginners often make mistakes when working with these SQL Server clauses.

Here are some common mistakes and their solutions.

1. Forgetting DESC While Finding Highest Values

Incorrect:

SELECT TOP (5) *
FROM Students;

Correct:

SELECT TOP (5) *
FROM Students
ORDER BY Marks DESC;

The second query retrieves the five students with the highest marks.

2. Expecting DISTINCT to Remove Duplicates from Every Column Separately

DISTINCT removes duplicate combinations of all selected columns. It does not independently remove duplicates from each column.

3. Using TOP Without ORDER BY

Without ORDER BY, SQL Server does not guarantee which records will be selected.

4. Confusing ASC and DESC

  • ASC means ascending order.

  • DESC means descending order.

5. Forgetting WITH TIES Requirements

WITH TIES must be used together with ORDER BY.

18. Advantages of ORDER BY, DISTINCT and TOP

These SQL Server clauses provide several benefits when managing and retrieving database information.

  • Organized Data: ORDER BY arranges records in a meaningful sequence.

  • Duplicate Removal: DISTINCT helps retrieve unique values and combinations.

  • Limited Results: TOP reduces the number of rows returned.

  • Better Reporting: These clauses help generate useful reports and summaries.

  • Practical Database Operations: They are useful in student management, employee management, inventory systems, e-commerce applications, and billing software.

  • Improved Query Readability: They make database queries easier to understand and maintain.

19. Frequently Asked Questions (FAQs)

Q1. What is ORDER BY in SQL Server?

ORDER BY is used to sort query results in ascending or descending order.

Q2. What is the default sorting order in SQL Server?

Ascending order (ASC) is the default sorting direction.

Q3. What is the difference between ASC and DESC?

ASC sorts values from smallest to largest or A to Z, whereas DESC sorts values from largest to smallest or Z to A.

Q4. What is DISTINCT in SQL Server?

DISTINCT removes duplicate rows from the selected columns in a query result.

Q5. Can we use DISTINCT with multiple columns?

Yes. DISTINCT can be used with multiple columns to retrieve unique combinations of their values.

Q6. What is the TOP clause in SQL Server?

TOP limits the number of rows returned by a SELECT query.

Q7. Can we use TOP with ORDER BY?

Yes. TOP and ORDER BY are commonly combined to retrieve the highest, lowest, latest, or earliest records.

Q8. What is TOP WITH TIES?

TOP WITH TIES returns additional rows that have the same ORDER BY value as the last selected row.

Q9. What is TOP PERCENT in SQL Server?

TOP PERCENT returns a specified percentage of the total result rows.

Q10. Can we combine DISTINCT, TOP and ORDER BY?

Yes. All three can be combined in one SELECT statement to retrieve limited, unique, and sorted records.

Conclusion

The ORDER BY, DISTINCT, and TOP clauses are important SQL Server features that help developers retrieve and organize database records efficiently.

In this tutorial, we learned how to sort records using ASC and DESC, arrange data using multiple columns, remove duplicate values using DISTINCT, limit query results using TOP, and retrieve tied records using WITH TIES.

We also explored practical examples of combining these clauses in a Student Management System.

At Param Classes, we focus on helping students and beginners understand SQL Server through practical examples, step-by-step tutorials, and real-world database projects. Practise these SQL queries in SQL Server Management Studio (SSMS) to improve your database querying skills and prepare for advanced SQL Server concepts.

←
Post 14 of 40
→