pg_dump and mysqldump With a WHERE Clause: Copy a Prod Slice

You rarely need a copy of production. You need the one account that hit the bug, the rows it points at, and enough of the surrounding tables that the foreign keys still resolve. A pg_dump where clause would be the obvious way to ask for that. pg_dump will not do it. The flag is not hiding under another name.
pg_dump --help on PostgreSQL 16.15 lists --table and --data-only. It lists --where zero times. The pg_dump manual describes a consistent backup of tables, schemas, or a whole database. A row filter is a query. mysqldump, by contrast, grew --where years ago, and it has a sharp edge: one condition is applied to every table in that run.
This page is the workflow that replaces the missing flag. Schema with the dump tool, rows with a query, parents before children, personal data masked in the query so production is never updated to hide it. The SQL was run on PostgreSQL 16.15 and MySQL 8.0.46. The last section says what a client can automate, and it is optional. The commands work without one.
Getting a session to the server is a separate problem. If the database is on RDS and your laptop is not, start with connect to RDS from a local machine.
Why pg_dump has no WHERE
pg_dump’s job is a consistent snapshot. It opens a repeatable-read transaction (or uses a snapshot export when you run in parallel) and copies the tables you named. A WHERE clause is per table, often per run, and it has to stay consistent with the foreign keys you also want. That is application logic. The tool copies objects.
What it will limit:
pg_dump --schema-only --no-owner --no-privileges -f schema.sql mydb
pg_dump --data-only --table=orders --table=customers -f rows.sql mydb
--schema-only is the right first step for a slice. You want the tables, constraints, and indexes on the destination, then a small set of rows. --data-only on two tables copies every row of those tables. That is “specific tables”, which is a different and much larger request than “this customer”.
--no-owner and --no-privileges matter when the destination is a database on your machine. Production roles do not exist there, and the restore fails on the first ALTER ... OWNER TO if you leave them in.
The lock behaviour is the part people worry about. The manual says pg_dump does not block other users accessing the database, readers or writers. It still requests ACCESS SHARE on each table, which conflicts with the exclusive lock taken by DROP, TRUNCATE, and some ALTER TABLE forms. --lock-wait-timeout=5s fails the dump if it cannot get that shared lock, instead of queueing behind a migration. Use it when a deploy might be altering tables at the same time.
A full pg_dump of a busy database is safe in the “will not corrupt” sense and expensive in the “reads a lot of the heap” sense. A slice should not start from a full dump that you then edit.
Postgres: schema with pg_dump, data with \copy
Create the empty destination and load the schema into it:
createdb slice
pg_dump --schema-only --no-owner --no-privileges --schema=public mydb | psql --dbname=slice
Then copy rows with psql’s \copy. The query runs on the server. The file is written on the client. That distinction matters: SQL COPY ... TO '/tmp/file' writes on the database server and needs a superuser or the pg_write_server_files role (COPY). \copy writes where psql is running, which is what you want when production is remote.
This is the command that was run, against a table of generated people, and the file it wrote:
\copy (SELECT id, 'user' || id || '@example.test' AS email, created_at FROM people WHERE id <= 2 ORDER BY id) TO '/tmp/people-slice.csv' CSV HEADER
id,email,created_at
1,user1@example.test,2024-06-20
2,user2@example.test,2024-11-12
The real emails never entered the file. The mask is in the SELECT, so the production table is not updated. Load the file into the destination:
\copy people (id, email, created_at) FROM '/tmp/people-slice.csv' CSV HEADER
Run that \copy connected to the slice database, not to production. Check SELECT current_database(); first if you are tired. The header row names the columns. The column list on the \copy has to match the file. If the destination table has more columns, name the ones you are filling and let the rest take defaults or NULL.
For a query you will re-run, put it in a file and use psql -f. \copy is a psql command, not a server statement, so it cannot sit in a migration that runs through a driver. Drivers should use COPY ... FROM STDIN or just INSERT. For an interactive slice, \copy is the one you want.
A practical shape for one customer:
SELECT o.id, o.customer_id, o.total_cents
FROM orders o
WHERE o.customer_id = 42;
Save that result, then the customer row, then the payments, each as its own \copy. The next section is how to choose those queries so the foreign keys load.
MySQL: mysqldump –where
mysqldump 8.0.46 documents -w, --where=name as “Dump only selected records.” This invocation was run against a parent table that contained two rows:
mysqldump --no-create-info --where="id=1" proof parent
The output included the comment -- WHERE: id=1 and a single insert of the row whose id was 1. --no-create-info keeps the dump to rows, which is what you want when the schema is already loaded. Add --single-transaction for InnoDB so the dump is one consistent snapshot instead of locking the tables for the whole run. --lock-tables defaults to on. --single-transaction turns that off. Combined with --source-data, it takes a short global read lock at the start. --single-transaction on its own does not take that lock, unless the server has GTIDs on (8.0.32+), where it takes it briefly. It does not apply to MyISAM. If you still have MyISAM tables, a consistent slice of them is a different problem. Convert them, or accept a lock. The mysqldump manual is the reference for both options.
The sharp edge: --where is one string, applied to every table in the command. Asking for parent and child with --where="parent_id=1" failed on parent with:
Unknown column 'parent_id' in 'where clause'
The child table has parent_id. The parent table does not. mysqldump does not attach a different condition to each table. Run it once per table, with a condition that table can satisfy:
mysqldump --single-transaction --no-create-info --where="id=1" proof parent > parent.sql
mysqldump --single-transaction --no-create-info --where="parent_id=1" proof child > child.sql
Quote the condition. The shell will eat it otherwise. id = 1 needs quotes around the whole value because of the spaces: --where="id = 1".
Load into the destination in parent-then-child order:
mysql --database=slice < parent.sql
mysql --database=slice < child.sql
mysqldump files turn foreign key checks off for the session that loads them, so a child-first load will not fail. Load parents first anyway, then run the orphan query below. It is the only check that runs.
mysqldump writes INSERT statements, not a CSV. That is convenient to reload and inconvenient to mask. A masked MySQL slice is usually a SELECT ... INTO OUTFILE on a server you control, or a client-side query. Do not UPDATE production to scrub a column and then dump it. Select the masked expression.
SELECT id,
CONCAT('user', id, '@example.test') AS email
FROM customers
WHERE id = 42;
The same expression works in a report and in a file. INTO OUTFILE writes on the database server and is constrained by secure_file_priv. For a laptop copy, the mysql client in batch mode is easier:
mysql --batch --raw proof -e "SELECT id, CONCAT('user', id, '@example.test') AS email FROM customers WHERE id = 42" > customers.tsv
Keeping foreign keys consistent
Pick a root row. Walk out to the rows it needs, and walk in from the rows that need it. For a customer bug, the root is the customer. You need:
- the customer
- their orders
- the products those orders reference
- the payments and shipments that reference the orders
You do not need every customer who bought the same product. That way lies a full copy. Stop at the parents of your rows and the children of your rows. Skip the siblings.
A concrete check, the kind that was used on a generated parent and child (800 orders, zero orphans) before trusting the load:
SELECT count(*) AS orphans
FROM orders o
WHERE NOT EXISTS (
SELECT 1 FROM people p WHERE p.id = o.person_id
);
Run that on the destination after the load. Zero is the only acceptable answer if the foreign key is NOT NULL. If the column is nullable, decide whether a NULL parent is real data or a hole, and count those separately.
Order of load:
- Reference tables you touched (products, countries), or the subset of them your rows use.
- The root (customers).
- Children (orders, then order lines, then shipments).
Circular foreign keys (an order points at a shipment that points back at the order) need one of the columns loaded as NULL and updated after, or a deferred constraint. PostgreSQL can declare a constraint DEFERRABLE INITIALLY DEFERRED. MySQL checks foreign keys immediately. If you hit a cycle, load with checks off, then turn them on and hunt the orphans. Do not leave checks off.
Self-referential trees, such as a comment whose parent is another comment, need every ancestor of the rows you care about. A recursive query is the right tool there. Copying “the whole table because the tree is hard” is how a slice becomes a dump.
Masking personal data before it leaves production
The safe mask is an expression in the SELECT. The unsafe mask is an UPDATE on production followed by a dump, or a dump of the raw column “that we will clean up later”. Later does not happen, and the file is already on a laptop.
Decide, per column:
- Drop it. You do not need the phone number to reproduce a rounding bug. Omit the column.
- Replace it. Emails become
userplus the id atexample.test.example.testis a reserved name, so a bug that sends mail does not hit a real domain. Names become an initial. Free text that customers typed is the dangerous column. Read one sample before you decide it is harmless. It often contains an address. - Keep it, narrowly. A postal code might be required to reproduce a tax bug. Keep the code, drop the street.
- Keep a stable pseudonym. If two tables must still join on “the same person” and the id already does that, you do not need a fake email to match. If the bug is in the email parser, keep the structure (
a@b) and replace the parts.
Do this in the query that writes the file, as in the \copy above. Then the production backup and the slice are different objects. A teammate who restores the slice does not get a second copy of the real inbox.
Secrets, access tokens, session ids, and password hashes should not be in the slice at all. A hash is not “safe enough” on a laptop. Omit the column and let the destination use a known test password if the app requires one.
If the slice is for a staging environment other people can log into, treat it as production data until the mask is done, and as test data after. Those are different access rules. Do not point the staging app at the slice until the orphan check and the mask check have both been run.
Tools that automate subsetting
Specialist tools exist because the walk above is tedious on a schema with hundreds of foreign keys. fixturize follows foreign keys from a root predicate. pg_subsetter copies a fraction of every table, plus rows you force in with -include, and does not create the schema. pg_partialcopy does not walk foreign keys from a root predicate. They were not run for this article, and this article does not link out to their source trees. Read their own docs if you adopt one, and still mask personal data. A tool that copies the right rows will faithfully copy a passport number if you do not tell it otherwise.
You do not need them for a handful of tables. Two \copy commands and an orphan count are easier to review than a new dependency. You do need them, or a script you generate from information_schema, when every bug reproduction starts with an hour of drawing arrows. That script should live in the application repo so the next person can see which root predicate you used.
Whatever you use, keep the output small enough to inspect. A “subset” that is 40 percent of production has the same privacy problem as production and a worse story about why it was copied.
A client can do this too
The SQL above is the whole method. A client is a convenience when you do this often and you want the walk and the destination picker in one place.
MoleDB can copy a slice from a connection, including production, into a SQLite file or a PostgreSQL connection marked Local. The source is only read. You set a row limit and you can include related rows. The screenshots are that flow: choosing the slice, and the finished copy. They are not a substitute for the orphan check. If you would rather not use a client, the \copy and mysqldump --where sections are complete.


How the Mac clients compare, beyond this one feature, is in best Postgres client for Mac.
Safety checklist
- Use a database user that can
SELECTand cannotINSERT,UPDATE,DELETE, orDROP. A slice is a read. - Run it on a replica if you have one. The data is a moment behind production, which is what you want for a bug report, and the IO does not land on the primary.
- Set a timeout on the session that runs the
SELECT. In PostgreSQL,SET statement_timeout = '30s';cancels a runaway predicate. In MySQL,SET SESSION max_execution_time = 30000;is the millisecond equivalent forSELECT. SELECT count(*)with the same predicate before you copy. If the count is six figures, the predicate is wrong.- Mask in the
SELECT. Do not update production. - Load into an empty database, parents first, then count orphans.
- Do not commit the dump file. It is data, even after masking. Put it somewhere the team already treats as sensitive, or delete it when the bug is understood.
- If you cannot bound the rows, do not copy them. Generate dummy data for Postgres is the alternative when the bug is about volume and shape rather than one real customer’s history.
FAQ
Can pg_dump use a WHERE clause?
No. pg_dump 16.15 has no --where flag. Its --help lists --table and --data-only, and the option count for --where is zero. Filter in the query you pass to psql's \copy, or dump the schema with pg_dump and the rows with a SELECT. mysqldump does have --where, and that flag applies to every table in the same invocation.
Does pg_dump lock tables?
It takes a shared lock so the table cannot be dropped while the dump runs, and the PostgreSQL 16 manual says pg_dump does not block other users accessing the database, readers or writers. Ordinary INSERT, UPDATE, and DELETE proceed. DROP, TRUNCATE, and forms of ALTER that need an exclusive lock wait. --lock-wait-timeout makes the dump fail instead of waiting forever for that shared lock.
Is pg_dump safe to run on production?
It is a supported way to back up a live database, and it does not block readers or writers. It still reads the whole table you point it at, which costs IO, and a naive full dump of a large production database is the wrong tool for a one-customer bug. Prefer a filtered copy, run it against a replica when you have one, set a statement timeout on the session that does the SELECT, and use a user that cannot write.
How do I dump only data for specific tables?
pg_dump --data-only --table=orders --table=customers writes those tables and not the rest of the database. Repeat --table for each name. Patterns work, and they are easy to over-match, so list the names when the set is small. --data-only skips the CREATE TABLE. Dump the schema once, separately, and load it before the rows so foreign keys exist.
Where does pg_dump save the file?
Wherever -f points. pg_dump -f orders.sql writes orders.sql in the current directory of the machine running pg_dump, which is your computer if you ran it there, not the server. Omit -f and it writes to standard output, which you can redirect. The custom format (-Fc) is a single file that pg_restore reads. Plain SQL is a text file you can open.

