My DISTINCT SQL query taking long time to execute in PostgreSQL

39 Views Asked by At

I have more than 50 million rows and its taking hours to get this query done:

select distinct column_1
from table_1
where "colour" = 'red';

I tried this:

WITH RECURSIVE cte AS (
   (
   SELECT "column_1"
   FROM   table_1
   where "colour" = 'red'
   ORDER  BY "column_1"
   LIMIT  1
   )
   UNION ALL
   SELECT l."column_1"
   FROM   cte c
   ,      LATERAL (   
      SELECT "column_1"
      FROM  table_1
      WHERE  "column_1" > c."column_1" and "colour" = 'red'
      ORDER  BY "column_1"
      LIMIT  1
      ) l
   )
SELECT *
FROM cte;

I tried this one too:

select column_1
from table_1
where "colour" = 'red'
group by column_1 ;

All queries are taking more time. Is there any other way?

0

There are 0 best solutions below