Postgresql conditionally include distinct in query

65 Views Asked by At

Postgresql conditionally include distinct in query

Is there way to modify a query such as:

select distinct col1, col2  
            from our_schema.our_table
            where (id = '1001')

The goal is to easily activate/deactivate the distinct keyword.

Obviously, one could move it to a comment such as:

select col1, col2 -- distinct 
            from our_schema.our_table
            where (id = '1001')

Is there any easy way to do this in Postgresql?

I've seen 'dynamic SQL' in Microsoft SSMS using TSQL language. Is there something like this for Postgresql? Or something even simpler?

1

There are 1 best solutions below

0
Erwin Brandstetter On BEST ANSWER

Seems like this is just about code management / building SQL strings?

Insert a line break after DISTINCT. The only significance of white space in SQL is to separate tokens. Other than that, line breaks are purely cosmetic - except for standard comments starting with -- which end with the line.

SELECT DISTINCT
       col1, col2 ...

-->

SELECT -- DISTINCT
       col1, col2 ...

Or even:

SELECT
       DISTINCT
       col1, col2 ...

-->

SELECT
--     DISTINCT
       col1, col2 ...

Or use C-style block comments: /* comment */

SELECT DISTINCT col1, col2 ...

-->

SELECT /*DISTINCT*/ col1, col2 ...