Search code examples
google-bigqueryjinja2dbt

Jinja and det for if else SQL statement


During the creation of a model in dbt I'm trying to construct an if else statement that has the following logic: if there is a table with the "table_name" name under the "project_name.dataset" then use this SELECT 1 else use SELECT 2

As I understand this should be something like this:

{% if "table_name" in run_query("
                            SELECT
                                table_name
                            FROM project-name.dataset.INFORMATION_SCHEMA.TABLES
                            ").columns[0].values() %}
SELECT
    1
{%.else %}
SELECT
    2
{%.endif %}

This is by the way all happens in the BigQuery, that's why we use project-name.dataset.INFORMATION_SCHEMA.TABLES to extract the name of all the tables under this project and dataset.

But unfortunately this approach doesn't work. It would be really great if somebody could help me, please.


Solution

  • Here is how I did it:

        {% set tables_list = [] %}
        
        {%- for row in run_query(
                                   "
                                    SELECT
                                        *
                                    FROM project-name.dataset_name.INFORMATION_SCHEMA.TABLES
                                    "
        ) -%}
                {{ tables_list.append(row.values()[2]) if tables_list.append(row.values()[2]) is not none }}
        {%- endfor -%}
    
    {% if "table_name" in tables_list %}
        SELECT logic 1
    {% else %}
        SELECT logic 2
    {% endif %}