DISTINCT Clause
The DISTINCT Clause gives us the unique value from the column. For example, if we have to find the no. of DISTINCT Departments then we will write the query using the DISTINCT clause.
Example 1: Department Details Using DISTINCT Clause
Let’s fetch the all distinct department form the Employee table using DISTINCT Clause.
Query:
-- Getting the Distinct Departments from the Table
SELECT DISTINCT Department
FROM Employee;
Output:
Explanation: Mostly it is used to know the redundancy in the table. For example, if we are working with a student table and there are multiple entries of the same student then we can find it using the DISTINCT keyword. We can also use multiple columns with DISTINCT clauses. If I have to find the sum of the salaries given to each department and if there is a duplicate entry of an employee then it might give the wrong result. So to overcome this I will use three columns in DISTINCT clauses.
Example 2: Employees Details Using DISTINCT Clause
Let’s fetch the FirstName, LastName, and Department from the employee table using DISTINCT Clause.
Query:
SELECT DISTINCT FirstName, LastName, Department
FROM employee;
Output:
Explanation: Using this we can get the idea about the duplicates in the table. DISTINCT is generally used where we have to use aggregate functions.
Group By Vs Distinct Difference In SQL Server
Distinct is a relational database management system. SQL Server offers a wide range of features and tools that handle different needs, from small-scale applications to large-scale application solutions. GROUP BY has performance features, especially when dealing with large datasets and complex aggregations. DISTINCT is generally more effective and more efficient when the purpose is to obtain unique values.
In this article, we will understand the Group By vs. Distinct Difference In SQL Server with examples and so on.