PostgreSQL / Basic: relational foundations / Lesson 7
Import a small CSV fixture with COPY
Distinguish server and client file boundaries and validate a controlled CSV import.
On this page
Lesson goals
- Explain COPY FROM STDIN and the psql input boundary.
- Import a synthetic fixture with explicit columns.
- Verify counts, constraints, and recovery for a failed import.
- Distinguish PostgreSQL server COPY from psql client file access.
- Validate CSV mapping, keyed rows and transactional publication with independent evidence.
Define the import contract
Before loading data, identify the source owner, encoding, delimiter, header, column order, missing-value representation, expected types, and target table. Specify whether a failed batch should be rejected or handled by a documented exception policy. Use synthetic data in a disposable PostgreSQL 18 lab. An import that completes without a syntax error still needs checks for completeness and business meaning.
Load a small psql input stream
The following example is intended for psql connected to a new disposable lab, not an application database. COPY FROM STDIN receives data from the client; in this psql script, a line containing backslash and dot ends the inline data. The explicit column list and CSV header clarify the fixture. Other drivers have their own COPY interfaces and do not necessarily interpret psql commands.
CREATE TABLE lab_import (id integer PRIMARY KEY, item text NOT NULL, quantity integer NOT NULL CHECK (quantity > 0));
COPY lab_import (id, item, quantity) FROM STDIN WITH (FORMAT csv, HEADER true);
id,item,quantity
1,Notebook,2
2,Pen,5
\.
The fixture declares two rows, with quantities two and five. The end marker belongs to psql’s inline input handling. The table constraint rejects nonpositive quantities; no live execution is claimed.
Reconcile the loaded rows
Read the imported data and compare counts and totals with the source manifest. Explicit ordering makes a row-by-row inspection predictable. The following read-only queries operate on the same lab fixture; in a real import, add domain checks, rejected-record accounting, and duplicate detection appropriate to the source. Avoid logging private source records while diagnosing discrepancies.
SELECT id, item, quantity FROM lab_import ORDER BY id;
SELECT count(*) AS imported_rows, sum(quantity) AS total_quantity FROM lab_import;
Given the declared input, the expected count is 2 and total quantity is 7. This is a calculation from the fixture, not a measured production result. A matching total alone cannot prove that every field was mapped correctly.
Know which machine reads a file
A server-side COPY naming a file accesses the server’s filesystem and has specific privilege requirements. psql’s client-side copy facility reads a client file and routes its data through the connection. These are different operational boundaries. Use approved paths and permissions, and verify the target database and schema before loading anything. Never assume that a file visible on the client exists on the database server.
Test failure and recovery
On disposable data, test a malformed row, a duplicate key, and an invalid quantity using the chosen transaction and error-handling procedure. Determine what the driver or tool reports and how the application rolls back or reconciles the batch. Keep a source manifest and stable batch identity so a retry does not silently duplicate work. Recheck row-level examples and aggregate totals after the approved correction.
Define the import contract
A controlled import begins with a specific file, column mapping, encoding, delimiter, quote rules and expected row grain. In the training fixture two item rows have quantities 2 and 5, so the expected count is two and the sum is seven. Those totals are useful checks but do not prove that each item received the correct quantity; inspect the individual keys and values as well. Document whether a header is present and what missing, empty and invalid fields mean before loading.
Use a disposable staging table and a synthetic file for rehearsal. Record the intended database, schema, table definition, source file identity and permissions before running a command. COPY can change database contents or read and write files, so the illustrative blocks below are non-runnable and no server or file was accessed. Never point a training import at production or learner data.
Distinguish client and server files
Server-side COPY FROM a file asks the PostgreSQL server process to read a path on the server filesystem with the server’s permissions. A path visible to psql may exist only on the client machine or in a different container. psql’s \copy is a client meta-command that transfers data through the client connection, so its file access boundary is different. Choose deliberately and verify the documented permissions and path for the actual deployment.
COPY FROM STDIN can also receive data through a client connection, with the client responsible for supplying the stream. A database role’s table privileges and server-file privileges are distinct concerns; do not grant broad server-file access merely to make a lab command work. Record which process reads the file, which identity can access it and where errors are reported. A local test path does not prove that a remote server can see it.
Specify CSV semantics and mapping
CSV is a format contract, not just commas. Define HEADER behavior, delimiter, quote and escape rules, encoding and column order. A quoted comma belongs within a field; a missing field, an empty string and a NULL marker can have different meanings depending on COPY options and quoting. Use an explicit target column list so the file’s first field maps to the intended column rather than relying on table order. Validate the actual input bytes and reject malformed rows according to the approved policy.
A header being skipped does not establish that its names or order match the target columns. Check the expected header and compare a sample of parsed rows, especially names containing commas, quotes or non-ASCII text. Do not assume that every empty field means zero or that a successful COPY validated business ranges. A staging table can preserve raw fields for controlled validation before publication to final tables.
Validate before publishing
Check file identity, expected count, unique keys, required values and domain constraints in staging. For the two-row fixture, count two and sum seven are necessary but not sufficient: swapping quantities or changing 2 and 5 to 3 and 4 can keep the same totals. Compare exact keyed rows and reject or quarantine invalid records according to a documented rule. Validate duplicates against both the file and existing destination state before applying a merge.
Use a transaction boundary that matches the intended publication decision. A failed statement in PostgreSQL can leave the transaction aborted until rollback. PostgreSQL COPY options and error-handling features vary by version; verify PostgreSQL 18 documentation and the actual command rather than assuming every failure is automatically skipped. Record accepted and rejected counts and reconcile them to the source manifest.
Protect the operation and evidence
Separate a dry-run or isolated rehearsal from a real import. Establish who owns the transaction, how to stop or roll back publication, and how to recover if the result is wrong. A successful command message is not proof of correct field mapping, authorization or business meaning. Preserve a protected source artifact and a manifest with checksum, schema version, row count and load identity where the process requires them.
Check downstream effects, constraints and permissions before publication. Avoid logging sensitive file contents or credentials. After the load, compare exact sample rows, counts and business invariants with independent expectations and record discrepancies. A repeated import needs a deliberate identity and duplicate policy; simply running COPY twice can insert the same business records twice when constraints do not prevent it.
20 worked examples
1. Fixture count
Problem: What count and sum does this CSV fixture imply?
- The file contains two data rows after its header.
- Their quantities add as two plus five.
item_id,quantity
1,2
2,5
2 rows; quantity sum 7
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: The count and sum provide initial reconciliation checks.
2. Exact keyed rows
Problem: Why inspect each item as well as its sum?
- The increases and decreases cancel in the total.
- The row count is unchanged.
Expected: (1,2), (2,5)
Loaded: (1,3), (2,4)
Both counts=2 and sums=7.
The loaded quantities are wrong for both keys.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Keyed comparisons detect errors hidden by matching aggregates.
3. Server file boundary
Problem: Which filesystem does server-side COPY read?
- The command is server-side COPY FROM a file.
- The server must be able to access that path under its permissions.
COPY lab_stage (item_id,quantity) FROM '/lab/items.csv' WITH (FORMAT csv, HEADER true);
The PostgreSQL server process reads its own /lab/items.csv.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: A path on the client machine is not automatically a server path.
4. Client file boundary
Problem: Which process reads a file for psql copy?
- The backslash command is interpreted by psql.
- Its file path is resolved on the client side.
\copy lab_stage (item_id,quantity) FROM '/lab/items.csv' WITH (FORMAT csv, HEADER true)
The psql client reads its local file and streams data.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Client and server file boundaries can differ.
5. Different machines
Problem: Why can a psql-visible path fail in server COPY?
- The file exists only in the client container in this scenario.
- Server-side COPY resolves the path on the server.
Client container: /lab/items.csv exists.
Server container: /lab/items.csv is absent.
Command: server-side COPY FROM file.
Server COPY cannot read that absent server path.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: A shared path string does not imply a shared filesystem.
6. Column mapping
Problem: How do explicit target columns map the CSV?
- The first CSV field maps to the first named column.
- The second field maps to the second named column.
-- CSV data: 1,2
COPY lab_stage (item_id,quantity) FROM STDIN WITH (FORMAT csv);
item_id=1; quantity=2
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: An explicit column list makes positional mapping reviewable.
7. Reversed mapping
Problem: What happens if the target list is reversed?
- The first field maps to quantity in this command.
- The second field maps to item_id.
-- CSV data: 1,2
COPY lab_stage (quantity,item_id) FROM STDIN WITH (FORMAT csv);
quantity=1; item_id=2
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Column names do not automatically reorder a positional CSV record.
8. Header skip
Problem: What does HEADER true do for this fixture?
- The first line is designated as a header.
- The next two lines are data records.
item_id,quantity
1,2
2,5
-- COPY ... WITH (FORMAT csv, HEADER true)
The header row is skipped; two data rows remain.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Skipping a header does not itself prove its names match the target.
9. Quoted comma
Problem: How many fields are in this CSV data row?
- The comma inside the quoted field belongs to the label.
- The other commas separate the three fields.
1,"North, quay",2
-- Columns: item_id,label,quantity; standard CSV quoting.
3 fields; label is North, quay.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: CSV quoting preserves delimiters within a field.
10. Escaped quote
Problem: What label is represented by this CSV field?
- The doubled quotes inside the quoted field represent literal quotes.
- The surrounding quotes delimit the field.
1,"A ""quoted"" label",2
A "quoted" label
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: CSV escaping differs from simply splitting text at commas.
11. Empty versus NULL
Problem: Why must empty CSV fields be specified?
- The lexical forms differ in quoting.
- COPY’s NULL and quote rules determine the loaded values.
-- Two source fields: an unquoted empty field and a quoted empty string.
-- COPY CSV NULL and quote options determine their interpretation.
Check the actual COPY options and intended missing-value policy.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Do not assume both forms mean numeric zero or the same business state.
12. Encoding
Problem: Why verify encoding before loading a label?
- The file bytes need a correct decoding interpretation.
- An incorrect encoding declaration changes that interpretation.
-- File contains a non-ASCII station label.
-- Declared file encoding does not match its actual bytes.
The load can fail or produce incorrect text depending on the mismatch.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Validate encoding and representative multilingual rows before publication.
13. Duplicate keys
Problem: What should happen to duplicate item ids in a file?
- Both data rows use item id one.
- The final identity rule permits only one such key.
item_id,quantity
1,2
1,5
-- Final item_id must be unique.
Reject or resolve the duplicate under the documented policy.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: File-level duplicate checks complement destination constraints.
14. Negative quantity
Problem: Does syntactically valid CSV prove a valid quantity?
- The record is well-formed CSV.
- Its quantity is negative under the stated rule.
item_id,quantity
1,-2
-- Business rule: quantity must be nonnegative.
No; the row violates the domain rule.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Parsing and business validation are separate stages.
15. Staging validation
Problem: What should be checked before publishing the fixture?
- The aggregate expectations match the stated staging rows.
- A different pair could share those aggregates.
Staging rows: (1,2), (2,5)
Expected manifest: count=2, quantity sum=7.
Verify both exact rows as well as count and sum.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Keyed validation adds evidence beyond a successful load count.
16. Rollback failed load
Problem: What follows an error inside an import transaction?
- The COPY statement raises an error inside the transaction.
- PostgreSQL keeps the transaction in a failed state until rollback.
BEGIN;
-- COPY encounters a constraint error.
SELECT 1;
ROLLBACK;
The transaction is failed and the later SELECT is rejected until rollback.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: The owner must clear the failed transaction before normal continuation.
17. Repeat import
Problem: What can happen if the same file is copied twice?
- Each run supplies the same two rows.
- The scenario has no duplicate prevention rule.
File contains business rows 1 and 2.
No unique constraint or load identity prevents repetition.
COPY is run twice.
Duplicate business rows can be inserted.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: A repeated import needs an explicit identity and idempotency policy.
18. Permission boundary
Problem: Does table INSERT privilege imply server-file access?
- The table privilege controls writing rows.
- The server file boundary has additional permission requirements.
Role can insert into lab_stage.
Server-side COPY FROM file requires its own documented file access conditions.
No; verify table and server-file permissions separately.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Do not broaden file privileges merely to make a lab path work.
19. Manifest identity
Problem: Why record a file checksum and load id?
- The candidate checksum differs from the manifest.
- The load id associates the attempt with its expected artifact.
Manifest: file checksum H1, load id run-7, expected rows 2.
Candidate file checksum: H2.
Investigate the mismatch before loading.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Artifact identity is part of reproducible reconciliation.
20. Publication decision
Problem: When can the staged fixture be considered for publication?
- The exact rows and aggregates match the manifest.
- The stated operational prerequisites have been reviewed.
Staging: (1,2),(2,5).
Expected: same keyed rows, count 2, sum 7.
Permissions and transaction plan reviewed.
The fixture passes these stated checks; follow the approved publication procedure.
Synthetic file and outcome are reasoned; no PostgreSQL server or file was accessed.
Why this result follows: Acceptance remains scoped to the checks and authorized process.
Common errors and fixes
The server cannot open the requested file.
- Why it happens
- A client-local path was supplied to server-side COPY.
- How to fix it
- Use the documented client-side facility or an approved server-accessible path and privileges.
- Prevent it next time
- Document which machine reads each source.
Fields appear in the wrong columns.
- Why it happens
- The source order and target column list do not match.
- How to fix it
- Correct the mapping and reload a disposable fixture.
- Prevent it next time
- Validate headers and representative rows before import.
A retry creates duplicate business records.
- Why it happens
- The import lacks a stable batch or source identity.
- How to fix it
- Reconcile the previous outcome and apply the approved idempotent procedure.
- Prevent it next time
- Test failure and retry with stable identifiers.
20 practice exercises
1. What are the expected fixture count and quantity sum?
Show hint
Add the two quantities and count data rows, not the header.
Show worked solution
Two rows and a quantity sum of seven: 2 + 5. Inspect the individual rows as well because a matching sum does not establish correct field mapping.
The fixture contains two data rows with quantities 2 and 5, so the count is two and the sum is seven. Verify each item’s quantity as well; aggregates alone cannot prove correct mapping.
Check your solution
- There are 2 data rows.
- The quantity sum is 7.
2. Why might a path visible to psql not be visible to server-side COPY?
Show hint
Identify the process that opens the file.
Show worked solution
The client and database server can run on different machines or containers with different filesystems and permissions. Choose the documented client or server file boundary deliberately.
Server-side COPY reads a path on the server filesystem using the server’s access conditions. psql and the server may run in different containers or machines, so a client-visible path need not exist on the server.
Check your solution
- Server COPY uses the server filesystem.
- Client and server paths or permissions can differ.
3. A CSV has rows (1,2) and (2,5). What count and quantity sum are expected?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
There are two data rows and their quantities sum to seven. Inspect the exact item-to-quantity mapping as well, because matching aggregates alone do not prove that each field was loaded correctly.
Check your solution
- Count is 2
- Quantity sum is 7
4. Expected rows are (1,2),(2,5); loaded rows are (1,3),(2,4). Do count and sum detect the error?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
No. Both sets contain two rows and sum to seven, but each key has the wrong quantity. Compare keyed rows independently of aggregate reconciliation.
Check your solution
- Counts and sums match
- Keyed quantities differ
5. A file is visible to psql on a client container but absent on the server. Can server-side COPY read that client path?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
No. Server-side COPY resolves the file on the server filesystem and needs the server’s documented permissions. Choose a client-side stream or another approved transfer boundary deliberately.
Check your solution
- Server path is absent
- Client visibility is not server visibility
6. What is the file boundary for psql \copy FROM a local file?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
The psql client reads its local file and streams the data through the connection. It remains important to verify target table permissions and the exact client and database identity.
Check your solution
- Client reads the file
- Verify target and permissions
7. A CSV row is 1,"North, quay",2. How many fields are parsed?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
There are three fields: item id 1, label North, quay and quantity 2. The comma inside the quoted label is data, not a field separator.
Check your solution
- Three fields
- The label includes the comma
8. The file fields are item_id,quantity but COPY names quantity,item_id. What mapping results for 1,2?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
The first value maps to quantity and the second to item_id, producing quantity 1 and item_id 2. Correct the target order and verify keyed rows before publication.
Check your solution
- First value maps to quantity
- Second value maps to item_id
9. Does HEADER true prove a CSV header matches the target column names?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
No. It controls header handling, but the import contract must still verify names, order and actual field mapping. Inspect representative parsed rows and reject unexpected headers under the process policy.
Check your solution
- Header handling is not mapping proof
- Verify names and order
10. Why distinguish an unquoted empty field from a quoted empty string in CSV?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
COPY options and quoting rules determine whether each form becomes NULL or empty text. State the intended semantics and test the exact command rather than treating missing data as zero.
Check your solution
- Forms can have different meanings
- Test the configured COPY options
11. A valid CSV row has quantity -2 but the domain requires nonnegative quantity. Is parsing enough?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
No. The syntax can be valid while the business value violates its domain. Reject or quarantine the row according to the documented validation policy before publishing it.
Check your solution
- CSV syntax can be valid
- Negative quantity violates the rule
12. A file contains item id 1 twice but the destination requires unique ids. What should be checked?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
Detect the duplicate within staging and compare it with existing destination keys. Reject or resolve it under an approved rule rather than silently choosing a row.
Check your solution
- Detect file duplicate
- Check destination conflicts
13. A COPY statement fails inside BEGIN and the client issues SELECT without rollback. What is expected?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
The PostgreSQL transaction is failed and rejects normal later commands until rollback. The owner must roll back or otherwise follow the documented transaction recovery path before continuing.
Check your solution
- Transaction remains failed
- Rollback clears the failed transaction
14. A file is copied twice and no unique rule exists. What risk follows?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
The same business rows can be inserted twice. Define a stable load or business identity and a duplicate policy before repeating the import.
Check your solution
- Duplicate rows are possible
- Define an idempotency policy
15. Does INSERT privilege on the staging table automatically permit server-side file access?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
No. Table privileges and server-file access have separate requirements. Verify the documented role and filesystem boundary rather than granting broad access for convenience.
Check your solution
- Table and file permissions differ
- Use the approved access boundary
16. A manifest expects checksum H1 but the candidate file has H2. What should happen?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
Stop and investigate the mismatch before loading. The file may not be the expected artifact, and a load id and checksum support reproducible evidence.
Check your solution
- Checksums differ
- Do not silently load the candidate
17. The expected fixture has count 2 and sum 7. What other evidence should be checked?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
Compare item ids and quantities row by row, plus required fields and constraints. Different incorrect rows can share the same count and sum.
Check your solution
- Verify exact keyed rows
- Check required fields
18. A staging load succeeds. Does that prove the final publication is safe?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
No. Validate mapping, domains, duplicate policy, authorization and the transaction and recovery plan before moving data to final tables. A command success is only one signal.
Check your solution
- Validate staging content
- Review publication boundary
19. A CSV file contains non-ASCII labels. What should be tested before import?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
Verify actual file encoding, COPY options and representative parsed labels through the whole client or server path. A mismatched declaration can fail or corrupt text.
Check your solution
- Check file encoding
- Compare representative labels
20. A load fails after staging changes in a transaction. What should the owner verify?
Show hint
Trace the file boundary, positional mapping, validation and transaction outcome.
Show worked solution
Follow the documented rollback path and confirm no partial publication remains. Record accepted and rejected counts and the load identity without exposing sensitive contents.
Check your solution
- Verify rollback state
- Reconcile source and outcome counts
Key takeaways
- State the source format and target mapping before import.
- Server-side and client-side file access are different boundaries.
- Reconcile rows and test failure and retry on disposable data.
- A client-visible path is not necessarily visible to the server process.
- Count and sum checks do not prove correct field mapping.
- A repeated import needs a deliberate duplicate and recovery policy.