How do you select unique rows from a table?
To select unique rows from a table, use the DISTINCT keyword in a SELECT command.
Syntax:
sql
SELECT DISTINCT Column1, Column2, ...
FROM Table_Name;Example:
sql
SELECT DISTINCT DepartmentID
FROM Employees;What this query does
- Selects only the unique values of the
DepartmentIDfield from theEmployeestable. - If several employees belong to the same department,
DISTINCTreturns that department only once.
Notes:
- Several columns can be used at once:
sql
SELECT DISTINCT Name, DepartmentID
FROM Employees;- In that case, uniqueness is based on the combination of values across every listed column.
Put simply,
DISTINCThelps remove repeated rows and get back only unique records from a table.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.