By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
Help with an interesting Postgres question: Why isn't an Index Only Scan used on a partition accessed via the parent table?.
CREATE TABLE names_table (name_id int, name text);
INSERT INTO names_table VALUES
(1, 'foo')
, (2, 'bar')
, (3, 'doo')
, (4, 'sue')
;
CREATE TABLE values_table (name_id int, value int, type text);
INSERT INTO values_table VALUES
(1, 90, 'red')
, (2, 95, 'blue')
, (3, 33, 'red')
, (3, 35, 'blue')
, (4, 60, 'blue')
, (4, 20, 'red')
;
4 rows affected
6 rows affected
SELECT name_id, n.name, v.blue, v.red
FROM (
SELECT name_id
, min(value) FILTER (WHERE type = 'blue') AS blue
, min(value) FILTER (WHERE type = 'red') AS red
FROM values_table
GROUP BY 1
) v
LEFT JOIN names_table n USING (name_id);
name_id | name | blue | red |
---|---|---|---|
1 | foo | null | 90 |
2 | bar | 95 | null |
3 | doo | 35 | 33 |
4 | sue | 60 | 20 |