![]() ![]() Now let’s apply the DISTINCT clause on multiple columns. PostgreSQL DISTINCT Clause On Multiple Columns ![]() Here, we only return a single column value, therefore the order clause is not needed as long as you want the output in any order. SELECT DISTINCT city FROM customers Code language: PostgreSQL SQL dialect and PL/pgSQL ( pgsql ) Select Distinct Single Column Now let’s return only unique city names from the customers table. PostgreSQL DISTINCT Clause On Single Column Note that, the city and country column contains duplicate values. The table contains the customer’s names, their city and country. Here, we have created a table ‘customers’. ( 'Alex', 'Sydney', 'Australia') Code language: PostgreSQL SQL dialect and PL/pgSQL ( pgsql ) Customers Table Data ![]() INSERT INTO customers ( name, city, country) Let’s create a table and insert some data into it so that we can perform operations with the DISTINCT clause on the table. Note that, when specifying the ORDER BY clause with the DISTINCT ON clause, make sure the DISTINCT ON expression matches the initial order of the ORDER BY expression, else it will throw an error. This is because, col2 contains only unique values, and the duplication of col1 doesn’t matter here. However, if you use the DISTINCT ON clause on col2, you will get both records in the output. If you sort the table in descending order based on col1 and col2, the output will be red-orange. The output may change based on the order of the records. In this case, the output will be red-blue. Now, we have applied the DISTINCT clause on the col1, therefore the output will contain only a single record whichever comes first by the order. Here, Let’s assume the table contains the above col1 and col2 records. FROM tableName Code language: PostgreSQL SQL dialect and PL/pgSQL ( pgsql ) ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |