Reference Queries
Learn how to include code from another query
Introduction
The Reference Queries feature allows you to include SQL code from another file in your current SQL query. This is useful for reusing common parts of a query, ensuring that your SQL code is consistent and easy to maintain.
How It Works
To reference SQL code from another file, use the syntax {ref ('other_query')}
, where other_query
is the name of another .sql
file located in the /queries
folder. This syntax imports the raw SQL code from the specified file to the location where it is added.
Code Example
Assuming that you have a file named other_query.sql
in the /queries
folder, you can include its SQL code in your current query as follows:
SELECT *
FROM {ref ('other_query')}
This will dynamically insert the SQL code from other_query.sql
into your current query, allowing you to build complex queries by reusing existing blocks of code.
Referencing queries as a source
An important use case for referencing queries is adding them as source. You can do this as follows:
SELECT *
FROM {ref ('users_clean')}
Which will translate to:
SELECT id, first_name, ...
FROM users
SELECT *
FROM (
SELECT
id,
first_name,
last_name,
email
)