<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mike Cummings on Medium]]></title>
        <description><![CDATA[Stories by Mike Cummings on Medium]]></description>
        <link>https://medium.com/@mike.cummings?source=rss-5a68985ed1d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ydvhnaIX3RLSeVE0</url>
            <title>Stories by Mike Cummings on Medium</title>
            <link>https://medium.com/@mike.cummings?source=rss-5a68985ed1d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:29:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mike.cummings/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting “Required” Fields in BigQuery Using dbt]]></title>
            <link>https://blog.montrealanalytics.com/setting-required-fields-in-bigquery-using-dbt-b7a294d31080?source=rss-5a68985ed1d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7a294d31080</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[self-service]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Mike Cummings]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 10:10:42 GMT</pubDate>
            <atom:updated>2023-06-27T10:42:23.255Z</atom:updated>
            <content:encoded><![CDATA[<p>For those of us working with curated data, we are always on the lookout for null values appearing where they shouldn’t. Nulls indicate a record is missing or unknown; in some cases, this is expected, but for some key attributes, we expect data to always be present and it can cause issues downstream if this is not the case.</p><p>In most data warehouse platforms, we can apply column constraints to prevent nulls from being added in the first place. Google BigQuery is no exception; you can set the <strong>mode</strong> of a column to <strong>Required</strong>, which means no null values are permitted in that particular column.</p><p>When using BigQuery with <strong>dbt</strong>, however, there is no “out of the box” way of applying the Required mode. Instead, it’s a common practice to add <a href="https://docs.getdbt.com/docs/build/tests#generic-tests">not-null tests</a> in order to flag nulls as soon as they appear.</p><p>However, it is possible to customise dbt in order to make use of Required fields in BigQuery.</p><h4>BigQuery modes — how do they work?</h4><p>There are three modes generally available in BigQuery:</p><ul><li>Nullable (default)</li><li>Required</li><li>Repeated</li></ul><p><em>(rounding modes are also available in Preview, for numeric data types)</em></p><p><strong>Nullable </strong>fields are the default option if no other mode is specified, and this allows null values to be added to the column. <strong>Required </strong>mode enforces the opposite; if you try to insert nulls into a required column an error will be thrown. Finally, <strong>Repeated </strong>is used for columns containing an array of values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*-qoianWjMTr3qGki5yMcKg.png" /><figcaption>Figure 1: The column mode is shown in the BigQuery UI under the schema details</figcaption></figure><p>Modes can be defined upon table creation by manually specifying the schema in your CREATE TABLE statement:</p><pre>CREATE TABLE IF NOT EXISTS mydataset.example <br>  (x INT64, <br>   y STRING, <br>   z BOOL NOT NULL)<br>  OPTIONS(<br>    description = &#39;An example table&#39;);</pre><p><em>Code Block 1: CREATE TABLE with schema definitions</em></p><p>Specifying column z as NOT NULL will set the mode of this column as REQUIRED.</p><p>This is fine when creating tables manually, however, in a production data warehouse, table creation would often be automated using a transformation tool such as <a href="https://www.getdbt.com/"><strong>dbt</strong></a>.</p><p>Under the hood, dbt takes your transformation SQL and wraps it in a CREATE OR REPLACE TABLE statement, like this:</p><pre>CREATE OR REPLACE TABLE mydataset.example <br>AS (<br>  ...<br>)</pre><p><em>Code Block 2: CREATE TABLE without schema definitions</em></p><p>Where ... in Code Block 2 will be the SQL transformation logic from your dbt model.</p><p>This method of creating tables will automatically determine the schema of the created table using the data types outputted by your SQL statement. This means arrays will automatically be assigned the REPEATED mode, but everything else will have the default mode of NULLABLE. There is not currently an “out of the box” way of defining columns as REQUIRED using dbt.</p><p>This means that null values can be inadvertently added to your tables. In some cases this can be problematic, so dbt offer built-in tests to check for null values in specific columns and throw an error if any are found.</p><p>Schema tests like this can be useful to flag any data quality issues, however these tests run <strong>after</strong> the table has been populated so your data may already be affected by null values before the error is raised. These tests also run as separate queries against your database which can impact cost and performance when working at scale.</p><p>So, how can we set columns as REQUIRED using dbt to prevent these null values?</p><h4>The Solution: dbt override</h4><p>One solution to this is to override dbt’s mechanism for creating tables.</p><p>Essentially, we want to change dbt’s method of creating tables from the one shown in Code Block 2, to that shown in Code Block 1. Then, we can add in the NOT NULL constraint for any columns we wish to set as required.</p><p>The create table logic in dbt is powered by a built-in macro called create_table_as. Since dbt is compatible with multiple clouds and database systems, this is prefixed with the relevant data platform; in our case we are interested in bigquery__create_table_as.</p><p>This is the built-in bigquery__create_table_as macro as of version 1.3.1:</p><pre>{% macro bigquery__create_table_as(temporary, relation, compiled_code, language=&#39;sql&#39;) -%}<br>  {%- if language == &#39;sql&#39; -%}<br>    {%- set raw_partition_by = config.get(&#39;partition_by&#39;, none) -%}<br>    {%- set raw_cluster_by = config.get(&#39;cluster_by&#39;, none) -%}<br>    {%- set sql_header = config.get(&#39;sql_header&#39;, none) -%}<br><br>    {%- set partition_config = adapter.parse_partition_by(raw_partition_by) -%}<br><br>    {{ sql_header if sql_header is not none }}<br><br>    create or replace table {{ relation }}<br>    {{ partition_by(partition_config) }}<br>    {{ cluster_by(raw_cluster_by) }}<br>    {{ bigquery_table_options(config, model, temporary) }}<br>    as (<br>      {{ compiled_code }}<br>    );<br>  {%- elif language == &#39;python&#39; -%}<br>    {#--<br>    N.B. Python models _can_ write to temp views HOWEVER they use a different session<br>    and have already expired by the time they need to be used (I.E. in merges for incremental models)<br><br>    TODO: Deep dive into spark sessions to see if we can reuse a single session for an entire<br>    dbt invocation.<br>     --#}<br>    {{ py_write_table(compiled_code=compiled_code, target_relation=relation.quote(database=False, schema=False, identifier=False)) }}<br>  {%- else -%}<br>    {% do exceptions.raise_compiler_error(&quot;bigquery__create_table_as macro didn&#39;t get supported language, it got %s&quot; % language) %}<br>  {%- endif -%}<br><br>{%- endmacro -%}</pre><p><em>Check the </em><a href="https://github.com/dbt-labs/dbt-bigquery/blob/main/dbt/include/bigquery/macros/adapters.sql"><em>dbt-bigquery</em></a><em> project for any updates to this macro.</em></p><p>There are three main additions we want to make to our dbt project in order to enable this change.</p><ol><li><strong>Specify required fields in YAML</strong></li></ol><p>dbt already supports certain YAML-based column configurations such as adding descriptions and metadata. We can define a new column configuration here called “mode” and set it to “required” where applicable:</p><pre>- name: example<br>  description: An example table using dbt and BigQuery<br>  columns:<br>    - name: message_id<br>      description: Unique ID of a message<br>      mode: &#39;required&#39;  </pre><p>Then in our bigquery__create_table_as macro, we can check if there are any required fields present in a model’s column definition:</p><pre>if &#39;required&#39; in model.columns|string</pre><p>If true, we want to structure our CREATE TABLE statement in order to support required fields (along the lines of Code Block 1 above). If false, we can allow dbt to follow its usual pattern (Code Block 2).</p><p><strong>2. Build a list of columns</strong></p><p>In order to build the CREATE TABLE structure shown in Code Block 1, we will need to construct a list of columns; their names, data types and — in the case of required fields — a NOT NULL constraint.</p><p>We can get the names and datatypes of our columns using another of dbt’s built-in macros:</p><pre>columns = adapter.get_columns_in_relation(relation)</pre><p>This will create a list of <a href="https://docs.getdbt.com/reference/dbt-classes#column">column objects</a> within the model, including their names and datatypes. The relation used here would be the current model if the table exists already and the schema is stable — if not, you may need an additional step to derive the schema from your model SQL, something like this:</p><pre>{% set tmp_relation = make_temp_relation(this) %}<br><br>{% set tmp_sql = &quot;create or replace table &quot; ~ tmp_relation ~ &quot; as (&quot; ~ compiled_code ~ &quot; limit 0);&quot; %}<br><br>{% do run_query(tmp_sql) %}<br><br>{%- set columns = adapter.get_columns_in_relation(tmp_relation) -%}</pre><p>This executes your compiled SQL into a temporary table and extracts the columns from that. Note the limit 0 used here — this allows you to derive the schema without incurring any costs.</p><p>We can add the required column details into a dictionary for easier use later on, and append a NOT NULL constraint to any columns which are configured as required:</p><pre>{% for column in columns %}<br>    {% if model.columns.get(column.name, {}).get(&#39;mode&#39;) == &#39;required&#39; %}<br>      {% set dummy = column_dict.update({column.name: column.data_type ~ &quot; NOT NULL&quot;}) %}<br>    {% else %}<br>      {% set dummy = column_dict.update({column.name: column.data_type}) %}<br>    {% endif %}<br>{% endfor %}</pre><p><strong>3. Create the table</strong></p><p>Now we can pass in our column list, and the SQL logic obtained from our dbt model, to generate the CREATE TABLE statement:</p><pre>    create or replace table {{ relation }}<br>    (<br>      {% for column_name, data_type in column_dict.items() %}<br>        {% if not loop.last %}<br>          {{ column_name }} {{ data_type }},<br>        {% else %}<br>          {{ column_name }} {{ data_type }}<br>        {% endif %}<br>      {% endfor %}<br>    )<br>    {{ partition_by(partition_config) }}<br>    {{ cluster_by(raw_cluster_by) }}<br>    {{ bigquery_table_options(config, model, temporary) }}<br>    as (<br>      {{ sql }}<br>    );</pre><p>When dbt compiles and runs your model, the SQL will something look like this:</p><pre>create or replace table `my-project`.`my_dataset`.`example`<br>(      <br>      x INT64,         <br>      y STRING,   <br>      z BOOLEAN NOT NULL<br>)     <br>OPTIONS(<br>description=&quot;&quot;&quot;An example table using dbt and BigQuery&quot;&quot;&quot;,<br>)<br>as (<br>  SELECT<br>    ...<br>);</pre><p>As you can see, this is of the form shown in Code Block 1, and contains the NOT NULL constraints we need. When viewing the materialised table in the BigQuery console we see the Required column as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*xWmdU2AHs9Vrg6zxkZ5jqw.png" /></figure><p>And we’re done! Here’s an example of a modified macro, bringing together all of the components from above:</p><pre>{% macro bigquery__create_table_as(temporary, relation, compiled_code, language=&#39;sql&#39;) -%}<br>  {%- if language == &#39;sql&#39; -%}<br>    {%- set raw_partition_by = config.get(&#39;partition_by&#39;, none) -%}<br>    {%- set raw_cluster_by = config.get(&#39;cluster_by&#39;, none) -%}<br>    {%- set sql_header = config.get(&#39;sql_header&#39;, none) -%}<br><br>    {%- set partition_config = adapter.parse_partition_by(raw_partition_by) -%}<br><br>    {% if &#39;required&#39; in model.columns|string and not temporary %}<br><br>      {% set tmp_relation = make_temp_relation(this) %}<br><br>      {% set tmp_sql = &quot;create or replace table &quot; ~ tmp_relation ~ &quot; as (&quot; ~ compiled_code ~ &quot; limit 0);&quot; %}<br><br>      {% do run_query(tmp_sql) %}<br><br>      {%- set columns = adapter.get_columns_in_relation(tmp_relation) -%}<br><br>      {% do adapter.drop_relation(tmp_relation) %}<br><br>      {% set column_dict = {} %}<br><br>      {% for column in columns %}<br>        {% if model.columns.get(column.name, {}).get(&#39;mode&#39;) == &#39;required&#39; %}<br>          {% set dummy = column_dict.update({column.name: column.data_type ~ &quot; NOT NULL&quot;}) %}<br>        {% else %}<br>          {% set dummy = column_dict.update({column.name: column.data_type}) %}<br>        {% endif %}<br>      {% endfor %}<br><br>      {{ sql_header if sql_header is not none }}  <br><br>      create or replace table {{ relation }}<br>      (<br>        {% for column_name, data_type in column_dict.items() %}<br>          {% if not loop.last %}<br>            {{ column_name }} {{ data_type }},<br>          {% else %}<br>            {{ column_name }} {{ data_type }}<br>          {% endif %}<br>        {% endfor %}<br>      )<br>      {{ partition_by(partition_config) }}<br>      {{ cluster_by(raw_cluster_by) }}<br>      {{ bigquery_table_options(config, model, temporary) }}<br>      as (<br>        {{ compiled_code }}<br>      );<br><br>    {% else %}<br><br>      {{ sql_header if sql_header is not none }}<br><br>      create or replace table {{ relation }}<br>      {{ partition_by(partition_config) }}<br>      {{ cluster_by(raw_cluster_by) }}<br>      {{ bigquery_table_options(config, model, temporary) }}<br>      as (<br>        {{ compiled_code }}<br>      );<br><br>    {% endif %}<br><br>  {%- elif language == &#39;python&#39; -%}<br>    {#--<br>    N.B. Python models _can_ write to temp views HOWEVER they use a different session<br>    and have already expired by the time they need to be used (I.E. in merges for incremental models)<br><br>    TODO: Deep dive into spark sessions to see if we can reuse a single session for an entire<br>    dbt invocation.<br>     --#}<br>    {{ py_write_table(compiled_code=compiled_code, target_relation=relation.quote(database=False, schema=False, identifier=False)) }}<br>  {%- else -%}<br>    {% do exceptions.raise_compiler_error(&quot;bigquery__create_table_as macro didn&#39;t get supported language, it got %s&quot; % language) %}<br>  {%- endif -%}<br><br>{%- endmacro -%}</pre><p>This can be adapted to suit your own use cases, but first there are some important considerations to bear in mind — explained below.</p><h4>Considerations &amp; Caveats</h4><p>The method described above allows you to leverage BigQuery modes, but there are some important points to think about before implementing a solution like this.</p><p>Firstly, built-in macros such as create_table_asare maintained by dbt Labs and can change from one version to the next. If you update your dbt version, do make sure to update your custom macros as well or risk missing out on the latest functionality!</p><p>It’s also important to consider that this method adds complexity to the default table creation method and requires additional computational steps — though performance impact can be mitigated using the limit 0 technique used above. Make sure to keep an eye on performance and decide whether the benefits of Required fields outweigh any potential impact, for your own use cases.</p><p>Finally, note that a small change will be required in your dbt project configuration to ensure that your custom macro takes precedence over the default dbt version.</p><p>Simply add a <a href="https://docs.getdbt.com/reference/dbt-jinja-functions/dispatch#overriding-global-macros">project-level dispatch configuration</a> like this to your dbt_project.yml file:</p><pre>dispatch:<br>  - macro_namespace: dbt<br>    search_order: [&#39;my_project&#39;, &#39;dbt&#39;]</pre><p>This means dbt will search your own project for valid macros ahead of dbt’s default search locations.</p><h4>Conclusion</h4><p>Now that we have customised our table creation macro and configured our dbt project to override the built-in version, we can set fields as Required in BigQuery using dbt — and avoid those problematic null values.</p><p>Once this is all set up, setting a new field as Required is as simple as adding <em>mode: ‘required’</em> to your YAML column definitions…</p><pre>- name: example<br>  description: An example table using dbt and BigQuery<br>  columns:<br>    - name: message_id<br>      description: Unique ID of a message<br>      mode: &#39;required&#39;</pre><p>…and dbt will do the rest!</p><p><em>Datatonic, Google Cloud’s 4 X Partner of the Year, is the leading cloud data + AI consultancy for the world’s most ambitious businesses, challenging traditions to deliver tangible innovation at the leading edge of Google Cloud. Our team also has a wealth of experience with dbt, running the Expert Lounge at dbt Labs’ recent London event, Coalesce London. Need help with dbt? Get in touch at </em><a href="https://datatonic.com/contact/"><em>datatonic.com/contact/</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7a294d31080" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/setting-required-fields-in-bigquery-using-dbt-b7a294d31080">Setting “Required” Fields in BigQuery Using dbt</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>