SELECT DISTINCT clause

The syntax of the DISTINCT clause is as follows:

The DISTINCT clause is used in the SELECT statement to remove duplicate rows from a result set. The DISTINCT clause keeps one row for each group of duplicates. You can use the DISTINCT clause on one or more columns of a table.

SELECT DISTINCT
column_1
FROM table_name
SELECT DISTINCT
column_1,
column_2
FROM
tbl_name;
Example :
Distinct
SELECT DISTINCT  bcolor  FROM t1 ORDER BY bcolor;
Distinct_OP.PNG

PostgreSQL DISTINCT on multiple columns

SELECT DISTINCT  bcolor, fcolor FROM t1 ORDER BY bcolor,      fcolor;
distinct2.PNG
Because we specified both bcolor and fcolor columns in the SELECT DISTINCT clause, PostgreSQL combined the values in both bcolor and fcolor columns to evaluate the uniqueness of rows.

PostgreSQL DISTINCT ON ORDER BY example

The following statement sorts the result set by the  bcolor and  fcolor, and then for each group of duplicates, it keeps the first row in the returned result set.

SELECT DISTINCT ON (bcolor) bcolor, fcolor FROM t1 ORDER BY bcolor, fcolor;
distinct3.PNG
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s