Answer the question
In order to leave comments, you need to log in
How to optimize a PostgreSQL query?
Request
INSERT INTO client_4_level_group (client_id, level1, level2, level3, level4)
SELECT max(client_id), level1, level2, level3, 388 FROM client_4_level_group group by client_id, level1, level2, level3
HAVING COUNT(client_id) = (select count(*) from nomenclature_brand where nomenclature_brand_id != 388)
+---------------------------------------------------------------------------------------------------------------------------------------------+
| QUERY PLAN |
+---------------------------------------------------------------------------------------------------------------------------------------------+
| Subquery Scan "*SELECT*" (cost=61429.69..64038.44 rows=274606 width=20) (actual time=1314.545..1331.383 rows=20797 loops=1) |
| -> HashAggregate (cost=61429.69..63763.84 rows=274606 width=16) (actual time=1314.544..1327.734 rows=20797 loops=1) |
| Filter: (count(public.client_4_level_group.client_id) = $0) |
| InitPlan 1 (returns $0) |
| -> Aggregate (cost=1.77..1.77 rows=1 width=0) (actual time=0.040..0.040 rows=1 loops=1) |
| -> Seq Scan on nomenclature_brand (cost=0.00..1.45 rows=128 width=0) (actual time=0.009..0.025 rows=128 loops=1) |
| Filter: (nomenclature_brand_id <> 388) |
| -> Seq Scan on client_4_level_group (cost=0.00..20237.06 rows=2746057 width=16) (actual time=0.012..253.424 rows=2662848 loops=1) |
| Total runtime: 1577.023 ms |
+---------------------------------------------------------------------------------------------------------------------------------------------+
9 rows in set
Answer the question
In order to leave comments, you need to log in
store max(client_id) as a separate field so you don't have to aggregate each group?
SELECT max(client_id), level1, level2, level3, 388 FROM client_4_level_group group by client_id, level1, level2, level3
SELECT client_id, level1, level2, level3, 388 FROM client_4_level_group group by client_id, level1, level2, level3
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question