What Is SQL DISTINCT?

SQL DISTINCT Keyword like a filter that allows you to get only unique or distinct values from a dataset. Imagine you have a table filled with various entries, and some of them are duplicated. SQL DISTINCT swoops in to rescue you, presenting only the unique values and leaving duplicates in the dust.

But why is this necessary? Well, databases often contain redundant information, and you might want to focus only on the unique elements. For instance, think of a list of students, some of whom may come from the same hometown. When you want to know how many different hometowns are represented, SQL DISTINCT is your go-to ally.

The Syntax of SQL DISTINCT

Now that we understand the purpose of SQL DISTINCT, let's unravel the syntax that brings this command to life.

SELECT DISTINCT column_name, column_name
FROM table_name;

In this command, you need to replace column_name with the actual name of the column from which you want to extract unique values. And table_name is, well, the name of the table where all this data resides.

For example, if you have a table called 'students,' and you want to retrieve a list of distinct hometowns from it, your SQL query would look like this:

SELECT DISTINCT HOME_TOWN
FROM students;

A Real-World Example

To make the concept even clearer, let's consider a real-world example. Imagine you have a table of students with columns for their id,names, age, subject, marks:

Post Images

Now, suppose you want to find out the distinct subjects represented in this table. You'd use the SQL DISTINCT command like this:

SELECT DISTINCT subject
FROM students;

And the result would be:

Post Images