0

I have a db with multiple tables. The tables have all the same structure with one column called date and a bunch of other columns with various data.

I can remove the duplicates from a single table as follow:

DELETE FROM table1
WHERE EXISTS (
    SELECT 1 FROM table1 p2
    WHERE table1.date = p2.date
    AND table1.ROWID > p2.ROWID
)

I have about 30 tables to clean regularly. Although I could run the above code for each table, is there a way to do this via a for loop after getting the list of tables in the db as:

SELECT name FROM sqlite_master WHERE type='table'

1 Answer 1

2

Here's a script that generates & runs individual DELETE statements for each table: --> Loops through the table list and remove duplicates from each table

BEGIN;
 FOR table_name IN (SELECT * FROM table_list) DO
   EXECUTE IMMEDIATE 'DELETE FROM ' || table_name.name || ' WHERE ROWID NOT IN (
     SELECT MAX(ROWID) FROM ' || table_name.name || ' GROUP BY date
   )';
 END FOR;
COMMIT;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.