0
0
DbtHow-ToBeginner ยท 3 min read

How to Use + Operator in dbt Select Statements

In dbt select statements, the + operator is used to add numeric columns or concatenate strings depending on the data type. You can use it inside your SQL select clause to perform arithmetic addition or string concatenation when supported by your database.
๐Ÿ“

Syntax

The + operator in a dbt select statement is used to add two numeric columns or concatenate strings (if your database supports it). The general syntax is:

  • SELECT column1 + column2 AS result FROM table โ€” adds numeric columns.
  • SELECT string_column1 + string_column2 AS combined_string FROM table โ€” concatenates strings in some databases.

Note: String concatenation with + depends on your database (e.g., SQL Server supports it, but PostgreSQL uses ||).

sql
SELECT column1 + column2 AS sum_result
FROM your_table;
๐Ÿ’ป

Example

This example shows how to add two numeric columns using the + operator in a dbt model select statement.

sql
with source_data as (
    select 10 as sales_jan, 15 as sales_feb
)
select
    sales_jan,
    sales_feb,
    sales_jan + sales_feb as total_sales
from source_data;
Output
sales_jan | sales_feb | total_sales ----------+-----------+------------- 10 | 15 | 25
โš ๏ธ

Common Pitfalls

Common mistakes when using the + operator in dbt select statements include:

  • Trying to concatenate strings with + in databases that do not support it (like PostgreSQL). Use || instead.
  • Adding columns with NULL values without handling NULLs, which results in NULL output.
  • Mixing data types without casting, causing errors.
sql
/* Wrong: string concatenation in PostgreSQL */
select 'Hello' + 'World' as greeting;  -- This will error

/* Right: use || for string concatenation in PostgreSQL */
select 'Hello' || 'World' as greeting;
๐Ÿ“Š

Quick Reference

Use CaseOperatorNotes
Add numeric columns+Works in all SQL dialects supported by dbt
Concatenate strings (SQL Server)+Supported in SQL Server, not in PostgreSQL
Concatenate strings (PostgreSQL)||Use double pipe for string concatenation
Handle NULLs in additionCOALESCE(column, 0) + COALESCE(column2, 0)Avoids NULL results when adding
โœ…

Key Takeaways

Use the + operator in dbt select to add numeric columns directly.
String concatenation with + depends on your database; use || in PostgreSQL.
Handle NULL values to avoid unexpected NULL results in addition.
Always check your database's SQL dialect for operator support.
Casting may be needed when mixing data types with + operator.