What's the (Big O) computational complexity of a PostgreSQL recursive common...
For example, taking this StackOverflow #44620695 question, recursive path aggregation and CTE query for top-down tree postgres as an example, which uses a recursive CTE to traverse a tree structure to...
View ArticleHow to make use of WITH in PostgreSQL to reduce query cost
I am trying to get twitter data of narendramodi using below command.SELECT b.t_id,a.profile_image,b.tweet_text,e.media_media_url,b.retweet_count,b.favorite_count as like_count,count(reply_to_status_id)...
View ArticleInsert multiple rows into a table with id from other table if not exists...
I have done similar task where I can insert a row into a table if data doesn't exists:WITH user_exists AS ( Select id from users where username='%s' ), user_new AS ( INSERT INTO users (username) SELECT...
View ArticleUnrecognized configuration parameter when using set_config(text, text,...
I'm trying to implement a simple ABAC system using row level security, with main policy defined as following:CREATE policy resource_access ON resourceUSING ( ( org_id::varchar =...
View ArticleOptimizing a recursive CTE or replacing it with a temporary table
I have a recursive query like this:with recursive PCte(id) as ( select p1.id from Product p1 where p1.parent_id is null and p1.serial_number in ('123', '124','125', 'n') union all select p2.id from...
View ArticleHow to create multiple temp tables using records from a CTE that I need to...
I am already using a CTE expression within a plpgsql Procedure to grab some Foreign Keys from (1) specific table, we can call it master_table. I created a brand new table, we can call this table...
View ArticleDifference between a query based on CTE and a simple query
i'm doing a select starting from a table named events that is joined with device measurements using a date between function (this time between is a sort of "mobile windowing") in order to get the...
View ArticleCan EXPLAIN be used to get some insights about Common Table Expression (CTE)?
I need to find the ancestors in a table having an ID value and a Google research point me to recursive Common Table Expression (CTE) I wonder if EXPLAIN can be used to get some insights on how MySQL...
View ArticleHow to make a Data Modifying CTE abort if an update only partially succeeded?
I am wondering if it is possible to add some kind of check to make a data modifying CTE abort if an update is partially successful. Attached is a minimal query that represents the problem. I would like...
View ArticleCount 2 tables same query - PG 9.3
I've got two tables that I need a count on both of them.table1: idtable2: cid (table1.id = table2.cid) -- Join can be done by this.I already got two queries that I'm using, and wanna put them in one...
View ArticleWhen generating combinations using a CTE, is there a way to use an index to...
I have a project that involves combining a variety of things into their possible combinations. This includes permutations, combinations, with and without repetition, and some more exotic ways of...
View ArticleGetting sum for each day based on most recent timestamp entry for each entity
I have a table that contains an ID, timestamp, and integer. Each row is a "snapshot" of the entity at a given time:TableAIDtimestampnumA2024-02-045B2024-02-043C2024-02-078A2024-02-073My goal is to get...
View Articlecreating a CTE to filter previous CTE populaiton down. How to find new...
The first CTE grabs all patients with the diagnosis codes for substance abuse, the second CTE should filter down to only NEW paitents.Meaning of the people in the first CTE, which of thses people have...
View ArticleCTE where to place the where clause to filter rows sooner (in postgresql)?
I have function with CTE which looks like this:function param(p_userId, p_templateId) with a(select...), b (select..), c (insert..returning..), d (update..returning..), ...k(select..) insert ... select...
View ArticlePostgreSQL CTE behavior influenced by outer `update` statement: Why?
tl;drWhy does an update from ... statement make a CTE behave differently than an update where... with subquery statement in postgresql?Full ContextDisclaimer: The information below has been sanitized...
View ArticleHow do I calculate a streak of data and show the data that corresponds to it...
I'm currently working on a project with NBA stats and I want to check a player's longest streak of his highest amount of points on MySQL. I'm open to a 5-10 game streak to simplify it.For example:...
View ArticleLocking for update inside CTEs
If I make a query using CTEs that looks like that:WITH cte_a AS ( SELECT a.id, a.something FROM a WHERE a.something IS NOT NULL ),-- [...] some other CTEscte_d AS ( SELECT cte_a.id, cte_a.something...
View ArticleTrouble with slow stored procedure performance on 35M rows with CTE/Temp table
We recently went through a new feature release to our app that added about 25 new columns to a large table (~35 million rows), and now we're having some major query performance issues. I assume that it...
View ArticlePostgreSQL window function: Add value in CASE running sum gets below threshold
For context:I am playing with a filling level sensor, a water tank and a watering pump and have the following problem:I have an initial filling value for my tank.Each time step, I am subtracting a...
View ArticleRecursively sum child's nominal to parent, on dynamic level parent-child...
i have data look like this :i try to sum the Nominal column to each respective parent, so it will looks like this :i provided the sql script for the data :SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER...
View ArticlePostgreSQL CTE Recursion - How to Improve Performance for Parent->Child Tree...
I am working on a query that performs PostgreSQL CTE Recursion in PostgreSQL 13. This query is intended to recurse from the root nodes to the deepest leaf node with certain properties (labeled 'begat'...
View ArticleAre non-used CTEs never materialized in PostgreSQL 16?
I want to return my post rows in one of three sort orders, controlled by a sorting_param function parameter. The sorting is complex, doesn't lend itself to a simple ORDER BY CASE .... So I'm thinking...
View ArticleWhy delete and insert in a CTE works despite UNIQUE constraint?
Given a table with a unique constraint on a columnCREATE TABLE t( id int GENERATED ALWAYS AS IDENTITY, name text NOT NULL UNIQUE);Let's create a single recordINSERT INTO t (name) VALUES ('a');When I...
View Articleoracle working with CTE with condition
DEFINE fromtable1= true;WITH firstQuery AS ( SELECT columns FROM table),secondQuery AS ( SELECT columns FROM second_table) IF @fromtable1= true BEGIN SELECT * FROM firstQuery ENDELSE BEGIN SELECT *...
View ArticleSQL Server query with common table expression suspended with pageiolatch_sh
I have a cte based query which runs for a very long time, and on the Activity Monitor for the query there are multiple rows showing the query is suspended in pageiolatch_sh. The strange thing is that...
View ArticleWhat are use cases for Recursive CTEs?
I am looking for examples of why you would use a recursive CTE, but the dozens of examples I have found in my web searching basically reduce to two:Generating a sequenceIterating through an employee...
View ArticleRepeated CTEs vs Recursive CTE
I'd like to ask which of the following two functions is better for retrieving a hierarchical list of child items from a table. Here are the two function definitions:Version 1 (Recursive CTE):CREATE OR...
View ArticleHow to adapt a recursive CTE over multiple tables?
I'm using PostgreSQL 17I am modelling a package index for the Haskell ecosystem, and a feature that is useful is to determine transitive dependencies. Haskell packages can be normalised as:Package...
View ArticleCreate a plan guide to cache (lazy spool) CTE result
I normally create plan guides by first constructing a query that uses the correct plan, and copying it across to the similar query that doesn't. However, that is sometimes tricky, especially if the...
View ArticleCTE Error when installing sp_WhoIsActive
I have several identical (near as I can tell) SQL Servers where I've recently added sp_WhoIsActive (showing some folks how much I like this tool) but one of them will not let me create the stored...
View Article