Database Moving Data: Imports, Exports and ETL
What you will learn
- Why moving data is a common job
- How to import from and export to CSV files
- What ETL means: extract, transform, load
- How to clean and validate rows, and keep a list of rejects
- Good habits: repeatable, checked, reversible
1. Data does not stay in one place
Data arrives from files, other programs, partners and older systems. It also leaves: reports, exports for the accountant, copies for analysis (chapter 13). Moving data is not a one-off chore; it is a regular part of running a database. It is also a classic source of trouble, because outside data is rarely clean.
The most common common-denominator format is CSV (comma-separated values): a text file where each line is a row and commas separate the columns. Every database tool and spreadsheet can read and write it. Bigger systems use other formats too, but the steps are the same.
2. ETL: extract, transform, load
ETL names the three steps of nearly every data move:
| Step | What happens |
|---|---|
| Extract | read the data from its source (a file, another database, an API) |
| Transform | clean, fix, convert and check it so that it fits your tables |
| Load | write it into the target database |
The order matters. Do not load first and clean later: bad rows inside your tables are much harder to remove than bad rows in a file. (In some analytics systems the load comes first and the transform later; this is called ELT, and lesson 13.4 explains when and why.)
3. A messy import, step by step
Here is a small CSV, held in a string to keep the example self-contained. Real data is messy, so it has problems on purpose: spaces around a name, a missing phone, a date with slashes, a non-number where a number should be, a repeated id, and an impossible date.
import csv, io, sqlite3
raw = """id,name,phone,joined,spend
1, Rina ,01711-000001,2026-01-05,1200
2,Sam,,2026/02/11,300
3,Lee,01911-000003,2026-03-02,abc
3,Lee,01911-000003,2026-03-02,450
4,Amy,01611-000004,2026-13-40,90
"""
Transform: one function turns a raw row into clean values, or raises an error saying what is wrong:
def clean(row):
name = row["name"].strip()
phone = row["phone"].strip() or None
joined = row["joined"].replace("/", "-")
y, m, d = joined.split("-")
if not (1 <= int(m) <= 12 and 1 <= int(d) <= 31):
raise ValueError(f"bad date {row['joined']!r}")
return (int(row["id"]), name, phone, joined, int(row["spend"]))
Load: go through the rows, load the good ones, and keep the bad ones with their line number and reason, instead of stopping or silently skipping:
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT, joined TEXT, spend INTEGER)")
loaded, rejected, seen = 0, [], set()
for line_no, row in enumerate(csv.DictReader(io.StringIO(raw)), start=2):
try:
values = clean(row)
if values[0] in seen:
raise ValueError("duplicate id")
con.execute("INSERT INTO customers VALUES (?, ?, ?, ?, ?)", values)
seen.add(values[0])
loaded += 1
except (ValueError, sqlite3.Error) as e:
rejected.append((line_no, str(e)))
print("loaded:", loaded)
print("rejected:", rejected)
print(con.execute("SELECT * FROM customers ORDER BY id").fetchall())
loaded: 3
rejected: [(4, "invalid literal for int() with base 10: 'abc'"), (6, "bad date '2026-13-40'")]
[(1, 'Rina', '01711-000001', '2026-01-05', 1200), (2, 'Sam', None, '2026-02-11', 300), (3, 'Lee', '01911-000003', '2026-03-02', 450)]
The same import in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). SQL can do the whole extract-transform-load job when the file has already been read into a staging table of plain text. The tables are small ones of their own; Reset data removes them.
CREATE TABLE raw_customers (line_no INTEGER, id TEXT, name TEXT, phone TEXT, joined TEXT, spend TEXT);
INSERT INTO raw_customers VALUES
(2, '1', ' Rina ', '01711-000001', '2026-01-05', '1200'),
(3, '2', 'Sam', '', '2026/02/11', '300'),
(4, '3', 'Lee', '01911-000003', '2026-03-02', 'abc'),
(5, '3', 'Lee', '01911-000003', '2026-03-02', '450'),
(6, '4', 'Amy', '01611-000004', '2026-13-40', '90');
(5 rows changed)
Transform: a view turns each raw row into clean values and names the problem, if there is one:
CREATE VIEW cleaned AS
SELECT line_no, CAST(id AS INTEGER) AS id, trim(name) AS name, NULLIF(trim(phone), '') AS phone,
replace(joined, '/', '-') AS joined, spend,
CASE WHEN spend = '' OR spend GLOB '*[^0-9]*' THEN 'spend is not a number'
WHEN date(replace(joined, '/', '-')) IS NOT replace(joined, '/', '-') THEN 'bad date'
END AS problem
FROM raw_customers;
SELECT line_no, id, name, phone, joined, problem FROM cleaned ORDER BY line_no;
line_no id name phone joined problem
------- -- ---- ------------ ---------- ---------------------
2 1 Rina 01711-000001 2026-01-05 NULL
3 2 Sam NULL 2026-02-11 NULL
4 3 Lee 01911-000003 2026-03-02 spend is not a number
5 3 Lee 01911-000003 2026-03-02 NULL
6 4 Amy 01611-000004 2026-13-40 bad date
(5 rows)
Load: insert the good rows, and keep the bad ones with their line number and reason:
CREATE TABLE imported (id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT, joined TEXT, spend INTEGER);
INSERT INTO imported SELECT id, name, phone, joined, CAST(spend AS INTEGER) FROM cleaned WHERE problem IS NULL;
SELECT * FROM imported ORDER BY id;
SELECT line_no, problem AS rejected_because FROM cleaned WHERE problem IS NOT NULL ORDER BY line_no;
id name phone joined spend
-- ---- ------------ ---------- -----
1 Rina 01711-000001 2026-01-05 1200
2 Sam NULL 2026-02-11 300
3 Lee 01911-000003 2026-03-02 450
(3 rows)
line_no rejected_because
------- ---------------------
4 spend is not a number
6 bad date
(2 rows)
CREATE TABLE raw_customers (line_no INTEGER, id TEXT, name TEXT, phone TEXT, joined TEXT, spend TEXT);
INSERT INTO raw_customers VALUES
(2, '1', ' Rina ', '01711-000001', '2026-01-05', '1200'),
(3, '2', 'Sam', '', '2026/02/11', '300'),
(4, '3', 'Lee', '01911-000003', '2026-03-02', 'abc'),
(5, '3', 'Lee', '01911-000003', '2026-03-02', '450'),
(6, '4', 'Amy', '01611-000004', '2026-13-40', '90');
(5 rows changed)
Transform: a view turns each raw row into clean values and names the problem, if there is one:
CREATE VIEW cleaned AS
SELECT line_no, CAST(id AS INTEGER) AS id, trim(name) AS name, NULLIF(trim(phone), '') AS phone,
replace(joined, '/', '-') AS joined, spend,
CASE WHEN spend = '' OR spend GLOB '*[^0-9]*' THEN 'spend is not a number'
WHEN date(replace(joined, '/', '-')) IS NOT replace(joined, '/', '-') THEN 'bad date'
END AS problem
FROM raw_customers;
SELECT line_no, id, name, phone, joined, problem FROM cleaned ORDER BY line_no;
line_no id name phone joined problem
------- -- ---- ------------ ---------- ---------------------
2 1 Rina 01711-000001 2026-01-05 NULL
3 2 Sam NULL 2026-02-11 NULL
4 3 Lee 01911-000003 2026-03-02 spend is not a number
5 3 Lee 01911-000003 2026-03-02 NULL
6 4 Amy 01611-000004 2026-13-40 bad date
(5 rows)
Load: insert the good rows, and keep the bad ones with their line number and reason:
CREATE TABLE imported (id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT, joined TEXT, spend INTEGER);
INSERT INTO imported SELECT id, name, phone, joined, CAST(spend AS INTEGER) FROM cleaned WHERE problem IS NULL;
SELECT * FROM imported ORDER BY id;
SELECT line_no, problem AS rejected_because FROM cleaned WHERE problem IS NOT NULL ORDER BY line_no;
id name phone joined spend
-- ---- ------------ ---------- -----
1 Rina 01711-000001 2026-01-05 1200
2 Sam NULL 2026-02-11 300
3 Lee 01911-000003 2026-03-02 450
(3 rows)
line_no rejected_because
------- ---------------------
4 spend is not a number
6 bad date
(2 rows)
CREATE TABLE raw_customers (line_no INTEGER, id TEXT, name TEXT, phone TEXT, joined TEXT, spend TEXT);
INSERT INTO raw_customers VALUES
(2, '1', ' Rina ', '01711-000001', '2026-01-05', '1200'),
(3, '2', 'Sam', '', '2026/02/11', '300'),
(4, '3', 'Lee', '01911-000003', '2026-03-02', 'abc'),
(5, '3', 'Lee', '01911-000003', '2026-03-02', '450'),
(6, '4', 'Amy', '01611-000004', '2026-13-40', '90');
(5 rows changed)
Transform: a view turns each raw row into clean values and names the problem, if there is one:
CREATE VIEW cleaned AS
SELECT line_no, CAST(id AS INTEGER) AS id, trim(name) AS name, NULLIF(trim(phone), '') AS phone,
replace(joined, '/', '-') AS joined, spend,
CASE WHEN spend = '' OR spend GLOB '*[^0-9]*' THEN 'spend is not a number'
WHEN date(replace(joined, '/', '-')) IS NOT replace(joined, '/', '-') THEN 'bad date'
END AS problem
FROM raw_customers;
SELECT line_no, id, name, phone, joined, problem FROM cleaned ORDER BY line_no;
line_no id name phone joined problem
------- -- ---- ------------ ---------- ---------------------
2 1 Rina 01711-000001 2026-01-05 NULL
3 2 Sam NULL 2026-02-11 NULL
4 3 Lee 01911-000003 2026-03-02 spend is not a number
5 3 Lee 01911-000003 2026-03-02 NULL
6 4 Amy 01611-000004 2026-13-40 bad date
(5 rows)
Load: insert the good rows, and keep the bad ones with their line number and reason:
CREATE TABLE imported (id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT, joined TEXT, spend INTEGER);
INSERT INTO imported SELECT id, name, phone, joined, CAST(spend AS INTEGER) FROM cleaned WHERE problem IS NULL;
SELECT * FROM imported ORDER BY id;
SELECT line_no, problem AS rejected_because FROM cleaned WHERE problem IS NOT NULL ORDER BY line_no;
id name phone joined spend
-- ---- ------------ ---------- -----
1 Rina 01711-000001 2026-01-05 1200
2 Sam NULL 2026-02-11 300
3 Lee 01911-000003 2026-03-02 450
(3 rows)
line_no rejected_because
------- ---------------------
4 spend is not a number
6 bad date
(2 rows)
Three rows were loaded and two rejected, the same result as the Python version: the text abc is not a number, and 2026-13-40 is not a date (date() returns NULL for it, so it does not equal the text it was given). The duplicate id 3 was harmless here because the first row with that id was the rejected one; a real job would also check for repeated ids before loading.
Going the other way, a query can write a CSV-style line for each row (the export side of the same job):
SELECT customer_id || ',' || first_name || ',' || last_name || ',' || city AS csv_line
FROM customers ORDER BY customer_id LIMIT 3;
csv_line
-------------------
1,Vik,Ahmed,Leeds
2,Wanda,Ahmed,Leeds
3,Dana,Costa,Cairo
(3 rows)
SELECT branch_id || ',' || name || ',' || city AS csv_line
FROM branches ORDER BY branch_id LIMIT 3;
csv_line
-------------------
1,Central,Lisbon
2,Riverside,Toronto
3,Harbour,Osaka
(3 rows)
SELECT department_id || ',' || name || ',' || COALESCE(building, '') AS csv_line
FROM departments ORDER BY department_id LIMIT 3;
csv_line
------------------------
1,Mathematics,North Hall
2,Science,Lab Block
3,Languages,West Hall
(3 rows)
What happened:
- Rina's name lost its spaces; Sam's slashes became dashes and his empty phone became
NULL(lesson 2.3). - Line 4 (
abcas a spend) and line 6 (month 13) were rejected with a reason. The line numbers count the header as line 1, so they match what you see in a text editor. - Lee appears twice, and the first copy was the rejected one, so the second was loaded. That was luck. If both copies had been valid, the second would be rejected as a duplicate. A person must decide which of two conflicting rows is right, which is why rejects are kept, not hidden.
The rejects list is the most valuable output. Send it to whoever owns the source file, so the problem is fixed at the source and not repeated next month.
Load inside a transaction (chapter 6): if the script crashes halfway, ROLLBACK leaves the table as it was, instead of half-loaded.
4. Export
Exporting is the reverse and much simpler:
out = io.StringIO()
w = csv.writer(out, lineterminator="\n")
w.writerow(["id", "name", "phone", "joined", "spend"])
w.writerows(con.execute("SELECT * FROM customers ORDER BY id"))
print(out.getvalue())
id,name,phone,joined,spend
1,Rina,01711-000001,2026-01-05,1200
2,Sam,,2026-02-11,300
3,Lee,01911-000003,2026-03-02,450
Things to watch with CSV: NULL and an empty text both become an empty field (Sam's phone), so the difference is lost; text that contains commas or line breaks must be quoted (the csv module does this); and dates and numbers are plain text, so the receiver must know their formats. For these reasons exports should come with a short description of the columns.
5. Good habits
- Repeatable: keep the import as a script, not a series of clicks, so it gives the same result every time and can be run on a test copy first (lesson 12.8).
- Idempotent where possible: running it twice should not create duplicate rows. Use keys (lesson 2.4) and rules such as "insert, or update if the id exists".
- Checked: after loading, compare counts (rows read = rows loaded + rows rejected: here 5 = 3 + 2) and spot-check values.
- Logged: record when it ran, how many rows, and how many were rejected.
- Reversible: take a backup before a big load (lesson 8.2), so you can undo it.
- Careful with personal data: exports leave your protected system; send them only to people who may see them, and delete them afterwards (lesson 8.6).
Worked example: the accountant's monthly export
Each month the accountant needs a list of paid orders for the previous month.
| Step | ETL stage | Detail |
|---|---|---|
| 1 | Extract | SELECT paid orders with a date range for last month |
| 2 | Transform | format dates the way the accountant's software expects, round amounts to two decimals, give the columns clear names |
| 3 | Load | write a CSV file, named with the month, for example orders-2026-09.csv |
| 4 | Check | the number of lines equals the number of paid orders, and the total equals the total in the shop's own report |
| 5 | Record | note the date, the row count and the total in a log |
The same script is run every month, so mistakes from hand-made copies cannot creep in. The shop and files are made up.
Common mistakes
- Loading raw data straight into real tables and cleaning afterwards.
- Silently skipping bad rows, so that nobody knows data is missing.
- Changing the data by hand in the file instead of fixing the script or the source.
- Not counting: no check that rows in equals rows loaded plus rejected.
- Forgetting formats: dates such as
03/04/2026mean different things in different countries. Use an unambiguous form such as2026-04-03.
Key takeaways
- Moving data is a regular task; CSV is the common format.
- ETL: extract from the source, transform (clean and validate), load into the target.
- Reject bad rows with a line number and reason; do not stop, and do not hide them.
- Load in a transaction, check the counts, log the result and keep a backup.
- Make imports and exports repeatable scripts, safe to run twice.
Practice
1. What do the letters E, T and L stand for, and why should T come before L?
Show answer
Extract, Transform, Load. Cleaning before loading keeps bad rows out of the real tables, where they are harder to remove.
2. In the import, why were lines 4 and 6 rejected?
Show answer
Line 4 had abc where a number was needed for spend; line 6 had month 13 and day 40, which is an impossible date.
3. A file has 1,000 data rows. Your script loaded 962 and rejected 30. What does the check "rows read = loaded + rejected" show?
Show answer
962 + 30 = 992, not 1,000, so 8 rows are unaccounted for. Something skipped or lost them and you must find out what.
4. Why wrap a big load in a transaction?
Show answer
If the script fails halfway, a rollback leaves the table unchanged instead of half-loaded.
5. Name two problems of exporting NULL values to CSV.
Show answer
NULL becomes an empty field, so it cannot be told apart from an empty text, and the receiver may read it as an empty string or zero.
6. Why are dates such as 03/04/2026 risky in a data file?
Show answer
They are ambiguous: some read them as 3 April, others as 4 March. Use 2026-04-03 (year, month, day).