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 ArticleHow to use a recursive CTE to get ancestors in a hierarchy
create table division ( id serial primary key, name varchar not null);-- nested sets tablecreate table location ( id serial primary key, name varchar not null, division_id integer not null references...
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 ArticleWhy can't unused columns and tables be ignored in a recursive CTE
Usually, SQL Server can optimize away any unused columns in the execution plan, and unused joined tables are not queried. But as soon as a recursive CTE comes into play, apparently all columns and...
View ArticleI want to make a tree of parents only in sql server
my table in databasehow can i get my result as Where child = 'chl1'
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 ArticleOptimal way to get a total count of rows in a paged query in Postgres?
I need to improve the performance of a paged query for customer orders in a Type2 Postgres db (always insert a new record with a new ID, the newest ID is the current version of the record). Changing...
View ArticleImplementing First In / First Out for fuel transactions (such as purchases at...
After being tasked with trying to improve the way my company keeps the fuel inventory, i hit a wall. My SQL knowledge is pretty basic and i don't even know where to start.A little background:The...
View ArticlePostgreSQL Query Performance: Sorting Array Length vs. CTE
I'm having a significant performance difference between two PostgreSQL queries that I'm trying to understand and optimize. I have a table with around 2TB of data, and both queries use the sequential...
View ArticlePerformance difference using CTE and subquery
I have run the following queries.CTEWITH temp AS (SELECT id, timestamp FROM table group by timestamp, id)SELECT COUNT(*) FROM temp WHERE timestamp = '2023-01-01 08:28:45'SubquerySELECT COUNT(*) FROM...
View ArticleHow to use WITH in a better way to parametrise a date
I love to use CTEs to create nice and clear queries. However, I'm pretty sure the query I created is really inefficient.Is there a better way to do this and keep things clear ?with first_date as ( --...
View ArticleIndex is not used when doing a query with PostgreSQL CTE
Given I use the following table :CREATE TABLE operations ( asset_id varchar(255) NOT NULL, event_id varchar(255) NULL, updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP);and the following Index...
View ArticleFind best intersect (most elements) between Order (haystack) and Pricerules...
Full disclosureI have posted a greater scoped question at SO a couple of days ago with a bounty (no answers yet).Scope hereHow can a CTE be used to find a match with the most elements?For the order 403...
View ArticleHow to retrieve min/max values and corresponding dates in a table
I'm trying to figure how to retrieve minimum/maximum values and minimum/maximum dates from a data set, but also the date value that corresponds to each minimum/maximum value.Example Data:CREATE TABLE...
View ArticleINSERT result for SELECT FROM join'ed tables just modified
I have the task to insert data into couple tables and return data from their intersection in one query. The tables are linked through specific fields (solditems refers to products and invoices,...
View ArticleCreate JSON object from recursive tree structure
Having this simple many-to-many self-referential structure.An item owns other items through the joins table:CREATE TABLE items ( item_id serial PRIMARY KEY, title text);CREATE TABLE joins ( id serial...
View ArticleCommon Table Expression syntax
Considering a query with CTEs:WITH cte_0 AS ( SELECT SUM(col_0) FROM table_0 WHERE condition_00 AND condition_01 ), cte_1 AS ( SELECT SUM(col_1) FROM table_0 WHERE condition_10 AND condition_11 )...
View ArticleReturn the longest consecutive sequence of a value in specific column
I am using PostgreSQL 12.0 and trying to get the longest sequence of continuous rows for a specific column and value.The table is called team2 and contains a team's results which looks like:match_id...
View ArticleHow to match rows from relationship via a recursive CTE
Apologies for the terrible question title, I couldn't think how to describe this question in a single line.I have a schema that looks roughly like this:...
View ArticleHelp with CTE syntax in SQL
I am new to SQL, I tried to create a CTE, but I get a red squiggle under the AS and I am getting an error message in the process of executing the syntax:Msg 102, Level 15, State 1, Line 117 Incorrect...
View ArticleUnable to use INSERT within CTE
I am trying to use a CTE to insert some random data into a table -create table foo (id integer)with x as (select random()) insert into foo (id) select x from xThis gives an error:ERROR: column "id" is...
View ArticleHow can I optimize a recursive CTE inside a IVTF?
I have a recursive CTE inside a inline table-valued function. The ITVF is returning a list of IDs containing a long sequence of ancestors for a person, it usually loops back about 12 to 18 times before...
View ArticleWhy is PostgreSQL performing a sequential scan, except when my CTE is...
The issueMy application is encountering performance issues on a query that, to the best of my understanding, should be performant. In this post, I have simplified the query and schema while still...
View ArticleGrouping values into buckets
I'm working a query and I wasn't sure if my current approach is the "best" approach.I got a table filled with values and a table with buckets that I use to group those values.There are 2 types of...
View ArticleRecursive CTE hiearchy snowflake -- join/ expand outward (columns) instead of...
I'm doing a dependency mapping explosion (like parts explosion).I did a typical recursive CTE with a union all.It looks likewith CTE as( select abc from myTable where start_point = Xunion allselect abc...
View ArticleUpgrade from Postgres 11 to Postgres 12 made some queries 300x slower,...
My application currently uses PostgreSQL 11.6. Today, I have tested PostgreSQL 12.1 on a virtual machine and the results were shocking:One important query which takes 100ms on version 11 (same VM) now...
View Article
More Pages to Explore .....