Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PostgreSQL DISTINCT Keyword

PostgreSQL DISTINCT Keyword

In PostgreSQL, the DISTINCT keyword is used together with the SELECT statement to remove duplicate records and retrieve only unique records.

When operating on data, a situation may arise where a table contains multiple duplicate records. When retrieving such records, the DISTINCT keyword is especially meaningful: it retrieves each unique record only once rather than retrieving duplicates.

Syntax

The basic syntax of the DISTINCT keyword for removing duplicate records is as follows:

SELECT DISTINCT column1, column2,.....columnN

FROM table_name

WHERE [condition]

Example

Create the COMPANY table (Download the COMPANY SQL file ), with the following data:

runoobdb# select * from COMPANY;

 id | name  | age | address   | salary

----+-------+-----+-----------+--------

  1 | Paul  |  32 | California|  20000

  2 | Allen |  25 | Texas     |  15000

  3 | Teddy |  23 | Norway    |  20000

  4 | Mark  |  25 | Rich-Mond |  65000

  5 | David |  27 | Texas     |  85000

  6 | Kim   |  22 | South-Hall|  45000

  7 | James |  24 | Houston   |  10000

(7 rows)

Let's insert two records:

INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (8, 'Paul', 32, 'California', 20000.00 );



INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (9, 'Allen', 25, 'Texas', 15000.00 );

The data is now as follows:

 id | name  | age | address    | salary

----+-------+-----+------------+--------

  1 | Paul  |  32 | California |  20000

  2 | Allen |  25 | Texas      |  15000

  3 | Teddy |  23 | Norway     |  20000

  4 | Mark  |  25 | Rich-Mond  |  65000

  5 | David |  27 | Texas      |  85000

  6 | Kim   |  22 | South-Hall |  45000

  7 | James |  24 | Houston    |  10000

  8 | Paul  |  32 | California |  20000

  9 | Allen |  25 | Texas      |  15000

(9 rows)

Next, we find all NAMEs in the COMPANY table:

runoobdb=# SELECT name FROM COMPANY;

The result is as follows:

 name

-------

 Paul

 Allen

 Teddy

 Mark

 David

 Kim

 James

 Paul

 Allen

(9 rows)

Now we use the DISTINCT clause in the SELECT statement:

runoobdb=# SELECT DISTINCT name FROM COMPANY;

The result is as follows:

name

-------

 Teddy

 Paul

 Mark

 David

 Allen

 Kim

 James

(7 rows)

As can be seen from the result, the duplicate data has been filtered out.