Loading
SQL Select Distinct-interview

Scenario 1: Removing Duplicate Entries

Some of the student ages that you are examining in a database are repeated. Only distinct age values should be displayed.


Interview Question

In SQL, how may duplicate values be eliminated from a column's result set?

Answer: 


Use the DISTINCT keyword:
SELECT DISTINCT Age FROM Students;


Tips: To extract just distinct entries from a column, use DISTINCT.


Scenario 2: Multiple Column Duplicates
From a table, you wish to identify distinct names and age combinations.


Interview Question

Is it possible to use the DISTINCT keyword on more than one column?

Answer: 


Indeed. Rows with identical chosen columns are filtered out:
SELECT DISTINCT Name, Age FROM Students;


Tips: When used with many columns, DISTINCT compares entire rows rather than simply individual columns.


Scenario 3: NULL Handling
A column containing NULL values is the subject of your query. You don't know if DISTINCT gets rid of them.


Interview Question

How are NULL values handled by SQL DISTINCT?

Answer: 


NULL is treated as a value by DISTINCT. Only one NULL will show up since multiple NULLs are regarded as duplicates.


Tips: DISTINCT will only return one NULL if a column contains several NULL values.

Scenario 4: Using with Aggregate Functions
The amount of distinct nations in a customer table is what you wish to count.


Interview Question

How can I use SQL to count only unique values in a column?

Answer: 


Use COUNT(DISTINCT column):

SELECT COUNT(DISTINCT Country) FROM Customers;


Tips: For computations dependent on uniqueness, use DISTINCT inside aggregate functions.


Scenario 5: Using with Aggregate Functions
To prevent duplicate rows, you use DISTINCT when joining multiple tables.


Interview Question

Why is DISTINCT frequently required following a SQL JOIN?

Answer: 


Repeated rows may result from joins, particularly INNER JOIN or LEFT JOIN. They are filtered out by DISTINCT.


Tips: When using DISTINCT in joins, exercise caution and attempt to minimize duplication in the first place.