Since you are only interested whether any row with qualifying status
exists in the table designer_orders
, the most obvious query style would be an EXISTS
semi-join. Typically fastest with potentially many duplicate rows in n-table:
SELECT COUNT(o.id) AS no_of_orders
,SUM(o.total) AS total
,SUM(o.shipping) AS shipping
FROM orders o
WHERE EXISTS (
SELECT 1
FROM designer_orders d
WHERE d.state = ANY('{pending, dispatched, completed}')
AND d.order_id = o.id
);
-> SQLfiddle demo
For fast SELECT
queries with bigger tables (and at some cost for write performance), you would have a partial index like:
CREATE INDEX designer_orders_order_id_idx ON designer_orders (order_id)
WHERE state = ANY('{pending, dispatched, completed}');
The index condition must match the WHERE
condition of the query to talk the query planner into actually using the index.
A partial index is particularly attractive if there are many rows with a status
that does not qualify. Else, an index without condition might be the better choice overall.