Open In App

SQL Query to Find Unique Column Values From Table

Last Updated : 31 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Finding unique column values is a common task in SQL when analysing data or ensuring data integrity. By using the DISTINCT clause, we can efficiently retrieve unique values from a specified column, avoiding duplicate results.

In this article, we will explain the use of the DISTINCT clause with detailed examples, syntax, and practical use cases. By the end of this guide, we will have a thorough understanding of how to apply the DISTINCT clause in SQL to improve our data queries and analysis.

What is the DISTINCT Clause in SQL?

The DISTINCT clause is a powerful feature in SQL that allows us to fetch unique values from a specified column in a table. It removes duplicate entries from the result set, ensuring that each value appears only once.

Syntax

SELECT DISTINCT column_name
FROM table_name;

Finding Unique Column Values in SQL

Let’s look at an example, where we will retrieve unique column values from a table using the DISTINCT clause. We take a sample table named Geeks and return unique column values by applying various SQL queries.

Geeks-Table

Geeks Table

Retrieve Unique Departments

The query retrieves distinct department names from the Geeks table, ensuring that no duplicate department names appear in the result. This is particularly useful for summarising data or understanding the available categories within a column.

Query:

SELECT DISTINCT DEPARTMENT 
FROM Geeks;

Output

DEPARTMENT
Admin
DBA
Review
Writer

Retrieving Additional Details

This query fetches all rows from the Geeks table where the DEPARTMENT column contains values that start with “DBA“. Using the LIKE operator allows partial matching, making it flexible for filtering records based on patterns.

Query:

Select * from Geeks 
where DEPARTMENT like 'DBA%';

Output

G_ID FIRSTNAME LASTNAME JOININGDATE DEPARTMENT
1 Mohan Arora 7-08-2019 DBA
3 Vishal Gupta 9-01-2020 DBA

Explanation:

  1. LIKE** Clause**: Used to filter rows with the DEPARTMENT column matching “DBA”.
  2. Result: Returns all rows where the department is “DBA”.

Conclusion

The DISTINCT clause is an essential tool in SQL for retrieving unique column values. By eliminating duplicates, it simplifies data analysis and ensures clean result sets. Whether we’re working with a large dataset or generating reports, understanding how to use DISTINCT effectively can save time and improve accuracy.

Through practical examples and best practices discussed in this article, we are now equipped to usage the power of the DISTINCT clause in our SQL queries. Start implementing it today to enhance your data workflows and insights.



Next Article
Article Tags :

Similar Reads