Database Warehousing and Analytics · Lesson 98 of 112

Database ETL and ELT

What you will learn

  • What extract, transform and load mean
  • The difference between ETL and ELT
  • What a staging table is
  • How to handle bad rows and duplicates
  • How to choose between ETL and ELT

1. Moving data into a warehouse

A warehouse (lesson 13.1) is filled from other places: the shop database, spreadsheets people email around, files from a supplier, exports from a website. This job has three steps, and the common name is ETL:

  1. Extract: read the data from its source.
  2. Transform: clean it and change its shape: fix dates, remove duplicates, unify spelling, compute new columns, drop impossible rows.
  3. Load: write it into the warehouse tables.

Real data is untidy. Our source (made up) is a small CSV export with typical problems:

order_id,date,city,amount
1001,05/01/2026, dhaka ,"1,200 Tk"
1002,06/01/2026,Chattogram,450 Tk
1002,06/01/2026,Chattogram,450 Tk
1003,07/01/2026,,300 Tk
1004,not a date,Dhaka,100 Tk
1005,09/01/2026,DHAKA,"2,050 Tk"

The problems: dates are dd/mm/yyyy (the warehouse wants yyyy-mm-dd), the amount is text with a thousands comma and "Tk", cities have extra spaces and different capital letters, order 1002 appears twice, order 1003 has no city and order 1004 has no valid date.

2. ETL: transform before loading

In ETL the transform step happens outside the warehouse, in a program (here Python). Only clean rows are loaded.

import csv, io, sqlite3

raw = """order_id,date,city,amount
1001,05/01/2026, dhaka ,"1,200 Tk"
1002,06/01/2026,Chattogram,450 Tk
1002,06/01/2026,Chattogram,450 Tk
1003,07/01/2026,,300 Tk
1004,not a date,Dhaka,100 Tk
1005,09/01/2026,DHAKA,"2,050 Tk"
"""

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE sales_clean (order_id INTEGER PRIMARY KEY, sale_date TEXT, city TEXT, amount INTEGER)")
rejected, seen = [], set()
for row in csv.DictReader(io.StringIO(raw)):                     # extract
    oid = int(row["order_id"])
    if oid in seen:
        continue                                                  # drop exact duplicates
    seen.add(oid)
    try:                                                          # transform
        day, month, year = row["date"].split("/")
        sale_date = f"{year}-{month}-{day}"
        if len(year) != 4:
            raise ValueError
        city = row["city"].strip().title() or None
        amount = int(row["amount"].replace("Tk", "").replace(",", "").strip())
    except ValueError:
        rejected.append((oid, "bad date"))
        continue
    con.execute("INSERT INTO sales_clean VALUES (?,?,?,?)", (oid, sale_date, city, amount))   # load
print("loaded:", con.execute("SELECT * FROM sales_clean ORDER BY order_id").fetchall())
print("rejected:", rejected)
loaded: [(1001, '2026-01-05', 'Dhaka', 1200), (1002, '2026-01-06', 'Chattogram', 450), (1003, '2026-01-07', None, 300), (1005, '2026-01-09', 'Dhaka', 2050)]
rejected: [(1004, 'bad date')]

Three decisions were made in code:

  • The duplicate of 1002 was dropped.
  • Order 1003 was kept with an empty city (None), because the sale is real even though the city is unknown.
  • Order 1004 was rejected and written to a rejected list so that someone can look at it later.

(.title() is fine for these city names but would mangle names such as "McDonald"; always test transformations against real values.)

3. ELT: load first, transform inside

In ELT the order changes: extract, load, then transform. The raw data is first loaded unchanged into a staging table; the cleaning is done with SQL inside the warehouse. The SQL cells below run on the sample database you chose in lesson 4.1 (use the Example data picker at the top); they add small tables of their own to your browser's copy, and Reset data starts again. The six CSV lines are written as rows of text:

CREATE TABLE staging (order_id TEXT, date TEXT, city TEXT, amount TEXT);
INSERT INTO staging VALUES
  ('1001', '05/01/2026', ' dhaka ', '1,200 Tk'),
  ('1002', '06/01/2026', 'Chattogram', '450 Tk'),
  ('1002', '06/01/2026', 'Chattogram', '450 Tk'),
  ('1003', '07/01/2026', '', '300 Tk'),
  ('1004', 'not a date', 'Dhaka', '100 Tk'),
  ('1005', '09/01/2026', 'DHAKA', '2,050 Tk');
SELECT COUNT(*) AS staging_rows FROM staging;
staging_rows
------------
           6
(1 row)
CREATE TABLE staging (order_id TEXT, date TEXT, city TEXT, amount TEXT);
INSERT INTO staging VALUES
  ('1001', '05/01/2026', ' dhaka ', '1,200 Tk'),
  ('1002', '06/01/2026', 'Chattogram', '450 Tk'),
  ('1002', '06/01/2026', 'Chattogram', '450 Tk'),
  ('1003', '07/01/2026', '', '300 Tk'),
  ('1004', 'not a date', 'Dhaka', '100 Tk'),
  ('1005', '09/01/2026', 'DHAKA', '2,050 Tk');
SELECT COUNT(*) AS staging_rows FROM staging;
staging_rows
------------
           6
(1 row)
CREATE TABLE staging (order_id TEXT, date TEXT, city TEXT, amount TEXT);
INSERT INTO staging VALUES
  ('1001', '05/01/2026', ' dhaka ', '1,200 Tk'),
  ('1002', '06/01/2026', 'Chattogram', '450 Tk'),
  ('1002', '06/01/2026', 'Chattogram', '450 Tk'),
  ('1003', '07/01/2026', '', '300 Tk'),
  ('1004', 'not a date', 'Dhaka', '100 Tk'),
  ('1005', '09/01/2026', 'DHAKA', '2,050 Tk');
SELECT COUNT(*) AS staging_rows FROM staging;
staging_rows
------------
           6
(1 row)

Every column in staging is TEXT, so nothing can fail to load; all six rows, including the duplicate and the bad date, are stored. Now transform with SQL:

CREATE TABLE sales_elt AS
  SELECT DISTINCT CAST(order_id AS INTEGER) AS order_id,
         substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date, 1, 2) AS sale_date,
         NULLIF(trim(city), '') AS city,
         CAST(replace(replace(replace(amount, 'Tk', ''), ',', ''), ' ', '') AS INTEGER) AS amount
  FROM staging WHERE date GLOB '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]';
SELECT * FROM sales_elt ORDER BY order_id;
SELECT order_id, date FROM staging WHERE date NOT GLOB '[0-9][0-9]/*';
order_id  sale_date   city        amount
--------  ----------  ----------  ------
    1001  2026-01-05  dhaka         1200
    1002  2026-01-06  Chattogram     450
    1003  2026-01-07  NULL           300
    1005  2026-01-09  DHAKA         2050
(4 rows)

order_id  date
--------  ----------
1004      not a date
(1 row)
CREATE TABLE sales_elt AS
  SELECT DISTINCT CAST(order_id AS INTEGER) AS order_id,
         substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date, 1, 2) AS sale_date,
         NULLIF(trim(city), '') AS city,
         CAST(replace(replace(replace(amount, 'Tk', ''), ',', ''), ' ', '') AS INTEGER) AS amount
  FROM staging WHERE date GLOB '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]';
SELECT * FROM sales_elt ORDER BY order_id;
SELECT order_id, date FROM staging WHERE date NOT GLOB '[0-9][0-9]/*';
order_id  sale_date   city        amount
--------  ----------  ----------  ------
    1001  2026-01-05  dhaka         1200
    1002  2026-01-06  Chattogram     450
    1003  2026-01-07  NULL           300
    1005  2026-01-09  DHAKA         2050
(4 rows)

order_id  date
--------  ----------
1004      not a date
(1 row)
CREATE TABLE sales_elt AS
  SELECT DISTINCT CAST(order_id AS INTEGER) AS order_id,
         substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date, 1, 2) AS sale_date,
         NULLIF(trim(city), '') AS city,
         CAST(replace(replace(replace(amount, 'Tk', ''), ',', ''), ' ', '') AS INTEGER) AS amount
  FROM staging WHERE date GLOB '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]';
SELECT * FROM sales_elt ORDER BY order_id;
SELECT order_id, date FROM staging WHERE date NOT GLOB '[0-9][0-9]/*';
order_id  sale_date   city        amount
--------  ----------  ----------  ------
    1001  2026-01-05  dhaka         1200
    1002  2026-01-06  Chattogram     450
    1003  2026-01-07  NULL           300
    1005  2026-01-09  DHAKA         2050
(4 rows)

order_id  date
--------  ----------
1004      not a date
(1 row)

DISTINCT removed the duplicate, GLOB kept only rows whose date looks like dd/mm/yyyy, and NULLIF(trim(city), '') turned an empty city into NULL. The second result is the raw row that was kept in staging for audit. The capital letters in dhaka and DHAKA are still untidy (SQLite has no built-in "title case"), so one more SQL step finishes the job:

UPDATE sales_elt SET city = upper(substr(city, 1, 1)) || lower(substr(city, 2)) WHERE city IS NOT NULL;
SELECT * FROM sales_elt ORDER BY order_id;
SELECT (SELECT COUNT(*) FROM staging) AS staging_rows, (SELECT COUNT(*) FROM sales_elt) AS clean_rows;
order_id  sale_date   city        amount
--------  ----------  ----------  ------
    1001  2026-01-05  Dhaka         1200
    1002  2026-01-06  Chattogram     450
    1003  2026-01-07  NULL           300
    1005  2026-01-09  Dhaka         2050
(4 rows)

staging_rows  clean_rows
------------  ----------
           6           4
(1 row)
UPDATE sales_elt SET city = upper(substr(city, 1, 1)) || lower(substr(city, 2)) WHERE city IS NOT NULL;
SELECT * FROM sales_elt ORDER BY order_id;
SELECT (SELECT COUNT(*) FROM staging) AS staging_rows, (SELECT COUNT(*) FROM sales_elt) AS clean_rows;
order_id  sale_date   city        amount
--------  ----------  ----------  ------
    1001  2026-01-05  Dhaka         1200
    1002  2026-01-06  Chattogram     450
    1003  2026-01-07  NULL           300
    1005  2026-01-09  Dhaka         2050
(4 rows)

staging_rows  clean_rows
------------  ----------
           6           4
(1 row)
UPDATE sales_elt SET city = upper(substr(city, 1, 1)) || lower(substr(city, 2)) WHERE city IS NOT NULL;
SELECT * FROM sales_elt ORDER BY order_id;
SELECT (SELECT COUNT(*) FROM staging) AS staging_rows, (SELECT COUNT(*) FROM sales_elt) AS clean_rows;
order_id  sale_date   city        amount
--------  ----------  ----------  ------
    1001  2026-01-05  Dhaka         1200
    1002  2026-01-06  Chattogram     450
    1003  2026-01-07  NULL           300
    1005  2026-01-09  Dhaka         2050
(4 rows)

staging_rows  clean_rows
------------  ----------
           6           4
(1 row)

Both routes end with the same four clean rows. The difference is where the work happens, and what is left behind: ELT still has the raw staging table, so if a rule was wrong you can fix the SQL and re-run it without going back to the source.

4. ETL or ELT?

ETL ELT
Where is the cleaning? in a program or tool outside in SQL inside the warehouse
Raw data kept? only if you save it separately yes, in staging
Good when the warehouse is small or weak; sensitive fields must be removed before loading the warehouse is powerful and cheap to run big jobs; you want to re-run or change rules
Risk a program bug can lose rows silently raw (maybe sensitive) data sits in the warehouse

Neither is "better". Many teams mix them: a light cleanup in code, the heavy shaping in SQL.

5. Habits of a reliable load

  • Make it repeatable (idempotent). Running the load twice should not create duplicate rows. Use keys, INSERT OR REPLACE, or clear and reload a staging table.
  • Never silently drop rows. Send bad rows to a reject table or list, with the reason, and count them.
  • Compare counts. Source rows = loaded rows + rejected rows + duplicates removed. Here: 6 = 4 + 1 + 1.
  • Load in increments when tables are large (only what changed since the last run) rather than reloading everything.
  • Write down the rules, such as "missing city is allowed, missing date is not", so everyone agrees.

Worked example: the load audit

Check that no rows vanished in the ETL run above.

Step Rows
In the file 6
Duplicate removed (order 1002 twice) 1
Rejected (order 1004, bad date) 1
Loaded into sales_clean 4

6 = 1 + 1 + 4, so every input row is accounted for. If the sum did not match, the load would have a bug, and you would find out on the day it ran rather than months later in a wrong report.

Common mistakes

  • Dropping bad rows without a trace. Totals then differ from the source and nobody knows why.
  • Loading the same file twice and doubling the numbers.
  • Guessing a date format. 05/01/2026 is 5 January in dd/mm/yyyy and 1 May in mm/dd/yyyy; confirm the source's format.
  • Cleaning sensitive data after it is already in the warehouse when privacy rules require removing it before loading.
  • Transforming without tests, such as .title() on names that do not follow its rules.

Key takeaways

  • ETL = extract, transform, load; ELT = extract, load, transform.
  • ETL cleans outside the database; ELT loads raw data into staging and cleans with SQL inside.
  • Decide what to do with duplicates and bad rows, and record every rejected row.
  • Make loads repeatable, and reconcile counts after each run.
  • Choose by where the compute is, whether raw data should be kept, and privacy rules.

Practice

1. What are the letters in ETL and ELT, and what is the difference in order?

Show answer

Extract, Transform, Load versus Extract, Load, Transform. In ELT, raw data is loaded first and transformed inside the warehouse.

2. Why was the staging table created with TEXT columns only?

Show answer

So that every row loads without type errors, even bad ones; the conversion and checking happen afterwards in SQL.

3. In the audit, why do 6 input rows equal 4 + 1 + 1?

Show answer

4 rows were loaded, 1 was a duplicate that was dropped, and 1 was rejected for a bad date.

4. Why is INSERT of the same file twice a problem, and how would you prevent it?

Show answer

The same sales would be counted twice. Prevent it with a primary key on order_id (the second run fails or replaces), or clear and reload staging each run.

5. Give one reason to prefer ETL and one to prefer ELT.

Show answer

ETL: sensitive columns must be removed before data enters the warehouse. ELT: you want to keep the raw data and re-run changed rules cheaply with SQL on a powerful warehouse.

6. A file has the date 03/04/2026. What must you find out before converting it?

Show answer

Whether the format is dd/mm/yyyy (3 April) or mm/dd/yyyy (4 March); the source's documentation or its owner must say.