SQL DISTINCT Vs UNIQUE Clause
UNIQUE keyword designates a database constraint, which can be specified during table construction or subsequently on a single column or a group of columns.
When retrieving the result set from the database, the
DISTINCT keyword is utilised.
When we want to make sure that all the rows in the result set contain separate values or a distinct collection of values, we use it after the
SQL UNIQUE Clause
In SQL, a UNIQUE command or constraint assures that all values in a column are distinct.
Furthermore, the uniqueness of a column or a set of columns is guaranteed by both unique and primary keys.
In most cases, the primary key is already bound by the unique constraint.
Multiple unique constraints per table are feasible, but each table can only have one primary key.
Example: The steps for creating a Student using UNIQUE are as follows.
CREATE TABLE Student( id int not null. name varchar(255), int age, UNIQUE (ID) ); INSERT INTO Student VALUES(1,'Vishnu',23); INSERT INTO Student VALUES(2,'Kamal',34); INSERT INTO Student VALUES(3,Vijay',45);
Additionally, a unique constraint can be applied to an existing table.
It will make a change to the table. In the example below, the id column of the existing student database is given a unique constraint.
As a result, it's utilised with
ALTER TABLE Student ADD UNIQUE (id);
SQL DISTINCT Clause
DISTINCT is a SQL command that allows you to return only unique values.
In a table, the same value might appear in numerous columns.
In other words, it may contain values that are duplicated.
The programmer may occasionally need to eliminate duplicate values and acquire distinct values from the database. He can use DISTINCT in that situation.
Example: The following query used to get unique values from Employee.
SELECT DISTINCT Dept FROM Employee;
In above query we get unique values in Dept column from Employee table.
Only unique data from the column 'Dept' is returned by a SQL
SELECT query with the DISTINCT keyword.
Output: The output of unique values
SQL Difference Between UNIQUE And DISTINCT Function
There are 2 main contrast in union & distinct function:-
|A constraint that prevents two records from having the same values in a column is called unique.||When retrieving data, DISTINCT helps to eliminate duplicate values.|
|A sql constraint that permits one or more table columns to uniquely identify a record in a database table.||SELECT constraint that aids in the return of distinct or diverse values in a result set.|