> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://help.sigmacomputing.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://help.sigmacomputing.com/_mcp/server.

# Write custom SQL

When you explore your data platform using the SQL editor, you can preview SQL queries and create workbooks, data models, and datasets directly from SQL.

This document describes how to do the following:

* [Create a workbook from SQL](#create-a-workbook-from-sql)
* [Create a SQL workbook element](#create-a-sql-workbook-element)
* [Reference existing Sigma workbook elements](#reference-existing-sigma-workbook-elements)
* Use [shortcuts](#shortcuts), including:
  * Toggle within SQL-based workbook data elements to an inline SQL editor with side-by-side display.
  * Auto-format your SQL query.
  * Use find and replace within your SQL query.

## Requirements

* To use this feature, you must be assigned an [account type](/docs/account-type-and-license-overview) with the **Write SQL** permission enabled.
* To run custom SQL, you must be granted **Can use** access for an entire connection. See [Manage access to data and connections](/docs/manage-data-permissions).
* The SQL editor only appears if you have connection-level access to at least one connection in your organization.

## Limitations and considerations

### Query limitations

* Sigma incorporates your custom SQL as a subquery inside a larger query with other workbook contents. Because of this, any SQL statement that cannot be performed in a subquery or CTE is not supported in Sigma's custom SQL editor, including:
  * Data Manipulation Language (DML) or Data Definition Language (DDL) statements.
  * Multiple queries in one custom SQL editor. This limitation applies to statements such as `SET` and `USE DATABASE` run before another query.
    * To store and use a variable in custom SQL, consider [referencing a workbook control value](/docs/reference-workbook-control-values-in-sql-statements).
    * To change the database or schema, consider using [dynamic schema selection](/docs/reference-workbook-control-values-in-sql-statements#return-rows-based-on-a-schema-text-selector) or explicitly stating database and schema in your query.
* Sigma does not support the use of ordinal positions to select columns from Sigma elements in custom SQL. For example, `SELECT $1 FROM sigma_element('table')` is not supported as syntax for referencing the first column in a table.

### Row and column order limitations

* Because Sigma incorporates your SQL query into an optimized query with other workbook contents, sort orders defined in your custom SQL cannot be guaranteed. To guarantee sort order for records in a custom SQL element, apply a sort from the table UI.
* Because users can change column order in both the table UI and the SELECT statement of a SQL query, Sigma stores the column order according to the first query run for each custom SQL element. This has the following consequences:
  * Changes to column order made in the table UI after the first run will be respected, but changes to column order made in the SELECT statement after the first run may not be.
  * To return columns in the order defined in the SELECT statement of your custom SQL query, create a new custom SQL element, copy your query into it, and run your query. This must be the first query run in that custom SQL element.

### Considerations

* Sigma converts all timestamps to your organization’s timezone. This has the following consequences:
  * If a column in your data platform has timezone data, Sigma converts the timestamp to your organization’s timezone while preserving the moment in time. For example, a column stating the timestamp `2025-09-10 10:00:00.000` for the `America/New_York` timezone is converted to `2025-09-10 07:00:00.000` if your Sigma organization has the `America/Los_Angeles` timezone.
  * If a column in your data platform has no timezone, Sigma interprets it as if it is in your organization’s timezone, but does not convert the timestamp. For more details on timezone handling, see [How Sigma displays date data](/docs/account-time-zone#how-sigma-displays-date-data).

## Create a workbook from SQL

To create a workbook from a SQL query, do the following:

1. Open **Sigma Home**.

2. In the navigation panel, click <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/button-add.svg" alt="" /> **Create New**, then select **Write SQL** to open the SQL editor.

   ![Create New menu open and displaying the following options shown are Workbook, Dataset, Data Model, Write SQL, and Upload CSV.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/05c40b125b9986f0de108bca598fa3e3aed5ac0e47662a50fb7479e1e4d84805/assets/docs-images/012c84e6e4c0d1dc1ea78ae375c0eb9f3019feddc58c57d4e6de7a49dd835548-sql-create-new.png)

3. In the side panel, click **Select a Connection** and select the connection you want to query.

4. In the query editor, enter your SQL query. Sigma provides autocomplete suggestions to guide you.

   ![SQL panel in a workbook with SQL syntax of select \* from EXAMPLES., with an autocomplete dropdown suggesting multiple available schemas such as BITCOIN, BIKES, CENSUS, and more.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/46fc330a9d57efe8fbc666d3e38b1e0fd7c623485ee3e1bcddb8d6b9b91dc0b6/assets/docs-images/771da6b1a1c971c1a9a8e7934cdb2943f6ac7965c03df86096a6b03f26da7ece-sql-better-exploration.png)

   You can reference workbook controls in your SQL by wrapping the control ID in curly brackets. See [Reference workbook controls](/docs/reference-workbook-control-values-in-sql-statements).

5. To run your SQL query, click **Run**, or use the keyboard shortcuts `⌘` + `return` on a Mac or `ctrl` + `enter` on a PC.

6. To save your unpublished workbook (exploration) as a workbook, click **Save As**.

To convert your SQL query to a data model, select <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/more.svg" alt="" /> **More** to open the element menu, then select **Advanced options** > **Create data model**.

## Create a SQL workbook element

To add a SQL element to an existing workbook and supplement existing analysis, do the following:

1. Open a workbook for editing.

2. In the add element bar, select the type of element you want to add, then choose a specific element type: **Data** > **Table**, **Data** > **Pivot Table** or **Chart** and any supported chart type.

3. In the **Select source** modal, choose the **SQL** option at the bottom.

   ![Select source popover modal showing the Sigma Sample Database selected in the Tables and Datasets tab, with four options at the bottom for CSV, SQL, Join, and Union.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/6ada54bbef54c4c4218d92b8686bb3ec2ff20a483bf9bc7195fe5db536423671/assets/docs-images/eaa2b6d9b9907a45801a87a2faeece3e576f135fdea3cb9814076115a9eda805-sql-source-pick.png)

4. Select the connection you want to query.

   An element appears in your workbook, prompting you to enter a SELECT statement to query the connection.

5. In the query editor, enter your custom SQL. Sigma provides autocomplete suggestions to guide you.

   ![SQL element in a workbook with SQL syntax of select \* from EXAMPLES., with an autocomplete dropdown suggesting multiple available schemas such as BITCOIN, BIKES, CENSUS, and more.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/022981f84e6e7b092021efb86038d3d6c6f5e46cba8edf93dc92a2dc23fc4c7d/assets/docs-images/8042db867cdd5489a2b8a5d29ce7cc49a37dc71b82018f4698b3cab45659080a-sql-autocomplete.png)

   You can reference workbook controls in your SQL by wrapping the control ID in curly brackets. See [Reference workbook controls](/docs/reference-workbook-control-values-in-sql-statements).

## Reference column identifiers

The syntax used to reference column identifiers in your SQL query depends on the data you are querying.

When querying a table in your data platform, you can reference the column name directly if it contains no spaces or special characters. For example:

```sql
SELECT QUANTITY FROM EXAMPLES.PLUGS_ELECTRONICS.PLUGS_ELECTRONICS_HANDS_ON_LAB_DATA
```

When querying a table in your data platform, use single quotes if the column name contains spaces or special characters. For example:

```sql
SELECT 'Customer Name' FROM EXAMPLES.PLUGS_ELECTRONICS.PLUGS_ELECTRONICS_HANDS_ON_LAB_DATA
```

When querying a data element in the same workbook, use double quotes to reference column identifiers. For example:

```sql
SELECT "Customer Name" FROM sigma_element('PLUGS_ELECTRONICS_HANDS_ON_LAB_DATA')
```

## Reference existing Sigma workbook elements

To reference other data elements in your workbook in your SQL query, including other custom SQL elements, use the `sigma_element()` syntax.

For example, to query a data element in your workbook titled *Fiscal Year Forecast* and filter based on the values of the *Revenue* column in the element, write a SQL statement like the following:

```sql
SELECT * FROM sigma_element('Fiscal Year Forecast')
   WHERE "Revenue" > 100000
```

### Syntax and usage notes

Use the following syntax to reference a data element in the same workbook:

```
sigma_element('Element title')
```

When using this syntax, consider the following usage notes:

* You must use the exact element title in your SQL statement.
* The element title that you reference must be a string.
* Column names must be identifiers. See [Reference column identifiers](#reference-column-identifiers)

### Limitations

* Using this syntax with AzureSQL connections is not yet supported.
* You cannot materialize an element that uses this syntax, including the output of a join with an element that uses this syntax.
* If you reference a grouped table with this syntax, you cannot specify the grouping level that you reference. This syntax returns all source columns, with any grouped calculations performed on the base table instead of for each grouping level.

If you reference a column restricted by a column-level security (CLS) rule in a SQL statement, the CLS is ignored and the column is no longer restricted. For details, see [Configure column-level security](/docs/column-level-security).

## Reference user attributes with system functions

You can use system functions with the `#formula` directive in custom SQL to return context-sensitive information about the current user or session. For a list of system functions you can use, see [System functions](/docs/system-functions).

### Syntax and usage notes

`{{#formula SystemFunction()}}`

When using this syntax, consider the following usage notes:

* System functions in custom SQL are equivalent to system functions referenced in the formula bar (ie. `{{#formula CurrentUserFullName()}}` is equivalent to `CurrentUserFullName()`)
* When using the functions [CurrentUserAttributeText](/docs/currentuserattributetext) and [CurrentUserInTeam](/docs/currentuserinteam), you must use the exact attribute or team name as it appears in the admin panel. For more details, see [Configure user attributes](/docs/user-attributes) and [Configure row-level security by team](/docs/set-up-row-level-security#configure-row-level-security-by-team).
* You can use system functions, like [CurrentUserAttributeText](/docs/currentuserattributetext) with the `#identifier` directive to select a database or schema in a query based on the user attribute value. For more details, see [Return rows based on a schema text selector](/docs/reference-workbook-control-values-in-sql-statements#return-rows-based-on-a-schema-text-selector)

### Examples

To return the email address of the current user:

```sql
SELECT {{#formula CurrentUserEmail()}}
```

To return the current user's full name:

```sql
SELECT {{#formula CurrentUserFullName()}}
```

## Shortcuts

Some shortcuts exist to make working with SQL in Sigma easier.

### Toggle SQL editor in the element menu

When a workbook is published, the SQL element displays only the results. When you edit or explore the workbook, you can toggle the SQL editor to show the SQL query that generates the results.

Click <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/sql-editor.svg" alt="" /> **Toggle SQL Editor** to switch back and forth between the data element and the SQL query editor.

### Maximize the SQL element

To maximize the SQL element in your workbook canvas and make it easier to write a long complex SQL query, press the space bar or click <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/maximize.svg" alt="" /> **Maximize element** to expand the element to full screen mode.

### Format SQL

To quickly format long blocks of SQL text, click <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/text-align_left.svg" alt="" /> **Format SQL**.

![](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/bfb3b6cedc09af4a5da97593d74673b8260b6de8b385564203fc386481c92676/assets/docs-images/77596fe-formatsql.gif)

### Find and replace

To search within your SQL query, and optionally replace instances of the searched term, click <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/search.svg" alt="" /> **Search SQL** or use the keyboard shortcut `⌘ + F`.

![SQL editor with find and replace option open, searching for the word Cost in a SQL query and replacing it with the word Price.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/3b7c8bd9d26b7bb0b4e1349636dd631a596e5f163032bf206cbd159e007f0d52/assets/docs-images/020b488-Screenshot_2024-05-15_at_3.35.57_PM.png)

### Access custom SQL from the lineage view

View and edit custom SQL from the lineage view of a workbook or data model. Copy the full query to your clipboard or click **Edit SQL** to go to the inline SQL editor for the element.

![Lineage view for a workbook showing two elements for custom SQL, the SQL query itself and the custom SQL element on the workbook canvas. The SQL query is selected and the details pane shows the SQL query, querying the EXAMPLES.BIKES.STATION table and limiting to 5 results.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/87c349317ea8beedf25f6c9d804c676114efc0831e5143224b18c50667655368/assets/docs-images/c5ab9c054a92da392aaa2554814f02e4b971ea3b16ef77665031ed5f2565c281-sql-lineage.png)

For more details about working with lineage, see [View workbook and data model data lineage](/docs/workbook-data-lineage).

### View the query history

When you use the SQL editor, you can access the history of the queries recently run against the current connection.

![Connection panel open with the History tab selected, showing 2 recent queries, both SELECT from EXAMPLES.SF\_RESTAURANTS... queries, with the specific timestamps for each query.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/a77927716240ee8001a77f8f8f10355bdcc7e313a0cf5b14916a6e0174094812/assets/docs-images/fe62cf3964dcfcaf8dea2f3a7fc27ff8aedb4e553c59df3647a35be57860ebd3-sql-qh.png)

To access this history, click the **DB** tab in the side panel, then select the **History** tab.

To see the query history for all elements in a specific workbook or data model, see [Examine workbook queries](/docs/examine-workbook-queries).

### View table previews

When writing your query, you can use the side panel to explore tables in your data platform. You can navigate to a specific table and select **Preview** to open a preview of the columns and rows in the table, helping you decide whether to add that table to your existing SQL query.

For a given table, select <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/more.svg" alt="" /> **More** and choose **Place name in SQL** or **Place select statement in SQL** to easily reference a new table in your SQL query.

## Examples

For more advanced custom SQL cases, refer to these examples.

### Change output based on a user attribute

If you have user attributes defined in your organization, you can reference an attribute to limit the results returned from a SQL query based on the value of the user attribute for the current user.

For example, for the example Plugs Electronics data, return results only with the store region that the current user can access based on the `store_region` user attribute assigned to them:

```sql
SELECT
  *
FROM
  EXAMPLES.PLUGS_ELECTRONICS.PLUGS_ELECTRONICS_HANDS_ON_LAB_DATA
WHERE 
  {{system::CurrentUserAttributeText::store_region}} = STORE_REGION
```

As another example, return results filtered by the `customer_name` that the current user has access to view, based on the value of the `organization_name` user attribute assigned to them:

```sql
SELECT 
  * 
FROM 
  test.orders 
WHERE 
  customer_name = {{system::CurrentUserAttributeText::organization_name}}
```

For more details about the function syntax, see [CurrentUserAttributeText](/docs/currentuserattributetext). For more details about user attributes and assignment, see [User Attributes](/docs/user-attributes).

### Return output for a specific date range control

For an example returning rows only when a date column matches the value specified in a date range control, refer to the example SQL in [Reference workbook control values in SQL statements](/docs/reference-workbook-control-values-in-sql-statements#reference-range-or-slider-control-values-in-sql).

### Return rows depending on the value of a multi-select control

For an example returning rows depending on the value of a multi-select list control, refer to the example SQL in [Reference workbook control values in SQL statements](/docs/reference-workbook-control-values-in-sql-statements#reference-multiple-values-from-a-multi-select-list-in-sql).

## Update custom SQL

If you need to make changes to a SQL statement, such as to update the referenced data source in a SQL statement, do the following:

1. Open the document for editing.
2. Click **Lineage** (<img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/lineage.svg" alt="" />), then search for **SQL**.

   ![Search bar in the lineage view with the search term SQL, showing 4 results, 2 tables called Custom SQL and 2 custom SQL elements directly.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/796fb9030e1f28f48cf17c7ec64fc9e88c9b528ebbfcd28730f81e6fe5d23ac6/assets/docs-images/ecf8cb0a91ddea75a9079afbd91119f57246b8a673a234e4db338910f5695f83-search-sql-lineage.png)
3. For each **Custom SQL** <img src="https://sigma-docs-screenshots.s3.us-west-2.amazonaws.com/Icons/sql-editor.svg" alt="" /> element in your document, select the custom SQL element and review the SQL query.

   ![After selecting the custom SQL element in the lineage view, review the summary of the connection and the SQL query itself, with options to copy query, focus the element in lineage, or edit the SQL.](https://files.buildwithfern.com/sigma.docs.buildwithfern.com/f12c4a884fa5a5fbd21abb0fc3e93a607311f88c567017d22b8a67874229d7d1/assets/docs-images/07da3dd46aafd8e748d48ba0d5b470645dbe3ca73af41aaeab29a0ca7b0ac244-custom-sql-lineage.png)
4. If the SQL query contains a data source that needs to be updated, click **Edit SQL** to open the element for editing in the canvas, then make your desired changes.

   If the SQL statement is more than a few lines, copy the SQL from the custom SQL element and paste it into a plain text editor, then make the desired changes in your plain text editor, then copy and paste them into the custom SQL element.
5. Run the SQL and validate that your SQL returns the expected results. For example, confirm that the correct data source is queried.
6. Publish the document.