StackPractices
intermediate By Mathias Paulenko

ETL Extract-Transform-Load Pattern in Python & SQL

How to build ETL pipelines with extract, transform, and load stages. Covers staging tables, incremental extraction, idempotent loads, and orchestration.

Topics: data

Overview

ETL (Extract, Transform, Load) is the classic data integration pattern: pull data out of source systems, reshape it to fit the target schema, and write it into a warehouse or lake. The extract stage lands raw rows in a staging area, the transform stage cleans and reshapes them there, and the load stage upserts the result into the destination. Keeping each stage a separate step with a physical handoff (a staging table) is what makes the pipeline debuggable and restartable: when a run fails, you inspect the staging table instead of guessing what the source looked like at 2 AM.

ETL is batch-oriented. It runs on a schedule (hourly, nightly, weekly) rather than reacting to events, which keeps load off the source systems but means your warehouse is only as fresh as the last run. If you need fresher data, that’s a different pattern: see CDC (Change Data Capture).

The examples below build up a complete ETL pipeline: a Python implementation with staging, the same flow in pure SQL, incremental extraction with watermarks, an Airflow DAG that orchestrates the stages, and a Spring Batch job in Java. For a runnable single-file version using pandas and Parquet instead of a warehouse, check the pandas ETL recipe; the complete project files with a pytest suite live in the companion repository. For the long-form walkthrough with extraction strategies and SCD handling, see the ETL pipeline guide.

When to Use

  • Periodic syncs from operational databases (CRM, ERP, app DBs) into a warehouse
  • Batch reporting and analytics that don’t need real-time data
  • Data migrations between systems with different schemas
  • Regulatory reporting that requires a consistent snapshot at a point in time
  • Source systems that can’t handle continuous query load from consumers

When NOT to Use

  • Real-time analytics: use CDC or streaming instead
  • Simple data copies with no transformation: direct replication is cheaper
  • Sources that change continuously and require sub-minute freshness
  • When the transform needs the full power of the target warehouse: that’s ELT (see Variants)

Solution

Every implementation below follows the same skeleton: extract into staging, transform from staging, load with an upsert, then validate and record the watermark. The staging table is the contract between stages; it’s what lets you re-run the transform without re-hitting the source.

ETL pipeline flow — extract pulls rows from source systems into staging tables, transform cleans and reshapes them, load upserts into the warehouse, while a watermark store feeds the next incremental run and a validation step checks row counts after load.

Python ETL pipeline with staging

This is the reference implementation. It takes a source, a staging, and a warehouse connection (SQLAlchemy engines work fine), and runs the three stages with a run ID stamped on every staging table so concurrent or retried runs don’t collide. Pass your own run_id to tie it to an orchestrator’s run identifier.

# etl_pipeline.py — ETL pipeline with extract, transform, load stages
import pandas as pd
from datetime import datetime
from sqlalchemy import text
import logging
import hashlib

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class ETLPipeline:
    def __init__(self, source_conn, staging_conn, warehouse_conn, run_id=None):
        self.source = source_conn
        self.staging = staging_conn
        self.warehouse = warehouse_conn
        self.run_id = run_id or hashlib.md5(str(datetime.now()).encode()).hexdigest()[:8]

    def run(self, source_table, target_table, since=None):
        logger.info(f"ETL run {self.run_id} started for {source_table} -> {target_table}")

        try:
            # Stage 1: Extract
            raw_data = self.extract(source_table, since)

            # Stage 2: Transform
            transformed_data = self.transform(raw_data)

            # Stage 3: Load
            self.load(transformed_data, target_table)

            logger.info(f"ETL run {self.run_id} completed successfully")
            return {"run_id": self.run_id, "rows_processed": len(transformed_data)}

        except Exception as e:
            logger.error(f"ETL run {self.run_id} failed: {e}")
            raise

    def extract(self, table, since):
        logger.info(f"Extracting from {table} since {since}")
        query = f"SELECT * FROM {table}"
        if since:
            query += f" WHERE updated_at >= :since"

        df = pd.read_sql(text(query), self.source, params={"since": since} if since else None)
        df['_etl_run_id'] = self.run_id
        df['_etl_extracted_at'] = datetime.now()

        # Write to a staging table namespaced by run id
        staging_table = f"stg_{table}_{self.run_id}"
        df.to_sql(staging_table, self.staging, index=False, if_exists='replace')
        logger.info(f"Extracted {len(df)} rows to {staging_table}")

        return df

    def transform(self, df):
        logger.info(f"Transforming {len(df)} rows")

        df = df.drop_duplicates(subset=['id'])

        if 'email' in df.columns:
            df['email'] = df['email'].str.lower().str.strip()

        if 'created_at' in df.columns:
            df['created_at'] = pd.to_datetime(df['created_at'], errors='coerce')

        if 'status' in df.columns:
            df['is_active'] = df['status'] == 'active'
        if {'first_name', 'last_name'} <= set(df.columns):
            df['full_name'] = df['first_name'] + ' ' + df['last_name']

        # Drop ETL metadata columns
        df = df.drop(columns=['_etl_run_id', '_etl_extracted_at'], errors='ignore')

        df = df.dropna(subset=['id'])
        logger.info(f"Transformed to {len(df)} rows")
        return df

    def load(self, df, target_table):
        logger.info(f"Loading {len(df)} rows to {target_table}")

        # Upsert: delete the ids we're about to write, then insert
        if not df.empty:
            with self.warehouse.begin() as conn:
                conn.execute(
                    text(f"DELETE FROM {target_table} WHERE id = ANY(:ids)"),
                    {"ids": df['id'].tolist()},
                )
        df.to_sql(target_table, self.warehouse, index=False, if_exists='append')
        logger.info(f"Loaded {len(df)} rows to {target_table}")

A few things worth noticing. The since parameter makes the same class usable for both full and incremental loads. The load is a delete-then-insert inside one transaction, which is what makes a re-run idempotent. And ANY(:ids) is PostgreSQL syntax, so swap in an expanding IN clause for MySQL or SQL Server.

SQL-based ETL with staging tables

When the warehouse can do the work, skip the application layer entirely. This version (PostgreSQL dialect; MERGE needs PG15+) does the whole pipeline in three statements, and it’s the fastest option because nothing leaves the database:

-- etl_customers.sql — SQL ETL with staging tables (PostgreSQL 15+)

-- Stage 1: Extract — copy raw data to staging
CREATE TABLE stg_customers AS
SELECT
    id,
    email,
    first_name,
    last_name,
    status,
    created_at,
    updated_at,
    CURRENT_TIMESTAMP AS _extracted_at,
    'daily_batch' AS _source
FROM source_db.customers
WHERE updated_at >= CURRENT_DATE - INTERVAL '1 day';

-- Stage 2: Transform — clean and reshape into a second staging table
CREATE TABLE tmp_customers AS
SELECT
    id,
    LOWER(TRIM(email)) AS email,
    TRIM(first_name) AS first_name,
    TRIM(last_name) AS last_name,
    status,
    (status = 'active') AS is_active,
    CONCAT(TRIM(first_name), ' ', TRIM(last_name)) AS full_name,
    COALESCE(created_at, _extracted_at) AS created_at,
    updated_at
FROM stg_customers
WHERE id IS NOT NULL
  AND email IS NOT NULL;

-- Stage 3: Load — upsert to warehouse
MERGE INTO warehouse.customers AS target
USING tmp_customers AS source
ON target.id = source.id
WHEN MATCHED THEN
    UPDATE SET
        email = source.email,
        first_name = source.first_name,
        last_name = source.last_name,
        status = source.status,
        is_active = source.is_active,
        full_name = source.full_name,
        updated_at = source.updated_at
WHEN NOT MATCHED THEN
    INSERT (id, email, first_name, last_name, status, is_active, full_name, created_at, updated_at)
    VALUES (source.id, source.email, source.first_name, source.last_name,
            source.status, source.is_active, source.full_name, source.created_at, source.updated_at);

-- Cleanup: staging tables are disposable once the load is validated
DROP TABLE stg_customers;
DROP TABLE tmp_customers;

Using MERGE instead of delete+insert is atomic per row, so a reader never sees the gap between the delete and the insert. The trade-off is that MERGE isn’t portable: MySQL needs INSERT ... ON DUPLICATE KEY UPDATE, older SQL Server and Oracle have their own MERGE variants with different syntax.

Incremental extraction with watermarks

Full extracts stop being viable once tables get large. A high-water mark (the maximum updated_at seen in the last successful run) is the standard way to extract only what changed:

# incremental_etl.py — incremental extraction using a high-water mark
import json
import pandas as pd
from sqlalchemy import text
from pathlib import Path

class IncrementalETL:
    def __init__(self, watermark_file="watermarks.json"):
        self.watermark_file = Path(watermark_file)
        self.watermarks = self._load_watermarks()

    def _load_watermarks(self):
        if self.watermark_file.exists():
            return json.loads(self.watermark_file.read_text())
        return {}

    def _save_watermarks(self):
        self.watermark_file.write_text(json.dumps(self.watermarks, indent=2, default=str))

    def get_watermark(self, table):
        return self.watermarks.get(table)

    def update_watermark(self, table, value):
        self.watermarks[table] = value
        self._save_watermarks()

    def extract_incremental(self, conn, table, timestamp_col="updated_at"):
        last_run = self.get_watermark(table)

        if last_run:
            query = text(
                f"SELECT * FROM {table} "
                f"WHERE {timestamp_col} > :wm ORDER BY {timestamp_col}"
            )
            df = pd.read_sql(query, conn, params={"wm": last_run})
        else:
            df = pd.read_sql(text(f"SELECT * FROM {table}"), conn)

        if not df.empty:
            new_watermark = df[timestamp_col].max()
            self.update_watermark(table, str(new_watermark))

        return df

Two edge cases trip people up here. Rows updated during the extract can be missed if you watermark with now() instead of max(updated_at) from the pulled batch, so always watermark from the data, not the clock. And deletes are invisible to timestamp watermarks entirely; if you need deletes, that’s what CDC is for.

Airflow DAG for ETL orchestration

Once a pipeline has more than one stage and a schedule, a cron job stops being enough. This DAG wraps the same ETLPipeline class from above: each task runs one stage and hands off through the staging table, which is exactly how production ETL pipelines pass data between tasks (never through XCom for row payloads). It uses connections defined in Airflow (source_db, staging_db, warehouse_db) and the schedule parameter from Airflow 2.4+:

# etl_dag.py — Airflow DAG orchestrating the ETLPipeline stages
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.postgres.hooks.postgres import PostgresHook
from datetime import datetime, timedelta
import pandas as pd
import re

default_args = {
    'owner': 'data-team',
    'depends_on_past': False,
    'email_on_failure': True,
    'retries': 2,
    'retry_delay': timedelta(minutes=5),
}

dag = DAG(
    'etl_customers_daily',
    default_args=default_args,
    description='Daily ETL for customers table',
    schedule='0 2 * * *',
    start_date=datetime(2026, 1, 1),
    catchup=False,
    tags=['etl', 'daily'],
)


def _pipeline(context):
    from etl.pipeline import ETLPipeline
    # Airflow run ids contain ':' and '+' — strip them for table-safe names
    safe_run_id = re.sub(r'\W', '', context['run_id'])[:12]
    source = PostgresHook(postgres_conn_id='source_db').get_sqlalchemy_engine()
    staging = PostgresHook(postgres_conn_id='staging_db').get_sqlalchemy_engine()
    warehouse = PostgresHook(postgres_conn_id='warehouse_db').get_sqlalchemy_engine()
    return ETLPipeline(source, staging, warehouse, run_id=safe_run_id)


def extract(**context):
    pipeline = _pipeline(context)
    pipeline.extract('customers', since=context['ds'])
    context['ti'].xcom_push(key='staging_table',
                           value=f"stg_customers_{pipeline.run_id}")


def transform(**context):
    pipeline = _pipeline(context)
    staging_table = context['ti'].xcom_pull(task_ids='extract', key='staging_table')
    df = pd.read_sql_table(staging_table, pipeline.staging)
    pipeline.transform(df).to_sql('tmp_customers', pipeline.staging,
                                  index=False, if_exists='replace')


def load(**context):
    pipeline = _pipeline(context)
    df = pd.read_sql_table('tmp_customers', pipeline.staging)
    pipeline.load(df, 'customers')
    context['ti'].xcom_push(key='rows_loaded', value=len(df))


def validate(**context):
    expected = context['ti'].xcom_pull(task_ids='load', key='rows_loaded')
    hook = PostgresHook(postgres_conn_id='warehouse_db')
    actual = hook.get_first("SELECT COUNT(*) FROM customers")[0]
    if actual < expected * 0.95:
        raise ValueError(
            f"Row count check failed: expected ~{expected}, got {actual}"
        )


def cleanup(**context):
    from sqlalchemy import text
    pipeline = _pipeline(context)
    staging_table = context['ti'].xcom_pull(task_ids='extract', key='staging_table')
    with pipeline.staging.begin() as conn:
        conn.execute(text(f"DROP TABLE IF EXISTS {staging_table}"))
        conn.execute(text("DROP TABLE IF EXISTS tmp_customers"))


for name, fn in [('extract', extract), ('transform', transform),
                 ('load', load), ('validate', validate), ('cleanup', cleanup)]:
    globals()[f'{name}_task'] = PythonOperator(
        task_id=name,
        python_callable=fn,
        dag=dag,
    )

extract_task >> transform_task >> load_task >> validate_task >> cleanup_task

Notice the run ID plumbing: the DAG sanitizes Airflow’s run_id and passes it into the pipeline, so the staging table name is deterministic and the cleanup task can find it again via XCom. For more on scheduling options (datasets, timetables, backfills), see the Airflow DAG scheduling recipe and the official DAG documentation.

Java ETL with Spring Batch

In JVM shops, Spring Batch gives you the same three stages as reader / processor / writer, plus chunking, retry, and restart semantics for free. A chunk size of 1000 means each commit covers 1000 rows, so a failed chunk can be retried without re-reading the whole table:

// CustomerEtlJob.java — Spring Batch ETL job (Spring Batch 4 API)
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@EnableBatchProcessing
public class CustomerEtlJob {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private DataSource dataSource;

    @Bean
    public JdbcCursorItemReader<Customer> reader() {
        JdbcCursorItemReader<Customer> reader = new JdbcCursorItemReader<>();
        reader.setDataSource(dataSource);
        reader.setSql("SELECT id, email, first_name, last_name, status FROM source.customers WHERE updated_at >= ?");
        reader.setRowMapper(new CustomerRowMapper());
        return reader;
    }

    @Bean
    public ItemProcessor<Customer, Customer> processor() {
        return customer -> {
            customer.setEmail(customer.getEmail().toLowerCase().trim());
            customer.setFirstName(customer.getFirstName().trim());
            customer.setLastName(customer.getLastName().trim());
            customer.setFullName(customer.getFirstName() + " " + customer.getLastName());
            customer.setActive("active".equals(customer.getStatus()));
            return customer;
        };
    }

    @Bean
    public JdbcBatchItemWriter<Customer> writer() {
        JdbcBatchItemWriter<Customer> writer = new JdbcBatchItemWriter<>();
        writer.setDataSource(dataSource);
        writer.setSql("""
            MERGE INTO warehouse.customers target
            USING (VALUES (:id, :email, :firstName, :lastName, :status, :active, :fullName)) source
            ON target.id = source.id
            WHEN MATCHED THEN UPDATE SET email = source.email, first_name = source.first_name,
                last_name = source.last_name, status = source.status, is_active = source.active,
                full_name = source.full_name
            WHEN NOT MATCHED THEN INSERT (id, email, first_name, last_name, status, is_active, full_name)
                VALUES (source.id, source.email, source.first_name, source.last_name, source.status, source.active, source.full_name)
            """);
        writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>());
        return writer;
    }

    @Bean
    public Step etlStep() {
        return stepBuilderFactory.get("etlStep")
                .<Customer, Customer>chunk(1000)
                .reader(reader())
                .processor(processor())
                .writer(writer())
                .build();
    }

    @Bean
    public Job etlJob() {
        return jobBuilderFactory.get("etlCustomersJob")
                .start(etlStep())
                .build();
    }
}

This uses the Spring Batch 4 *BuilderFactory API. On Spring Batch 5 the factories were removed, so inject JobRepository and PlatformTransactionManager into JobBuilder/StepBuilder constructors instead; the reader/processor/writer beans stay identical.

Variants

ELT (Extract-Load-Transform)

ELT flips the middle steps: raw data goes straight into the warehouse, and the transform runs there on warehouse compute. Pick it when the warehouse is a columnar engine (Snowflake, BigQuery, Redshift) and the transform is expressible in SQL; you trade a cleaner architecture for tying yourself to the warehouse’s SQL dialect and paying for compute there:

-- ELT: load raw data first, transform inside the warehouse (Redshift COPY)
-- Step 1: Extract + Load raw
COPY raw.customers FROM 's3://bucket/customers/2026-07-05/' FORMAT PARQUET;

-- Step 2: Transform in warehouse (using warehouse compute)
CREATE TABLE warehouse.customers AS
SELECT
    id,
    LOWER(TRIM(email)) AS email,
    TRIM(first_name) AS first_name,
    TRIM(last_name) AS last_name,
    status,
    status = 'active' AS is_active
FROM raw.customers
WHERE id IS NOT NULL;

In practice, ELT pairs with a transformation layer like dbt, which brings version control and testing to the warehouse-side transforms. If the transforms need application-level logic (calling an API, custom parsing), that’s when ETL is the better fit (see the ETL vs ELT question below).

Parallel extraction from multiple sources

When you pull from several databases, extraction time adds up serially. Threads work well here because read_sql is I/O-bound, so the GIL isn’t the bottleneck:

# parallel_etl.py — extract from multiple sources concurrently
from concurrent.futures import ThreadPoolExecutor, as_completed
import pandas as pd
import logging

logger = logging.getLogger(__name__)

class ParallelETL:
    def __init__(self, sources):
        self.sources = sources  # dict of {name: connection}

    def extract_all(self, tables_config):
        results = {}

        with ThreadPoolExecutor(max_workers=4) as executor:
            futures = {}
            for source_name, tables in tables_config.items():
                for table in tables:
                    future = executor.submit(self._extract_from, source_name, table)
                    futures[future] = (source_name, table)

            for future in as_completed(futures):
                source_name, table = futures[future]
                try:
                    results[f"{source_name}.{table}"] = future.result()
                except Exception as e:
                    logger.error(f"Failed to extract {source_name}.{table}: {e}")
                    results[f"{source_name}.{table}"] = None

        return results

    def _extract_from(self, source_name, table):
        conn = self.sources[source_name]
        return pd.read_sql(f"SELECT * FROM {table}", conn)

The None result per failed source is deliberate: a partial failure shouldn’t kill the whole batch, but it must be visible in the results (and in your logs) rather than silently swallowed.

Best Practices

  • Use staging tables: never transform in place on the source; always extract to a staging area first
  • Make pipelines idempotent: running the same pipeline twice should produce the same result
  • Use incremental extraction: extract only changed rows using a watermark column
  • Log every stage: row counts at each step, timing, errors, and the run ID for debugging
  • Validate after load: check row counts, null checks, and referential integrity before dropping staging
  • Handle failures gracefully: retry with backoff, alert on failure, and allow restart from the failed step
  • Use an orchestrator: Airflow, Dagster, or Prefect for scheduling, retries, and dependencies
  • Keep transformations separate: don’t mix extract logic with transform logic in one function

Common Mistakes

  • No staging area: transforming directly on the source. If the transform fails midway, the source rows end up half-modified and there’s no clean snapshot left to recover from.
  • Full table extraction every run: pulling millions of rows when only a few hundred changed since the last run. Use incremental extraction with a watermark.
  • No error handling: if the load fails after the transform, the transformed rows are gone too. Use transactions or staging tables you can re-read.
  • Hardcoded timestamps: using CURRENT_DATE - 1 instead of a watermark table produces missed or duplicated rows on backfills and re-runs.
  • No validation: the load writes rows without checking counts, nulls, or referential integrity. Bad data silently enters the warehouse and corrupts downstream reports.
  • Passing row payloads through XCom: serializing dataframes between Airflow tasks is slow and can crash the metadata DB. Pass table names or file paths instead.
  • Dropping staging before validating: the staging table is your only copy of what the source looked like at extract time. Drop it only after post-load checks pass.

See Also

Frequently Asked Questions

What is the difference between ETL and ELT?

ETL transforms data before loading it into the warehouse. ELT flips the order: raw rows land in the warehouse first, and the warehouse's own compute runs the transform. ELT is preferred when the warehouse is capable (Snowflake, BigQuery) and the transform is SQL-based; ETL fits better when transforms need application code or the destination can't do the work.

What is a staging table?

A temporary table that holds raw extracted rows before the transform stage touches them. It isolates the source from the transform logic and acts as a checkpoint for debugging and restarts, so drop it only after post-load validation passes.

How do I make ETL pipelines idempotent?

Use upserts (MERGE) instead of plain inserts, or delete and re-insert rows for the same key set. Stamp a run ID on staging tables so a re-run can't collide with the previous attempt. The test is simple: running the pipeline twice must leave the warehouse in the same final state.

What is incremental extraction?

Extracting only rows that changed since the last run, using a timestamp column (e.g., updated_at) as a high-water mark. Watermark from max(updated_at) of the pulled batch, not from now(), so rows updated mid-extract aren't skipped. Deletes still need CDC.

Should I use Airflow for ETL?

Yes, if you're juggling more than one pipeline with dependencies, schedules, and retry requirements. Airflow gives you scheduling, dependency management, retries, and monitoring out of the box. For a single simple pipeline with no dependencies, a cron job wrapping a script usually does the job fine.