liveBook · Manning

SQLExecuteQueryOperator

As explained in Data Pipelines with Apache Airflow, Second Edition

SQLExecuteQueryOperator is an Airflow operator that executes SQL queries against a database.

Suppose an Airflow DAG extracts hourly page-view counts and needs to store them in PostgreSQL. SQLExecuteQueryOperator runs the SQL that writes those counts. It is a specialized alternative to writing database authentication, connection handling, and query execution inside a PythonOperator. section 5.4 section 6.2.1

A file-backed workflow has three parts:

  • Install the common SQL provider so the operator can be imported: pip install apache-airflow-providers-common-sql. section 5.4
  • Have an upstream task write INSERT statements to a SQL file accessible to the task that will execute them. Airflow tasks may run on different machines, so they cannot pass an in-memory object between tasks. section 5.4
  • Configure an Airflow database connection, then give the operator its task_id, conn_id, and SQL filename. Set the DAG’s template_searchpath to the file’s directory so the operator can find it. section 5.4

Execute generated INSERT statements

An upstream Python task writes statements such as INSERT INTO pageview_counts VALUES ('Google', 333, '2024-01-01T00:00:00'); to /tmp/postgres_query.sql. The downstream task uses SQLExecuteQueryOperator(task_id="write_to_postgres", conn_id="my_postgres", sql="postgres_query.sql") in a DAG with template_searchpath="/tmp". The my_postgres connection can be added with the Airflow CLI. section 5.4

The operator does not take CSV data directly as inserts in this workflow; generating SQL first bridges that gap. Ensure the SQL file is available wherever the executing task runs. Repeated DAG runs can also insert duplicate rows, so design the table’s key and INSERT conflict handling for retries or reruns. section 5.4

How Data Pipelines with Apache Airflow, Second Edition covers it

How deep it goes
Works through provider installation, SQL-file generation, connection setup, and operator arguments, while delegating database connection handling to a hook.
Examples
Uses hourly Wikipedia page-view INSERT statements, a PostgreSQL table, a generated SQL file, and an Airflow connection.
What it assumes
Assumes familiarity with DAG tasks and basic SQL, but shows the provider installation and connection configuration needed for this example.
What you can do after
Apply it via Airflow to execute generated SQL against a configured database connection, while checking file access and rerun behavior.
How it connects
Connects Airflow DAGs, PythonOperator, persistent task data, database connections, SQL templating, and DbApiHook.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Pipelines with Apache Airflow, Second Edition. The section links point to the parts of the book it draws on.