Search code examples
sqlpostgresqlselectdistinct

POSTGRESQL is showing "ERROR: syntax error at or near "DISTINCT"


I tried using DISTINCT keyword after a column name but it is giving syntax error.At the same time writing the same column name after DISTINCT keyword is fetching the result.Can you please tell me why it is so?

image of:DISTINCT keyword after a column name

image of:column name after DISTINCT keyword


Solution

  • DISTINCT is applied to the output results and needs to follow SELECT, you can't call it on an individual column. GROUP BY can give you single column results if that's what you're looking for.

    -- filter all results
    SELECT DISTINCT film_id, rental_rate FROM film;
    
    -- filter on rental_rate
    SELECT film_id, rental_rate FROM film GROUP BY rental_rate;
    
    -- syntax error
    SELECT film_id, DISTINCT(rental_rate) FROM film;