Skip to content

Commit 62182ab

Browse files
committed
Refactor get-lists query for speed
1 parent a22b274 commit 62182ab

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

queries.sql

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -294,11 +294,16 @@ UPDATE subscriber_lists SET status='unsubscribed', updated_at=NOW()
294294

295295
-- lists
296296
-- name: get-lists
297-
SELECT COUNT(*) OVER () AS total, lists.*, COUNT(subscriber_lists.subscriber_id) AS subscriber_count
298-
FROM lists LEFT JOIN subscriber_lists
299-
ON (subscriber_lists.list_id = lists.id AND subscriber_lists.status != 'unsubscribed')
300-
WHERE ($1 = 0 OR id = $1)
301-
GROUP BY lists.id ORDER BY %s %s OFFSET $2 LIMIT (CASE WHEN $3 = 0 THEN NULL ELSE $3 END);
297+
WITH ls AS (
298+
SELECT COUNT(*) OVER () AS total, lists.* FROM lists
299+
WHERE ($1 = 0 OR id = $1) OFFSET $2 LIMIT $3
300+
),
301+
counts AS (
302+
SELECT COUNT(*) as subscriber_count, list_id FROM subscriber_lists WHERE status != 'unsubscribed' GROUP BY list_id
303+
)
304+
SELECT ls.*, COALESCE(subscriber_count, 0) AS subscriber_count FROM ls
305+
LEFT JOIN counts ON (counts.list_id = ls.id) ORDER BY %s %s;
306+
302307

303308
-- name: get-lists-by-optin
304309
-- Can have a list of IDs or a list of UUIDs.

0 commit comments

Comments
 (0)