Menu Close
v0.19.1 / Users-Guide / 12 Sql Parameters

SQL Parameters


Metabase has the flexible ability to allow variables in native (SQL) queries. This lets you dynamically replace values in your queries using filter widgets or through the query’s URL.

Variables

Options and settings for your variables will appear in the Variables side panel of the native query builder once you’ve defined a variable. So, how do you define a variable?

Variables

Defining Variables

Typing {{variable_name}} in your native query creates a variable called variable_name. Variables can be given types in the side panel, which changes their behavior. All variable types other than field filter will cause a filter widget to be placed on this question corresponding to the chosen variable type. When a value is selected via a filter widget, that value replaces the corresponding variable in the SQL template, wherever it appears.

This example defines a variable called cat, allowing you to dynamically change the WHERE clause in this query:

SELECT count(*)
FROM products
WHERE category = {{cat}}

The Field filter variable type

Giving a variable the Field filter type allows you to connect SQL cards to dashboard filter widgets. A field filter variable inserts SQL similar to that generated by the GUI query builder when adding filters on existing columns. This is useful because it lets you do things like insert dynamic date range filters into your native query. When adding a field filter, you should link that variable to a specific column. Field filter variables should be used inside of a WHERE clause.

Example:

SELECT count(*)
FROM products
WHERE {{created_at}}

Optional Clauses

To make an optional clause in your native query, type [[brackets around a {{variable}}]]. If variable is given a value, then the entire clause is placed into the template. If not, then the entire clause is ignored.

In this example, if no value is given to cat from its filter widget or URL, then the query will just select all the rows from the products table. But if cat does have a value, like Widget, then the query will only grab the products with a category type of Widget:

SELECT count(*)
FROM products
[[WHERE category = {{cat}}]]

To use multiple optional clauses you must include at least one regular WHERE clause followed by optional clauses, each starting with AND.

Example:

SELECT count(*)
FROM products
WHERE True
  [[AND id = {{id}}]]
  [[AND category = {{category}}]]

That’s it!

If you still have questions, or want to share Metabase tips and tricks, head over to our discussion board. See you there!