Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows of a table specified in a text file in Postgres

I have a text file containing the row numbers of the rows that should be deleted in my table like this:

3
32
40
55
[...]

How can I get a PostgreSQL compatible SQL statement which deletes each of these rows from my table using the text file?

like image 758
ptikobj Avatar asked Oct 05 '11 09:10

ptikobj


People also ask

How do I delete a specific row in PostgreSQL?

The PostgreSQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows.

How do I delete multiple records in PostgreSQL?

Firstly, use the DELETE query followed by the FROM keyword. Afterward, specify the targeted table's name. Next, specify a column name in the WHERE clause, and finally, specify the IN operator followed by two parentheses. Within parentheses, specify the list of rows that you want to delete.

How do I delete a specific table in PostgreSQL?

DROP TABLE removes tables from the database. Only the table owner, the schema owner, and superuser can drop a table. To empty a table of rows without destroying the table, use DELETE or TRUNCATE . DROP TABLE always removes any indexes, rules, triggers, and constraints that exist for the target table.


2 Answers

Doing it once could look like this:

CREATE TEMP TABLE tmp_x (nr int);

COPY tmp_x FROM '/absolute/path/to/file';

DELETE FROM mytable d
 USING tmp_x
 WHERE d.mycol = tmp_x.nr;

DROP TABLE tmp_x;

For repeated use, wrap it into a plpgsql function with file-path / table name / column name as parameters. If table or column name are dynamic you have to use EXECUTE for the DELETE.

like image 176
Erwin Brandstetter Avatar answered Sep 19 '22 00:09

Erwin Brandstetter


I have a slightly different solution than Erwin's. I would use IN because performing a JOIN (USING) it would increase the number of rows that the query will process.

CREATE TEMP TABLE tmp_x (nr int);

COPY tmp_x FROM '/absolute/path/to/file';

DELETE FROM mytable d
 WHERE d.mycol IN (SELECT nr FROM tmp_x);

DROP TABLE tmp_x;
like image 24
Ulises Avatar answered Sep 21 '22 00:09

Ulises