aboutsummaryrefslogtreecommitdiff
path: root/content/posts/postgres-aggregates/merging-ctes.sql
diff options
context:
space:
mode:
authorMartin Kagamino Lehoux <martin@lehoux.net>2023-09-23 20:19:44 +0200
committerMartin Kagamino Lehoux <martin@lehoux.net>2023-09-23 20:19:44 +0200
commit20219dd4f7192c61492b7667dd3f15b05dbba044 (patch)
tree14d436e34d52ddea4517bb2c2ed8de9fe414e609 /content/posts/postgres-aggregates/merging-ctes.sql
parent7455ccba6c2e42006ecb606a3043d4407a2a774e (diff)
feat: Add post to version control
Diffstat (limited to 'content/posts/postgres-aggregates/merging-ctes.sql')
-rw-r--r--content/posts/postgres-aggregates/merging-ctes.sql34
1 files changed, 34 insertions, 0 deletions
diff --git a/content/posts/postgres-aggregates/merging-ctes.sql b/content/posts/postgres-aggregates/merging-ctes.sql
new file mode 100644
index 0000000..2061efd
--- /dev/null
+++ b/content/posts/postgres-aggregates/merging-ctes.sql
@@ -0,0 +1,34 @@
+EXPLAIN (
+ ANALYZE,
+ COSTS,
+ VERBOSE,
+ BUFFERS
+) WITH product_reviews AS (
+ SELECT
+ product_id,
+ COUNT(id) AS num_reviews
+ FROM
+ reviews
+ GROUP BY
+ product_id),
+ product_orders AS (
+ SELECT
+ product_id,
+ COUNT(id) AS num_orders
+ FROM
+ orders
+ GROUP BY
+ product_id
+)
+ SELECT
+ products.id,
+ products.name,
+ COALESCE(product_reviews.num_reviews, 0) AS num_reviews,
+ COALESCE(product_orders.num_orders, 0) AS num_orders
+FROM
+ products
+ LEFT JOIN product_reviews ON products.id = product_reviews.product_id
+ LEFT JOIN product_orders ON products.id = product_orders.product_id;
+
+-- WHERE
+-- products.id % 10 = 0