
Credentials
Before starting, you need to add credentials so Mage can execute your SQL commands. Follow the steps for the database or data warehouse of your choice:Add SQL block to pipeline
- Create a new pipeline or open an existing pipeline.
- Add a data loader, transformer, or data exporter block.
- Select
SQL.
Configure SQL block
There are 4 - 5 fields that must be configured for each SQL block:Write policies
YAML configuration
You can also modify block configuration in pipeline’smetadata.yaml file. Each block has a configuration field.
Example configuration
Automatically created tables
Each SQL block will create a table in the data provider of your choice. When you run a block, it’ll execute your SQL command, then store the results in a table created in your database or data warehouse.Using raw SQL
If you toggle this setting, you’re responsible for writing theCREATE TABLE command and the
INSERT command.
For example, if a table already exists then you can write the INSERT statement:
CREATE TABLE statement
and the INSERT statement:
mage.users with 2 columns: id as a BIGINT
and username as a VARCHAR(255).
Then, it’ll insert a single row into that table.
Required SQL statements
When writing raw SQL, you must at least 1 of the following statements:SELECTINSERTCREATE TABLEDROP TABLEUPDATE
Multiple SQL statements
You can execute multiple SQL statements in a SQL block. Separate your SQL statements using a semi-colon (;).
Automatic naming of tables
If you don’t choose the setting for using raw SQL, the name of this automatically created table follows these conventions:- If
Databasefield is configured:[database].[schema].[pipeline UUID]_[block UUID] - If no
Databasefield is configured:[schema].[pipeline UUID]_[block UUID]
Upstream blocks
If your SQL block depends on upstream blocks that aren’t SQL blocks (e.g. Python code blocks), then those blocks will also automatically create tables. The name of those tables follows the same naming convention mentioned above.Variables
All SQL blocks have the following variables they can access in their query:{{ execution_date }}
The date and time the block is ran.
Example
If a SQL block has 1 or more upstream blocks, then they have access to their parent blocks’ output using the following variable:
{{ df_1 }}
Depending on how many upstream blocks there are, the variable name changes. For
example, if there are 3 upstream blocks then there are 3 variables that can be
accessed:
{{ df_1 }}{{ df_2 }}{{ df_3 }}
{{ df_1 }}, and every
upstream block added after that will have an incrementing number in the variable
name after the prefix df_.
Example