Compare two databases
This recipe compares two databases: first their schema, then the rows of a table. The examples compare two SQLite files, old.db and new.db, with the shell bash and the program diff. The two databases can also be of different kinds.
Compare the schema
Section titled “Compare the schema”--schema-only writes the schema of a database as a script, with no rows. diff shows the lines that differ between the two scripts:
diff -I restrict <(usql -D --schema-only old.db) <(usql -D --schema-only new.db)15c15< CREATE TABLE products (id integer primary key, name text not null, price real not null);---> CREATE TABLE products (id integer primary key, name text not null, price real not null, stock integer not null default 0);Each dump holds a \restrict line with a new random key. -I restrict makes diff ignore those lines.
To compare a database of one kind with a database of another kind, write both dumps for the same database with --target, such as --target sqlite3. Dump a database explains the options.
Compare the rows
Section titled “Compare the rows”Write the rows of each table as CSV, in the same order, and compare them. Name the columns, so that a column that only one table has does not count:
q='select id, name, price from products order by id'diff <(usql -C -c "$q" old.db) <(usql -C -c "$q" new.db)3c3< 2,Coffee,3.25---> 2,Coffee,3.54a5> 4,Chai,4.75The row with the id 2 has another price, and the row with the id 4 is only in new.db.
Compare the rows with SQL
Section titled “Compare the rows with SQL”For a large table, copy the rows of both databases into DuckDB, and let except find the rows that differ. Save this script as compare.sql:
create table old_products (id integer, name text, price double);create table new_products (id integer, name text, price double);\copy sq:old.db dk:compare.duckdb 'select id, name, price from products' old_products\copy sq:new.db dk:compare.duckdb 'select id, name, price from products' new_productsselect 'only in old' as side, * from (select * from old_products except select * from new_products)union allselect 'only in new', * from (select * from new_products except select * from old_products)order by id, side;Run it on a new DuckDB file:
usql -f compare.sql dk:compare.duckdbCREATE TABLECREATE TABLECOPY 3COPY 4 side | id | name | price-------------+----+--------+------- only in new | 2 | Coffee | 3.5 only in old | 2 | Coffee | 3.25 only in new | 4 | Chai | 4.75(3 rows)Copy data between databases explains \copy.