SQL Distinct Clause

DISTINCT command is used to get the unique value from the table. it is not considered duplicate value. It is used with SELECT Statement

Syntax:-


SELECT DISTINCT column_name FROM table_name

Example:- Suppose the employees table has 6 records


+----+------------+-----------+----------------+------------+
| id | first_name | last_name | email          | city       |
+----+------------+-----------+----------------+------------+
|  1 | John       | Tailor    | john@abc.com   | California |
|  2 | Rom        | Tailor    | rom@abc.com    | California |
|  3 | Andrew     | Symonds   | andrew@abc.com | Sydney     |
|  4 | Miacle     | clerk     | miacle@abc.com | sydney     |
|  5 | Sachin     | Tendulkar | sachin@abc.com | Mumbai     |
|  6 | Virat      | Kohli     | virat@abc.com  | delhi      |
+----+------------+-----------+----------------+------------+

Now, we need to get the unique city name.


SELECT DISTINCT city FROM employees

Output:-


+----+-------
| city       |
+----+--------
| California |
| Sydney     |
| Mumbai     |
| delhi      |
+----+--------

SQL Distinct Clause – Interview Questions

Q 1: What is the DISTINCT clause in SQL?
Ans: The DISTINCT clause is used to remove duplicate values from the result set and return only unique records.
Q 2: How does DISTINCT work in a SELECT statement?
Ans: It filters duplicate rows based on the selected column(s).
Q 3: Can DISTINCT be used on multiple columns?
Ans: Yes, DISTINCT considers the combination of multiple columns for uniqueness.
Q 4: Does DISTINCT affect database data?
Ans: No, it only affects the query output.
Q 5: Is DISTINCT processed before ORDER BY?
Ans: Yes, DISTINCT is applied before sorting the result set.

SQL Distinct Clause – Objective Questions (MCQs)

Q1. What is the purpose of the DISTINCT keyword in SQL?






Q2. DISTINCT is used with which SQL statement?






Q3. Which query returns unique department names?






Q4. DISTINCT applies to:






Q5. Which clause executes first with DISTINCT?






Related SQL Distinct Clause Topics