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 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 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 ArticlePostgreSQL 16: WITH/CTE versus Non-Deferrable Constraints
I am using PostgreSQL 16 upwards.I am currently trying to create an example for a relationship of type G-|o-----|<-H in Crow's foot lingo.This means that each row in the table g for entity type G...
View Articleis it possible to make the CTE parallel in PostgreSQL 14
I have an analyse query in PostgreSQL 14 that use many CTEs, like this:witha0 as (select count(*) from ccc0) , a1 as (select count(*) from ccc1) , a2 as (select count(*) from ccc2) , a3 as (select...
View ArticleQuery Locks Table And Takes Long Time to Run
I have a query that can take a long time to run. I tried running the same query in a test server and it runs very quick.However, in production it seems to hang and causes blocking of other...
View ArticleList Top Daily Rentals Per Customer using a CTE
I've been trying to learn CTEs and having a bit or trouble getting the hang of them. I wrote a query against the Sakila Sample database that lists information about horror movie rentals for each day....
View ArticleQuery To Show YTD Total Summing Each Month Prior To Current
I need a query to give a YTD total that should sum each month before it. For example, January YTD would equal January Total, February YTD would equal January Total + February Total, March YTD would...
View Articlecalculate or get price of parent items on bill of materials
i want to calculate or get the price of parent items on bill of materials queryhere is the fiddle-> https://www.db-fiddle.com/f/o3jLgZxKNLG14mna8QGdVN/6please note in the second row, betax has qty =...
View Article