Hey all --
I'm semi-stuck on getting some SQL to do a job.
We have a bunch of widget data (>330m rows) with associations (>83m rows) to processed output/models (~167k rows)
We don't need that many associations, so we want to prune them down to no more than 1000-per output/model.
Now, I keep reading that its effectively a rule of thumb that if you're deleting more than you're retaining, you should create a new table with the data you're wanting to keep and swap it in, recreate indexes and constraints, then press on with your day.
I'm struggling with the "create table new_associations as " bit.
Assuming that the shape of things is roughly:
What I've done is
in order to duplicate the same table structure. Then, run the following PostgreSQL script:
I then go through the gyrations to rename the original table and rename the new table, rebuild indexes, etc.
While this WORKS, its super slow.
Help me turn this row-by-row (as folks have called slow-by-slow) process into a faster set-based operation?
I'm semi-stuck on getting some SQL to do a job.
We have a bunch of widget data (>330m rows) with associations (>83m rows) to processed output/models (~167k rows)
We don't need that many associations, so we want to prune them down to no more than 1000-per output/model.
Now, I keep reading that its effectively a rule of thumb that if you're deleting more than you're retaining, you should create a new table with the data you're wanting to keep and swap it in, recreate indexes and constraints, then press on with your day.
I'm struggling with the "create table new_associations as " bit.
Assuming that the shape of things is roughly:
Code:
create table widgets (
widget_id bigserial primary key,
.
process_date timestamp not null,
.
);
create table models (
model_id bigserial primary key,
.
.
);
create table associations (
widget_id int8 not null,
model_id int8 not null,
foreign key ( widget_id ) references widgets ( widget_id ),
foreign key ( model_id ) references models ( model_id )
);
What I've done is
Code:
create table new_associations as select * from associations where 1 = 0;
in order to duplicate the same table structure. Then, run the following PostgreSQL script:
Code:
do
$$
declare
f record;
begin
for f in select distinct model_id from associations order by model_id asc
loop
insert into new_associations ( widget_id, model_id )
select widget_id, model_id
from associations a
join widgets w
using ( widget_id )
where model_id = f.model_id
order by w.process_date desc
limit 1000;
commit;
end loop;
end;
$$
;
I then go through the gyrations to rename the original table and rename the new table, rebuild indexes, etc.
While this WORKS, its super slow.
Help me turn this row-by-row (as folks have called slow-by-slow) process into a faster set-based operation?