Open In App

How to Use SQL DISTINCT and TOP in Same Query?

Last Updated : 05 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Pre-requisites: SQL | Distinct Clause
 

Structured Query Language is a computer language that we use to interact with a relational database.SQL is a tool for organizing, managing, and retrieving archived data from a computer database.  In this article, we will see how to use SQL DISTINCT and TOP in the same query.

DISTINCT :

This keyword is only used to return distinct or we can say different values. This keeps only a single repeating element and eliminates duplicate rows.

TOP:

The TOP clause is used when we want to return a specific number of records. Keep in mind that not all of the database systems support the TOP clause. for MySQL, it is LIMIT while Oracle used FETCH FIRST number ROWS ONLY.

Steps to Use SQL DISTINCT and TOP in the Same Query:

Step 1: Create a Database. For this use the below command to 

Query:

CREATE DATABASE Student;

Step 2:  Use the Student database. For this use the below command.

Query:

USE Student;

Step 3: Insert 5 rows into the MARKS table.

Query:

INSERT INTO STUDENT VALUES('Amit');
INSERT INTO STUDENT VALUES('Amit ');
INSERT INTO STUDENT VALUES('Aniket');
INSERT INTO STUDENT VALUES('Aniket');
INSERT INTO STUDENT VALUES('Soumya');
INSERT INTO STUDENT VALUES('Tridib');

Step 4: To view inserted name without using distinct.

Query:

SELECT
   name
FROM
   student
ORDER BY
   name;

 

Step 5: To view inserted name using distinct.

Query:

SELECT DISTINCT
  name
FROM
  student
ORDER BY
  name;

 

Step 6: To view inserted name with distinct and top:

Query:

SELECT DISTINCT TOP 3
     name
FROM
     student
ORDER BY
     name;

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads