Search

Friday, 20 December 2019

Introduction to SQL - DISTINCT Keyword


SQL DISTINCT Keyword
SQL DISTINCT returns unique records from a table in the SQL database. By default SQL queries return all rows, including duplicate records. The SQL DISTINCT keyword is used to eliminate duplicate records in the result set and display a distinct list of values.

The SQL DISTINCT Keyword Syntax

The general syntax for a simple SQL Distinct is below. It returns only DISTINCT (different) values by eliminate duplicates in the result set.
SELECT DISTINCT column-names
              FROM table-name;


DISTINCT Keyword Practical Examples

SQL DISTINCT On One Column

Below DISTINCT Statement will return single Column [FirstName] from [Employees] table.
SELECT DISTINCT [FirstName]
    FROM [Employees];

SQL DISTINCT Multiple Columns

Below Distinct Statement will return multiple Columns [FirstName], [LastName] from [Employees] table.
SELECT DISTINCT [FirstName], [LastName],
       FROM [Employees];

SQL DISTINCT Statement on All Columns

If used (*) instead of column name in SQL Statement it will return all DISTINCT rows from [Employees] table.
SELECT DISTINCT (*)
       FROM [Employees];
Caution: It’s not ideal select all columns all the time if only need certain columns as that increase burden on SQL engine. We will discuss its effects on another day!

SQL DISTINCT and WHERE Clause

The following will list the DISTINCT employees and limit the result set to the Where Clause
SELECT DISTINCT [FirstName]
    FROM [Employees];
        WHERE FirstName= ='David';


SQL DISTINCT Count

When SQL COUNT () used with DISTINCT it eliminate the duplicate records of the same data and only count distinct records once.
SELECT COUNT (DISTINCT [FirstName])
    FROM [Employees];


SQL DISTINCT and NULL Values

SQL DISTINCT eliminate the duplicate records of the Null data and only count single Null record.





No comments:

Post a Comment