This tutorial will explain how to use DISTINCT keyword within a SQL query and how to use them with the examples.
DISTINCT keyword is used to remove duplicates from results
This is the general statement to use DISTINCT from a table
SELECT DISTINCT
column1, column2, column3
FROM
tablename
Lets create a sample table and add some rows
CREATE TABLE SampleContacts (
FullName VARCHAR(50) NOT NULL,
Gender CHAR(1) NOT NULL,
Age INT NOT NULL
);
INSERT INTO SampleContacts
(FullName, Gender, Age)
VALUES
('Contact1', 'M', 26),
('Contact2', 'M', 29),
('Contact3', 'F', 27),
('Contact4', 'F', 29),
('Contact5', 'F', 27),
('Contact6', 'M', 29)
A) Using DISTINCT keyword with single column
The following statement returns all gender values via removing any duplicates from SampleContacts table:
SELECT
DISTINCT Gender
FROM
SampleContacts
| Gender |
----------
M
F
If DISTINCT keyword was not used, it would return 6 records instead of 2. It basicly displays the unique value via removing duplicates.
B) Using DISTINCT keyword with multiple columns
The following statement returns all gender values via removing any duplicates from SampleContacts table:
SELECT
DISTINCT Gender, Age
FROM
SampleContacts
| Gender | Age |
------------------
F 27
F 29
M 26
M 29
This time uniqueness defined with the combination of the given multiple columns