Overview of ShopifyQL syntax
You can use ShopifyQL query syntax to retrieve and shape the data in your store's reports. A query is a question that you ask your data. FROM selects the dataset, SHOW selects the data to return, and the other keywords add filters, groupings, date ranges, comparisons, and visualizations.
ShopifyQL syntax can be used for any of the following purposes:
- Creating or modifying reports using the query editor.
- Creating or modifying customer segments using the segment editor.
- Developing apps with ShopifyQL through the GraphQL Admin API.
On this page
Glossary of terms
| Term | Definition |
|---|---|
| Dimension | An attribute that segments data so that it can be sorted and presented more clearly. Common examples of dimensions include time, products, and places. Dimensions are used as parameters in ShopifyQL. |
| Keyword | ShopifyQL syntax that acts as a command to direct your query. |
| Metric | A quantitative measurement of data. Common examples of metrics include total sales, number of orders, and gross profit. |
| Parameter | ShopifyQL syntax that identifies the database elements or details to be included in your query. |
| Operator | A reserved word or character that's used as part of a query. Examples include STARTS WITH, >= or last_week. |
ShopifyQL syntax rules
You must meet the following requirements when crafting a valid report query using ShopifyQL:
- You can place an entire query on one line, or on separate lines.
- You must include at least the
FROMandSHOWkeywords, with their appropriate parameters. All other keywords and parameters are optional. - All keywords in a query must be included in the following order:
FROMSHOWWHEREGROUP BYTIMESERIESWITHTOTALS,GROUP_TOTALS,PERCENT_CHANGE,CUMULATIVE_VALUES,CURRENCY,TIMEZONEHAVINGSINCEandUNTIL, orDURINGCOMPARE TOand optionalUNTILORDER BYLIMITVISUALIZEandTYPE,MAX,ANNOTATE
This is an example of ShopifyQL, written out as a query using the correct syntax. The parameters are included using generic placeholders, and optional parameters are in brackets:
FROM table_name1, table_name2, ...
SHOW column1 { AS alias }, column2 { AS alias }, ...
WHERE condition
GROUP BY dimension
TIMESERIES time_dimension WITH TOTALS, GROUP_TOTALS, PERCENT_CHANGE, CUMULATIVE_VALUES, CURRENCY 'currency_code', TIMEZONE 'iana_timezone'
HAVING condition
SINCE date_offset
UNTIL date_offset
DURING named_date_range
COMPARE TO [ date_offset { UNTIL date_offset }, ... | TARGETS ]
ORDER BY column { ASC | DESC }
LIMIT number { OFFSET number }
VISUALIZE [ alias1, alias2, ... ]
TYPE { visualization_type }
MAX number
ANNOTATE annotation_category { FILTER annotation_filter }The WITH keyword modifies the keyword that it follows, so it's written at the end of the GROUP BY or TIMESERIES statement that it applies to, such as TIMESERIES day WITH TOTALS.
ShopifyQL keywords
ShopifyQL queries can range from basic, for high-level data insights, to comprehensive, for detailed insights. Each keyword has a specific function that builds out your query.
| Keyword | Description |
|---|---|
FROM | Specifies which dataset table to select data from. |
SHOW | Selects the columns you want to extract from the dataset table. |
WHERE | Defines the condition or conditions that rows must satisfy to be selected. |
GROUP BY | Groups the extracted data by a dimension or time dimensions. |
TIMESERIES | Distinguishes grouping by time dimensions and backfills dates in a query. |
WITH | Modifies the behavior of certain ShopifyQL keywords. |
HAVING | Filters the results of a query after they've been grouped. |
SINCE | Includes data from a specified time in the past. Often paired with UNTIL. |
UNTIL | Includes data until a specified time in the past. Often paired with SINCE or COMPARE TO. |
DURING | Includes data during a specified time in the past. |
COMPARE TO | Includes data for comparison to a specified time in the past. |
ORDER BY | Specifies which column to order the data by. |
LIMIT | Limits the number of rows of data that are displayed. |
VISUALIZE | Displays your data in a visualization. You can specify which visualization you want with TYPE, such as line, bar, donut, or histogram. |
ANNOTATE | Displays annotations on a visualization that has a time axis. |
AS | An optional keyword that renames a column to a name of your choosing. |
FROM and SHOW
Creating the simplest ShopifyQL query only requires 2 keywords: FROM and SHOW, written in that order. FROM, followed by one or more table name parameters specifies which tables you want to query. SHOW, followed by any number of column name parameters specifies the columns you want to select.
SHOW can be used to specify the order in which metrics and dimensions are returned in the report.
For example, you can return the sum of total sales by writing this query:
FROM sales
SHOW total_salesRefer to the Shopify Developer Documentation for a list of available datasets.
WHERE
The WHERE keyword allows you to apply a dimensional filter to an entire ShopifyQL query. The filter can be modified by both comparison operators (such as greater than >), logical operators (such as AND or NOT), and partial string and array matching (such as STARTS WITH and CONTAINS).
Use WHERE when you want to focus on a specific segment, such as orders from a single country, sales of a particular product, or transactions above a certain value.
WHERE conditions must meet the following requirements:
- Values must be wrapped in single quotes ('), not double quotes (").
- Conditions can't contain any arithmetic.
- Conditions can only reference a dimension, not a metric.
For example, to return total sales filtered based on billing country, your query is:
FROM sales
SHOW total_sales, product_title, product_type, product_vendor
WHERE billing_country='Canada'
GROUP BY product_title, product_type, product_vendorAs in the previous example, you can filter the result set with the WHERE parameter even when that parameter isn't included in the SHOW keyword. In this case, total sales is filtered for orders from Canada only, even though billing_country isn't included in the result set.
Comparison operators
The WHERE keyword uses comparison operators to filter data. In the previous example, = was used to specify that the query filters on a specific value, however, there are other operators available to you:
| Comparison operator | Description |
|---|---|
| = | equal to |
| != | not equal to |
| < | less than |
| > | greater than |
| <= | less than or equal to |
| >= | greater than or equal to |
Logical operators
To further filter your data, you can add logical operators to your query. The ShopifyQL logical operators are:
| Logical operator | Description |
|---|---|
AND | Filter to include all rows where the conditions separated by AND are satisfied. |
OR | Filter to include all rows where either of the conditions separated by OR are satisfied. |
NOT | Filter to only include rows where the conditions aren't satisfied, such as rows that don't contain the specified value. |
You can use multiple filters with the WHERE keyword by adding logical operators.
Adding to the example dataset query, to get a monthly grouping of net sales for all orders with dried peaches where the billing address was in Canada and there was a discount applied, the query is:
FROM sales
SHOW total_sales, product_title, product_type, product_vendor
WHERE billing_country = 'Canada' AND product_title = 'Dried Peaches' AND is_discounted_sale = true
GROUP BY product_title, product_type, product_vendorAND is evaluated before OR. To control the order of evaluation, group your conditions with parentheses, such as WHERE billing_country = 'Canada' AND (product_type = 'Fruit' OR product_type = 'Nuts').
Range and membership operators
You can match a dimension against a list of values, or test whether a value falls inside a range:
| Operator | Description |
|---|---|
IN | Match any value in a list, such as WHERE billing_country IN ('Canada', 'United States'). |
NOT IN | Exclude every value in a list. |
BETWEEN | Match values inside a range, such as WHERE number_of_products_bought_together BETWEEN 2 AND 4. Both the low value and the high value are included. |
NOT BETWEEN | Exclude values inside a range. Both the low value and the high value are excluded. |
Null and boolean checks
You can filter for missing values, or for boolean states, without comparing a dimension to a value. Add NOT after IS to invert any of these checks:
| Operator | Description |
|---|---|
IS NULL | The value is missing. Works with any dimension that accepts missing values. |
IS TRUE | The value is true. Works with boolean dimensions. |
IS FALSE | The value is false. Works with boolean dimensions. |
An inverted boolean check also matches rows where the value is missing. For example, an inverted true check matches both the rows where the value is false and the rows where the value is missing. The inverted null check is the exception, because it selects only the rows where a value exists:
FROM sales
SHOW total_sales
WHERE product_type IS NOT NULL AND is_discounted_sale IS NOT TRUE
GROUP BY product_typeExcluding values with !=, NOT IN, or NOT CONTAINS doesn't remove rows where the dimension is missing. To drop those rows as well, add a not-null check for the same dimension:
FROM sales
SHOW total_sales
WHERE product_type != 'Fruit' AND product_type IS NOT NULL
GROUP BY product_typeCustomer event functions
To further filter your data, you can add conditional customer event functions to your query. Functions names are followed by either MATCHES or NOT MATCHES and parentheses enclosing the list of optional parameters.
You can add the following ShopifyQL customer event functions to your queries:
| Customer event operator | Description |
|---|---|
{customer_event} MATCHES ({condition1}, {condition2}, ...) | Filter to include all rows where the customer event conditions defined in the parentheses are satisfied. |
{customer_event} NOT MATCHES ({condition1}, {condition2}, ...) | Filter to only include rows where the customer event conditions aren't satisfied. |
For example, the following query displays only customers that have placed 5 orders or more:
FROM customers
SHOW customer_name, total_number_of_orders
WHERE orders_placed MATCHES (count >= 5)
GROUP BY customer_nameThe conditions inside the parentheses must reflect the available parameters that belong to the associated customer event. You can use the following default customer event fields and associated parameters in a WHERE statement:
| Events | Parameters |
|---|---|
products_purchased |
|
orders_placed |
|
shopify_email.opened |
|
shopify_email.clicked |
|
shopify_email.bounced |
|
shopify_email.marked_as_spam |
|
shopify_email.unsubscribed |
|
storefront_event.product_viewed |
|
storefront_event.collection_viewed |
|
store_credit_accounts |
|
within_distance |
|
For date parameters in customer event functions, you can use relative dates, such as date = today, date = -30d, and date = -6m.
When the FROM dataset is something other than customers, you must precede the matchable field with customer. in order to access the customer dataset in your query. For example, customer.products_purchased.
For example, this query displays total sales only from customers that purchased 3 or more skincare products in a single order in the past 30 days:
FROM sales
SHOW total_sales
WHERE customer.products_purchased MATCHES (tag CONTAINS 'skincare', quantity >= 3)
GROUP BY month
SINCE -30dAn additional anniversary customer event function is available that doesn't require a MATCHES operator. The anniversary function is available for customer dimensions that have date or time outputs, such as customer_added_date or first_order_date, and any time or date-related metafields, such as metafields.facts.birth_date or metafields.custom.preferred_delivery_date.
For example, this statement displays only results where the customer added date has an anniversary of today: WHERE anniversary(customer_added_date) = today. For another example, this statement displays only results where the customer's birthday (stored as a metafield) is happening at some time this week: WHERE anniversary(metafields.facts.birth_date) BETWEEN today AND +7d.
GROUP BY
To segment a metric by a dimension, such as group sales by region, use the GROUP BY keyword. The GROUP BY keyword can be paired with any dimension parameter.
GROUP BY is what transforms a single total into a breakdown. Without it, SHOW total_sales returns one number. With GROUP BY product_title, that same metric splits across every product, so that you can identify what's actually driving performance.
For example, a query that groups total sales by billing country and region is written as:
FROM sales
SHOW total_sales
GROUP BY billing_country, billing_regionHere is another example query that uses a time dimension to display total sales by month:
FROM sales
SHOW total_sales
GROUP BY monthThis query doesn't return any months where you have no sales. If you want a query that returns a complete, uninterrupted time period, then use the TIMESERIES keyword.
FROM sales
SHOW total_sales
TIMESERIES month
SINCE last_year UNTIL todayTime dimensions
These are the time dimensions that you can use to group your data:
| Operator | Description |
|---|---|
second | Grouping by second of hour. |
minute | Grouping by minute of hour. |
hour | Grouping by hour of calendar day. |
day | Grouping by calendar day. |
week | Grouping by calendar week. |
month | Grouping by calendar month. |
quarter | Grouping by calendar quarter. |
year | Grouping by calendar year. |
hour_of_day | Zero-based grouping by 24 hours (0, 1, ..., 23). |
day_of_week | Zero-based grouping by day of week, from 0 for Monday to 6 for Sunday. |
week_of_year | Grouping by week of year, from 1 to 52, or from 1 to 53 in years that have a 53rd week. |
month_of_year | Grouping by month of year (1, 2, ..., 12). |
TOP N
You can display a custom number of items in your report visualization with the TOP N parameter, where N is the number of items displayed. N must be a positive whole number.
As part of the query, you can include TOP and then the number of items, along with a categorical dimension, with multiple dimensions separated by a comma. Categorical dimensions are dimensions not associated with time, such as products, channels, or regions. Items not included in N are grouped as "Other" in the visualization and data table. Some visualization types, such as histogram or list, don't support grouping by TOP N parameters.
In this example, you're displaying the top 5 products for each day for the past 30 days, and the remaining items are grouped as "Other":
FROM sales
SHOW gross_sales
GROUP BY day, TOP 5 product_title WITH GROUP_TOTALS, TOTALS, CURRENCY 'USD'
TIMESERIES day
SINCE startOfDay(-30d) UNTIL today
ORDER BY day ASC, gross_sales DESC, product_title ASC
VISUALIZE gross_salesYou can include more than one TOP N parameter in a single GROUP BY statement.
Additional keywords can be added to the TOP N parameter to customize how the remainder items display, as well as the ranking system used:
ONLY TOP N: Displays only N number of items and hides the remaining items in the dataset from the visualization and data table, instead of grouping them as "Other".TOP N {dimension} OVERALL: Displays the top N number of items across the specified date range (the overall rank), grouped by the specified dimension.OVERALLhas no effect on the first dimension in aGROUP BYstatement. You can also include theONLYkeyword to hide the remaining items. The sort order for the dataset is still determined by theORDER BYkeyword.
In this example, you're displaying only the top 5 products for each day for the past 30 days, and the remaining items are hidden completely from the visualization and data table:
FROM sales
SHOW gross_sales
GROUP BY day, ONLY TOP 5 product_title WITH GROUP_TOTALS, TOTALS, CURRENCY 'USD'
TIMESERIES day
SINCE startOfDay(-30d) UNTIL today
ORDER BY day ASC, gross_sales DESC, product_title ASC
VISUALIZE gross_salesIn this example, you're displaying top 5 products in the past 30 days overall, grouped by day, and hiding the remaining items:
FROM sales
SHOW gross_sales
GROUP BY day, ONLY TOP 5 product_title OVERALL WITH GROUP_TOTALS, TOTALS, CURRENCY 'USD'
TIMESERIES day
SINCE startOfDay(-30d) UNTIL today
ORDER BY day ASC, gross_sales DESC, product_title ASC
VISUALIZE gross_salesSimilar to LIMIT, the TOP N parameter updates the number of items included in your data table as well as the visualization. To customize the number of items in your report visualization without impacting the data table, use the VISUALIZE {metric} MAX N parameter.
In this example, you're displaying the top 5 products for each day for the past 30 days, and the remaining items remain listed in the table:
FROM sales
SHOW gross_sales
GROUP BY day, product_title WITH GROUP_TOTALS, TOTALS, CURRENCY 'USD'
TIMESERIES day
SINCE startOfDay(-30d) UNTIL today
ORDER BY day ASC, gross_sales DESC, product_title ASC
VISUALIZE gross_sales MAX 5CLUSTER
You can use the CLUSTER modifier in a GROUP BY statement to group nearby addresses into geographic clusters. Clustered results can be displayed in a bubble map visualization, where each cluster is drawn as a bubble that's sized by your metric.
CLUSTER works with the shipping_address and billing_address dimensions, which are available in datasets such as sales and payments. These address dimensions can only be grouped with CLUSTER. If you group by shipping_address without it, then the query returns the error 'shipping_address' can only be grouped with CLUSTER.
Address dimensions aren't available in the filter panel. To filter by location in a query, use an address's coordinate fields in WHERE, such as shipping_address.latitude and shipping_address.longitude. A bubble map uses these fields to add the visible map area to the query.
In this example, you're displaying total sales for the past 30 days, grouped into clusters of nearby shipping addresses and displayed on a bubble map:
FROM sales
SHOW total_sales
GROUP BY CLUSTER shipping_address WITH TOTALS
SINCE -30d UNTIL today
VISUALIZE total_sales TYPE bubble_mapEach cluster includes a generated address count field, such as shipping_address__cluster.size, which is displayed in the data table as Shipping address count. The count is the number of distinct map locations in the cluster, so multiple addresses at the same location are counted as 1 address. You can reference the address count field in ORDER BY and HAVING. For example, to list the clusters with the most locations first, add ORDER BY shipping_address__cluster.size DESC to your query.
You can combine CLUSTER with TOP N to return only the largest clusters, such as GROUP BY ONLY TOP 10 CLUSTER shipping_address. If you use TOP N without ONLY, then the remaining clusters are combined into an Other row. The Other row is displayed in the data table only, because the clusters that it combines can be in different areas of the map.
A bubble map can also display other dimensions alongside the clustered address. A dimension that comes before CLUSTER in the GROUP BY statement draws each value in its own color, such as GROUP BY product_title, CLUSTER shipping_address. A dimension that comes after it returns a row for each value at each cluster, such as GROUP BY CLUSTER shipping_address, day. When a bubble map groups by another dimension, a bubble whose center is drawn inside a larger bubble at the current zoom level is merged into it. The larger bubble keeps its own value rather than a total, and its tooltip lists the rows that it includes. To draw 1 bubble for each cluster's total instead, add WITH GROUP_TOTALS, such as GROUP BY CLUSTER shipping_address, product_title WITH GROUP_TOTALS.
TIMESERIES
You can use the TIMESERIES keyword to group results by a time dimension, view metrics over time, and return the time periods that have no data as empty values.
In this example, you're backfilling missing total sales data in the last 15 days:
FROM sales
SHOW total_sales
GROUP BY product_title, billing_country
TIMESERIES day
SINCE -15dDefault date ranges for TIMESERIES
If your query includes TIMESERIES without SINCE or DURING, then a default start date is applied, based on the time dimension that you're grouping by. The range runs to the end of the current day unless you set an UNTIL value.
| Time dimension | Default start date |
|---|---|
second | startOfMinute(-1min) |
minute | startOfHour(-1h) |
hour | startOfHour(-24h) |
day | startOfDay(-30d) |
week | startOfWeek(-4w) |
month | startOfMonth(-3m) |
quarter | startOfQuarter(-4q) |
year | startOfYear(-3y) |
hour_of_day | startOfDay(-3d) |
day_of_week | startOfWeek(-4w) |
week_of_year | startOfYear(-1y) |
month_of_year | startOfYear(-1y) |
TIMESERIES and the order of columns
Depending on whether or not the TIMESERIES is given and present in either the GROUP BY or SHOW values, the order of columns can change.
TIMESERIES | SHOW | GROUP BY | Result |
|---|---|---|---|
| Given | Not present | Not present | The TIMESERIES is the first dimension. |
| Given | Not present | Present | Time dimensions position is defined by its position in GROUP BY. |
| Given | Present | Present | Time dimensions position is defined by its position in SHOW. |
| Not given | Not present | Present | Time dimensions position is defined by its position in GROUP BY. Data isn't backfilled. |
| Not given | Present | Present | Time dimensions position is defined by its position in SHOW. Data isn't backfilled. |
| Not given | Present | Not present | Triggers a syntax error because SHOW can only reference dimensions present in GROUP BY. |
HAVING
Similar to WHERE, you can use the HAVING keyword to filter the results of a query after they've been grouped. The filter can have one condition, but the condition can be modified by both comparison operators (such as greater than >) and logical operators (such as AND or NOT). Unlike the WHERE keyword, HAVING can reference aliases, aggregate functions, and grouping columns.
HAVING requires your query to include a GROUP BY or TIMESERIES clause because HAVING filters the results of a query after they've been grouped by GROUP BY or TIMESERIES.
In this example, you're filtering the total sales for each product that have total sales greater than 1000 and less than 5000:
FROM sales
SHOW total_sales
GROUP BY product_title
HAVING total_sales > 1000 AND total_sales < 5000Filtering with HAVING has a few limitations for accepted keywords: totals, group totals, comparisons, percent changes, and running totals aren't valid in a HAVING condition, and referencing one returns an error such as 'comparison_total_sales__previous_year' is not allowed in the HAVING clause. Attributed metrics are valid, such as total_sales__first_click when an attribution model is applied.
WITH
The WITH keyword modifies the behavior of certain other ShopifyQL keywords. You can use the following modifications:
TOTALS: Provides a top-level summary of metrics before they're broken down by any dimension.GROUP_TOTALS: Provides a total for all sub-groupings when there is a group by aggregation.PERCENT_CHANGE: Adds a percent change value to the summary row for each comparison metric inCOMPARE TO.CURRENCY: Displays the data in the selected currency.TIMEZONE: Calculates time-based results in the selected IANA timezone.- Any attribution model, such as
LAST_CLICK_ATTRIBUTION,FIRST_CLICK_ATTRIBUTION, orANY_CLICK_ATTRIBUTION: Applies marketing attribution models to sales metrics when they're broken down by a marketing dimension. Each attributed metric replaces the metric that it's based on. CUMULATIVE_VALUES: Displays the metric as a running total instead of as individual values for each time period.
TOTALS
The TOTALS modifier provides a top-level summary of metrics before they're broken down by any other dimension. When you use WITH TOTALS, the data table displays the totals in a summary row at the start of the results, labelled with the date range that the query covers.
Additive metrics, such as net_sales, are summed across the whole result set. Ratio and percentage metrics, such as average_order_value, are recalculated across the whole result set instead of being summed from the grouped rows.
For example, this query displays daily sales metrics with a summary row:
FROM sales
SHOW gross_sales, net_sales
TIMESERIES day WITH TOTALSThis query might return a report similar to this:
| Day | Gross sales | Net sales |
|---|---|---|
| Jan 1-3, 2024 | 6 | 15 |
| 2024-01-01 | 1 | 4 |
| 2024-01-02 | 2 | 5 |
| 2024-01-03 | 3 | 6 |
GROUP_TOTALS
The GROUP_TOTALS modifier calculates a subtotal for each group when a query groups by at least 2 dimensions. ShopifyQL calculates a subtotal for each set of grouped dimensions except the full set. Grouping by 2 dimensions produces 1 level of subtotals, and grouping by 3 dimensions produces 2 levels.
To display the subtotals, your query must also order by the dimensions that they're grouped under. Every grouped dimension except the last must be included in ORDER BY, or be the dimension in TIMESERIES. When your query meets that requirement, the data table groups the results and adds a Total row for each group. When it doesn't, the data table stays flat and the subtotals aren't displayed at all.
Each subtotal has a generated name, which combines the metric and the dimensions that it totals:
{metric_name}__{first_dimension}_totals, such astotal_sales__billing_country_totals{metric_name}_{first_dimension}{second_dimension}_totals, which is produced when a query groups by 3 dimensions
You can reference these names in ORDER BY and VISUALIZE, whether or not the subtotals are displayed.
On its own, GROUP_TOTALS leaves the summary row empty, because no overall total is calculated. When you want an overall summary row as well, pair GROUP_TOTALS with TOTALS.
For example, this query displays total sales for each billing country on each day, with a subtotal for each day. The query orders by day, which is the grouped dimension that the subtotals are calculated for, so the subtotals are displayed:
FROM sales
SHOW total_sales
GROUP BY day, billing_country WITH TOTALS, GROUP_TOTALS
SINCE -30d
ORDER BY day ASCThis query might return a report similar to this:
| Day | Billing country | Total sales |
|---|---|---|
| Jun 1-30, 2024 | - | 150 |
| Jun 1, 2024 | Total | 90 |
| Jun 1, 2024 | Canada | 50 |
| Jun 1, 2024 | United States | 40 |
| Jun 2, 2024 | Total | 60 |
| Jun 2, 2024 | Canada | 60 |
The first row is the summary row that TOTALS adds. Each Total row is a subtotal for the day whose rows it groups.
Because the query orders by day, the data table displays a Total row for each day.
PERCENT_CHANGE
The PERCENT_CHANGE modifier adds a percentage change value for each comparison metric when you use COMPARE TO. A percentage change is calculated for every row that has a comparison value, but the data table displays it only in the summary row, stacked with the values for the 2 periods that it compares. Include TOTALS when you want the percentage change displayed, because TOTALS is what adds the summary row.
When your reporting period includes the current date, each period is measured only up to the same point in its own time unit, so a partial current period is compared against an equal period to date. For example, on the 17th of a month, each comparison month is measured up to its own 17th.
Each percent change has a generated name, which combines the metric and the comparison period:
- A relative comparison, such as
COMPARE TO previous_year, addspercent_change_net_sales__previous_year. - A date function comparison, such as
COMPARE TO startOfQuarter(-3q), addspercent_change_total_sales__startOfQuarter_sub_3q, where each minus sign becomessub.
Without a date comparison, this modifier doesn't add any percent change columns.
The formula used for calculating percentage change is: (base_column - comparison_column) * 100 / abs(comparison_column). A positive value means that the base period is higher than the comparison period, and a negative value means that the base period is lower than the comparison period.
For example, this query uses SINCE and COMPARE TO to compare the net sales per day in the previous calendar month to the same month in the previous year, with a percentage change in the summary row:
FROM sales
SHOW net_sales
TIMESERIES day WITH TOTALS, PERCENT_CHANGE
SINCE startOfMonth(-1m) UNTIL endOfMonth(-1m)
COMPARE TO previous_yearThe report displays a day column and a net sales column. Each cell stacks the reporting-period value with the comparison-period value, and the summary row includes the percentage change.
CURRENCY
The CURRENCY modifier displays the data in the report in the selected currency. Units of currency must be enclosed in single quotation marks, and must use the associated 3-letter currency code.
For example, this query uses CURRENCY to display net sales data in Canadian dollars (CAD).
FROM sales
SHOW net_sales
TIMESERIES day WITH CURRENCY 'CAD'TIMEZONE
The TIMEZONE modifier calculates the time-based results in your report in the selected timezone, which includes the boundaries that date functions resolve to. Timezones must be enclosed in single quotation marks, and must use a valid Internet Assigned Numbers Authority (IANA) timezone name, such as EST, UTC, or Europe/Paris.
For example, this query uses TIMEZONE to resolve each day boundary in the America/New_York timezone, so that sales near the start or the end of a day fall into the expected day.
FROM sales
SHOW net_sales
TIMESERIES day WITH TIMEZONE 'America/New_York'
SINCE startOfMonth(-1m) UNTIL endOfMonth(-1m)Attribution models
You can add any available attribution model as a modifier to display your sales metrics with standard marketing attribution. This option is available only when both a sales metric and a marketing dimension are used, and affects only sales metrics. When these conditions are met, and no attribution model is selected, reports default to LAST_CLICK_ATTRIBUTION.
When you apply an attribution model, each eligible sales metric is replaced by an attributed version of itself. Attribution is the one WITH modifier that changes the columns in your data table. The new column name combines the metric name and the suffix for the model, and the column heading names the model, such as Total sales (last click). If the metric is renamed with AS, then the alias is used in the column name instead of the metric name.
Because the metric is replaced, the original metric name is no longer valid in the rest of the query. For example, referencing the original metric in ORDER BY, VISUALIZE, or HAVING returns an error such as 'total_sales' is not allowed when applying attribution. Use: 'total_sales__last_click'. Use the attributed name in those keywords instead.
| Attribution model | Column suffix | Example column for total_sales |
|---|---|---|
FIRST_CLICK_ATTRIBUTION | __first_click | total_sales__first_click |
LAST_CLICK_ATTRIBUTION | __last_click | total_sales__last_click |
LAST_NON_DIRECT_CLICK_ATTRIBUTION | __last_non_direct_click | total_sales__last_non_direct_click |
ANY_CLICK_ATTRIBUTION | __any_click | total_sales__any_click |
LINEAR_ATTRIBUTION | __linear | total_sales__linear |
You can include more than one attribution model in the same WITH clause to compare models side by side. ANY_CLICK_ATTRIBUTION gives full credit to every touchpoint, so its attributed totals can add up to more than the overall value of the metric.
For example, this query uses LAST_CLICK_ATTRIBUTION to display total sales by referring channel attributed to the last click, displaying a Total sales (last click) column:
FROM sales
SHOW total_sales
GROUP BY ONLY TOP 5 referring_channel WITH TOTALS, LAST_CLICK_ATTRIBUTION
SINCE startOfDay(-30d) UNTIL today
ORDER BY total_sales__last_click DESC
VISUALIZE total_sales__last_clickLearn more about attribution models in reports.
CUMULATIVE_VALUES
When you display a metric over time, you can choose to display the metric as a running total instead of as individual values for each time period. This is called the cumulative view, and it makes it easier to track overall progress across a date range, such as how sales are building toward a monthly goal.
To represent this cumulative view in ShopifyQL, add CUMULATIVE_VALUES to your WITH clause. Additionally, your ShopifyQL query must include a time dimension in the TIMESERIES or GROUP BY statements.
For example:
FROM sales
SHOW total_sales
GROUP BY product_title, billing_country
TIMESERIES day WITH TOTALS, CUMULATIVE_VALUESEach running total has a generated name, {metric_name}__cumulative, such as net_sales__cumulative, which you can reference in ORDER BY and VISUALIZE. Metrics where summing values across time isn't meaningful, such as average_order_value or conversion_rate, don't produce a running total.
Learn more about including cumulative values in visualizations.
SINCE and UNTIL
To filter your query by a date or some time period, use the SINCE and UNTIL keywords and their associated parameters. These keywords are unique because they only filter time periods. Both boundaries are inclusive.
For example, this is a query to find net sales over the last 12 months, in Canada, ending with yesterday:
FROM sales
SHOW net_sales
WHERE billing_country = 'Canada'
GROUP BY month
SINCE -12m UNTIL yesterdayIf you use SINCE and don't define an UNTIL value, then your time range runs to the end of the current day, which is the same result as UNTIL today. To end the range at the moment that the query runs instead, use UNTIL now. If you use UNTIL without SINCE, then your query must include TIMESERIES, which supplies a default start date. Otherwise the query returns the error UNTIL requires SINCE without TIMESERIES present.
Offset operators
You can filter by specific dates, or by date and time offsets. The ShopifyQL offset operators are:
| Offset operator | Description |
|---|---|
-{#}s | Number of seconds ago from the date and time that the query is run. |
-{#}min | Number of minutes ago from the date and time that the query is run. |
-{#}h | Number of hours ago from the date and time that the query is run. |
-{#}d | Number of days ago from the date and time that the query is run. |
-{#}w | Number of weeks ago from the date and time that the query is run. |
-{#}m | Number of months ago from the date and time that the query is run. |
-{#}q | Number of quarters ago from the date and time that the query is run. |
-{#}y | Number of years ago from the date and time that the query is run. |
yyyy-MM-dd | A specific date. |
yyyy-MM-ddThh:mm:ss | A specific date and time. |
The minus sign marks a time in the past. An offset resolves to a point in time measured from when the query runs, rather than to a calendar boundary. For example, if you run SINCE -1m on March 15, then your range starts on February 15, not on February 1. An offset written without a minus sign resolves to a time in the future, so -1m and 1m aren't equivalent.
For a range that starts or ends on a calendar boundary, use a date function, such as SINCE startOfMonth(-1m) UNTIL endOfMonth(-1m) for the previous calendar month, or SINCE startOfMonth(0m) for the first day of the current month.
The time of day that an offset resolves to depends on its unit. Second, minute, and hour offsets keep the time of day from when the query runs. Day, week, month, quarter, and year offsets resolve to midnight, so UNTIL -0m ends your range at the start of the current day instead of at the current time. To end your range at the moment that the query runs, use UNTIL now. To cover the whole of the current day, omit UNTIL.
Date functions
You can use the following functions combined with any date range operators (with the exception of specific dates) in SINCE and UNTIL statements. The "startOf..." functions truncate to the start of the associated time unit (minute, hour, day, week, month, quarter, and year) when used with SINCE, and the "endOf..." functions truncate to the end of the associated time unit when used with UNTIL.
Date function units and operator units must match in order to return a valid result. For example, startOfMonth(-1m) is correct, but startOfMonth(-1d) isn't valid.
| Date function | Description |
|---|---|
now | The date and time when the query is run. |
startOfMinute(-{#}min) | Truncates the date range operator to the beginning of the target minute. |
endOfMinute(-{#}min) | Truncates the date range operator to the end of the target minute. |
startOfHour(-{#}h) | Truncates the date range operator to the beginning of the target hour. |
endOfHour(-{#}h) | Truncates the date range operator to the end of the target hour. |
startOfDay(-{#}d) | Truncates the date range operator to the beginning of the target day. |
endOfDay(-{#}d) | Truncates the date range operator to the end of the target day. |
startOfWeek(-{#}w) | Truncates the date range operator to the beginning of the target week. |
endOfWeek(-{#}w) | Truncates the date range operator to the end of the target week. |
startOfMonth(-{#}m) | Truncates the date range operator to the beginning of the target month. |
endOfMonth(-{#}m) | Truncates the date range operator to the end of the target month. |
startOfQuarter(-{#}q) | Truncates the date range operator to the beginning of the target quarter. |
endOfQuarter(-{#}q) | Truncates the date range operator to the end of the target quarter. |
startOfYear(-{#}y) | Truncates the date range operator to the beginning of the target year. |
endOfYear(-{#}y) | Truncates the date range operator to the end of the target year. |
For example, if today is November 8, 2022, then you can use the following query to return the gross sales from January 1, 2020 to October 31, 2022:
FROM sales
SHOW gross_sales
SINCE startOfYear(-2y) UNTIL endOfMonth(-1m)DURING
The DURING keyword simplifies date filtering for date ranges, and replaces the use of SINCE and UNTIL. Because DURING defines the full reporting period, don't combine it with SINCE or UNTIL in the same query.
You can use the DURING keyword to filter the query results for a known time period, such as a calendar year or specific month, or for date ranges that have different dates every year, such as Black Friday Cyber Monday (BFCM). DURING accepts named date range operators only, such as yesterday or last_year, and it doesn't accept now.
For example, this query filters by date for BFCM 2021:
FROM sales
SHOW total_sales
GROUP BY day
DURING bfcm2021If you need a specific date, a relative offset, or a date function as a boundary, then use SINCE and UNTIL.
Named date range operators
DURING accepts any of the following named date range operators:
| Named date range operator | Description |
|---|---|
today | The date when the query is run. |
yesterday | The previous calendar day. |
this_week | The current calendar week. |
this_month | The current calendar month. |
this_quarter | The current calendar quarter. |
this_year | The current calendar year. |
last_week | The previous calendar week. |
last_month | The previous calendar month. |
last_quarter | The previous calendar quarter. |
last_year | The previous calendar year. |
this_weekend | The current weekend. |
last_weekend | The previous weekend. |
bfcmYYYY | The Black Friday Cyber Monday range for the specified year. For example, bfcm2022 returns results for November 25-28, 2022. |
COMPARE TO
The COMPARE TO keyword compares the reporting period that you set with SINCE and UNTIL, or with DURING, against another period or against configured targets.
You can use the COMPARE TO keyword with the following types of parameters:
- Absolute dates, such as
2023-01-01: Includes the metrics for the specified period and the comparison metrics for the same period on the absolute date. - Named dates, such as
last_week: Includes the metrics for the specified period and the comparison metrics for the same period on the named date.- The operator used by
COMPARE TOdoesn't have to be the same length in time as the one used byDURING. If noUNTILvalue is provided, then it calculates the time range to be equal with the value specified inDURING. For example,DURING this_week COMPARE TO last_monthcompares this week's data to a one-week period that starts at the beginning of last month.
- The operator used by
- Offset dates, such as
-3q: Includes the metrics for the specified period and the comparison metrics for the same period on the relative date. - Multiple date comparisons, such as
-1y, -2y: Compare your data from a specific date range with multiple other date ranges. This can be useful when you want to track changes over several periods. - Configured targets, using
COMPARE TO TARGETS: Compare your data against the targets that you've set for a metric, rather than against another date range. This option is available for metrics that support targets. - If you use a date dimension in a query with
COMPARE TO, then useTIMESERIESfor it, rather thanGROUP BY.
The following example compares net sales during the previous calendar month to the same month in the previous year:
FROM sales
SHOW net_sales, product_title
GROUP BY product_title
TIMESERIES day
SINCE startOfMonth(-1m) UNTIL endOfMonth(-1m)
COMPARE TO previous_yearWhen you use COMPARE TO, each compared metric gains a comparison value. Comparison values aren't displayed in their own columns in the data table. Each cell of the data table stacks the reporting-period value with the comparison-period value, and each row label stacks the 2 periods in the same way. Each comparison has a generated name, which combines the metric and the comparison period, so one metric can carry more than one comparison. You can reference a comparison by name in ORDER BY or VISUALIZE:
- A relative comparison adds
comparison_net_sales__previous_year. - A specific date comparison adds
comparison_net_sales__20230101. - A named date comparison adds
comparison_net_sales__last_week. - A date function comparison adds
comparison_net_sales__startOfQuarter_sub_3q, where each minus sign becomessub.
Relative date range operators
Relative operators return the same length of time as the base date range, shifted back by the specified period. In addition to the named date range operators, COMPARE TO accepts the following relative operators:
| Relative date range operator | Description |
|---|---|
previous_period | One period before the base date range. |
previous_year | One year before the base date range. |
previous_quarter | One quarter before the base date range. |
previous_month | One month before the base date range. |
previous_week | One week before the base date range. |
previous_day | One day before the base date range. |
previous_hour | One hour before the base date range. |
previous_minute | One minute before the base date range. |
previous_second | One second before the base date range. |
previous_year_match_day_of_week | 52 weeks before the base date range, which keeps the comparison aligned to the same days of the week. |
Comparing to targets
COMPARE TO TARGETS requires TIMESERIES and a reporting period, which you set with SINCE, UNTIL, or DURING. You can't combine TARGETS with any other comparison period. Unlike a date comparison, targets don't add any values to your query results, so your data table is unchanged, and PERCENT_CHANGE has no effect. Your target is displayed on the visualization instead, as a pacing line in the cumulative view of a line or bar visualization.
To display your progress toward a target as a gauge, use VISUALIZE {metric} TYPE target_gauge. A target gauge doesn't require COMPARE TO TARGETS, but your query's date range must match the time period of a target that you've set. If no target matches the date range, then the visualization reports that no target was found for your selection.
Learn more about setting targets for metrics.
ORDER BY
You can specify how you want to sort the data returned by your query using the ORDER BY keyword, and its parameters: ASC, for ascending order, and DESC, for descending order.
You can specify any metric or dimension you're including in your query in the ORDER BY keyword, including multiple fields.
For example, this query returns net sales for all products and variants over the last year. The results are first sorted in alphabetical order by product title, and then in reverse alphabetical order by product type:
FROM sales
SHOW net_sales
GROUP BY product_title, product_type
SINCE -1y UNTIL today
ORDER BY product_title, product_type DESCThe order in which you write your metrics or dimension matters. If you specify multiple values for ORDER BY, then the sorting is applied to each metric or dimension in the order given.
TIMESERIES and the order of results
Depending on whether or not the query includes TIMESERIES and ORDER BY, the order of the returned rows can change.
TIMESERIES | ORDER BY | Result |
|---|---|---|
| Present | Not present | Results are ordered by TIMESERIES dimension. |
| Present | Present | Results are ordered by TIMESERIES time dimension, then ORDER BY dimension. |
| Not present | Present | Results are ordered by ORDER BY dimension. |
| Not present | Not present | Results are ordered by the first SHOW column. |
LIMIT
The LIMIT keyword allows you to specify a maximum number of rows that the query returns. This is useful when you want to preview how data displays, speed up queries on large datasets, or create top 10 lists. You can combine LIMIT with ORDER BY to create top and bottom lists.
If you don't specify a LIMIT value, then the query defaults to 1000 rows.
You can also use an optional { OFFSET # } parameter to skip a certain number of rows before beginning to return row data. The resulting phrase would be formatted similar to: LIMIT 15 { OFFSET 5 }.
This example uses LIMIT and ORDER BY to create a list of top 10 selling products over the last 3 months:
FROM sales
SHOW gross_sales as total_gross_sales
GROUP BY product_title
SINCE -3m UNTIL today
ORDER BY total_gross_sales DESC
LIMIT 10VISUALIZE and TYPE
The VISUALIZE keyword allows you to write a ShopifyQL query that displays data in a graphical visualization.
The TYPE keyword is optional and must be accompanied by a single type of visualization. If TYPE isn't included in your query, then ShopifyQL automatically selects the most suitable visualization for your query. If your query can't be visualized as written, then ShopifyQL returns tabular data. You can reference the TYPE keyword for each visualization in Selecting the right visualization for your Shopify report.
VISUALIZE also accepts an optional LIMIT keyword where the parameter is the limited number of data points to render in the visualization and data table. You can also use the optional MAX keyword to limit the number of data points in the visualization without impacting the data in the data table. MAX is the preferred keyword in new queries.
For example, you can visualize your sales trend over the last year by month with a trend line. This query returns a time series chart displaying the gross sales by month over the last year. The gross sales are depicted by a single line, with the x-axis labeled as month and the y-axis labeled as gross sales:
FROM sales
SHOW gross_sales
TIMESERIES month
SINCE -1y UNTIL today
VISUALIZE gross_sales TYPE lineMultiple metrics in visualizations
You can include multiple metrics in line visualizations for your report. Each metric included in the visualization must be separated by a comma, with the TYPE line keyword. Metrics listed in SHOW but not in VISUALIZE display in the data table only.
For example, the following query includes total sales, orders, and sessions as 3 separate lines in the visualization. Gross sales displays in the data table, but not in the visualization:
FROM sales
SHOW total_sales, orders, sessions, gross_sales
TIMESERIES month
SINCE -1y UNTIL today
VISUALIZE total_sales, orders, sessions TYPE lineTo use the Bar and line type visualization, you can separate the 2 metrics with a comma and specify the different TYPE value for each metric:
FROM sales
SHOW total_sales, orders, conversion_rate, gross_sales
TIMESERIES month
SINCE -1y UNTIL today
VISUALIZE total_sales TYPE bar, conversion_rate TYPE lineLearn more about including multiple metrics in report visualizations.
ANNOTATE
The ANNOTATE keyword displays annotations on your visualization, so that you can compare a change in a metric against the events that might explain it.
Write ANNOTATE at the end of your VISUALIZE statement, after any TYPE and MAX parameters. You can annotate in the following ways:
ANNOTATE ALL: Displays every category of annotation from all sources, including annotations that are generated by Shopify, created by apps, and created by you and your staff.ANNOTATE {category}: Displays every annotation in one category, such asANNOTATE product_events.ANNOTATE {category}.{type}: Displays a single type of annotation, such asANNOTATE product_events.published.
To combine categories and types, separate them with commas. Refer to the Shopify Developer Documentation for a complete list of annotation categories and types.
For example, this query displays daily total sales for the last 90 days, with markers for every product that was published or unpublished, and for every theme that was published:
FROM sales
SHOW total_sales
TIMESERIES day
SINCE -90d
VISUALIZE total_sales TYPE line ANNOTATE product_events, online_store_events.theme_publishedTo display annotations from only specific sources or creators, add FILTER after the annotation categories and types, followed by one or more conditions. If you don't include FILTER, then annotations from all sources display. You can filter annotations by the following fields:
source: The source of the annotation. Use'shopify'for annotations that are generated by Shopify,'app'for annotations that are created by apps, or'staff'for annotations that you and your staff create.app_id: The ID of the app that created the annotation.staff_id: The ID of the staff member who created the annotation.
Use = to filter by one value, or IN to filter by a list of values, such as source IN ('app', 'staff'). Enter app and staff IDs as numbers without quotation marks, such as staff_id = 123. To combine conditions, separate them with OR. Annotation filters don't support AND. Field names and source values are case-sensitive. When you enter app_id or staff_id in the ShopifyQL query editor, the apps and staff members that have created annotations are suggested.
For example, this query displays daily total sales for the last 90 days, with markers for every annotation that you and your staff created:
FROM sales
SHOW total_sales
TIMESERIES day
SINCE -90d
VISUALIZE total_sales TYPE line ANNOTATE ALL FILTER source = 'staff'Annotations need a time dimension, so your query must return one with TIMESERIES or GROUP BY, and use a visualization type that has a time axis. Annotations aren't available for multi-store queries that use FROM ORGANIZATION.
AS
The keyword AS is an optional keyword that allows you to rename (or provide an alias for) a column or an expression.
AS accepts only a single parameter. If the alias has a space in the name, then you must surround the alias with double quotes (").
FROM sales
SHOW total_sales AS "My Total Sales"Other ShopifyQL operators and features
ShopifyQL includes the following additional operators:
- Mathematical operators, such as
+or/ - Implicit joins
- Partial string and array matching, such as
STARTS WITHandCONTAINS - Comments
- Displaying data for organizations with multiple stores
- Metafields
- Metaobjects
Mathematical operators
ShopifyQL allows arithmetic operations with the metrics in your data. The following mathematical operators are available:
| Mathematical operator | Description |
|---|---|
| + | Addition of two numbers. |
| - | Subtraction of two numbers. |
| * | Multiplication of two numbers. |
| / | Division of two numbers. |
Mathematical expressions have the following limitations:
- Both values in an expression must be numeric. Dimensions such as product titles, IDs, and true or false values can't be used in arithmetic, even when an ID is displayed as a number.
- Dates and times support subtraction only. You can subtract one date from another date, or one time from another time, but you can't add, multiply, or divide them.
- Expressions are calculated in the
SHOWkeyword. AWHEREcondition can't contain any arithmetic. - A field that's used to join tables can't use math. Learn more about implicit joins.
For example, this query calculates order value for each region over the last year. When using mathematical operators with metrics, you can use the AS keyword to assign a new name to the new metric.
FROM sales
SHOW (net_sales + sales_reversals) AS order_value, orders
GROUP BY billing_region
SINCE -1y UNTIL todayImplicit joins
A join allows you to view metrics from different domains together, side by side. Joins are done implicitly and intelligently in ShopifyQL.
ShopifyQL has the following join capabilities:
- ShopifyQL allows dimension field joins when there is a single
FROMtable in the query. - Automatic left join on dimension fields.
- ShopifyQL allows multi-fact joins (when there are multiple
FROMtables in the queries). - Automatic full join on multi-fact joins, which support any number of tables or schemas and grouped by dimensions.
- Metrics in multi-fact joins can use math.
ShopifyQL has the following join restrictions:
- Join field must have the same name in all joined schemas.
- Join field must be in
GROUP BY. - Join field can't use math.
FROMis necessary for multi-fact joins to work.- In a multi-fact join, every
GROUP BYmust be in all schemas and is considered a field on which to be joined.
For example, this query uses a multi-fact join:
FROM sales, sessions
SHOW day, total_sales, sessions
GROUP BY day
SINCE 2023-10-03
ORDER BY dayPartial string and array matching
You can use the following operators for partial string and array matching:
| Operator | Description |
|---|---|
STARTS WITH | Return all rows where a column starts with a prefix. |
ENDS WITH | Return all rows where a column ends with a suffix. |
CONTAINS | Return all rows where a column contains a part of a string, or an element in an array. |
NOT CONTAINS | Return all rows where a column doesn't contain a part of a string, or an element in an array. |
Some examples of partial string matching using operators include the following queries:
FROM sales
SHOW product_title
WHERE product_title STARTS WITH 'Summer'
GROUP BY product_titleFROM sales
SHOW product_title
WHERE product_title ENDS WITH 'kit'
GROUP BY product_titleFROM sales
SHOW product_title
WHERE product_title CONTAINS 'Beef'
GROUP BY product_titleThe CONTAINS operator can be used to match elements within arrays, including integers, strings, and decimals. This matching isn't case-sensitive. Some examples of array matching using CONTAINS include the following queries:
FROM sales
SHOW orders
WHERE products_bought_together_ids CONTAINS '101'FROM customers
SHOW total_number_of_orders
WHERE customer_cities CONTAINS 'seattle'FROM sales
SHOW orders
WHERE variants_bought_together_variant_prices CONTAINS '10.2'Comments
You can use comments to explain sections of ShopifyQL statements, or to prevent the execution of a ShopifyQL statement. Any text within a comment will be ignored during execution time.
Single line comments start with -- and end at the end of the line.
Multi-line comments start with /* and end with */.
FROM sales
SHOW average_order_value, gross_sales
-- the line below has been commented out and won't run
-- GROUP BY billing_region
WHERE billing_country = 'United States'
/*
this line and the two lines below it have been commented out and won't run
SINCE 2021-01-01
UNTIL 2021-12-31
*/Other data that you can query with ShopifyQL
You can also use ShopifyQL to query the following data:
Displaying data for organizations with multiple stores
If your store is on a Plus or Enterprise plan and you have multiple stores within an organization, then you can modify your ShopifyQL query slightly to display data from multiple stores at one time. The FROM keyword should be followed by ORGANIZATION, and your WHERE keyword should include the shop_id for the stores that you want to include in your query declared as a parameter.
For example, you can return the sum of total sales across 4 stores in your organization by writing this query:
FROM ORGANIZATION sales
SHOW total_sales
WHERE shop_id IN (12301, 12302, 12303, 12304)Filtering on shop_id requires FROM ORGANIZATION. To find the shop_id value for each store in your organization, run an organization query by shop_id:
FROM ORGANIZATION sales
SHOW total_sales
GROUP BY shop_name, shop_idMulti-store queries also require the organization analytics permission.
Metafields
You can use product category metafields and supported custom metafields as dimensions or filters in your ShopifyQL queries.
Product category metafields in ShopifyQL
Category metafields map to specific product categories in Shopify's Standard Product Taxonomy.
Category metafields are formatted using dot notation in ShopifyQL queries. The formatting for a metafield is: product.metafields.shopify.{key}, where the {key} value is the specific metafield name, such as material or size. Multi-word hyphenated keys from the standard taxonomy use escaped identifiers, so the metafield is formatted as product.metafields.shopify."color-pattern" or product.metafields.shopify."age-group". Filtering a category metafield for a value requires the CONTAINS or NOT CONTAINS operator.
For example, if you sell garden planters and use the Home & Garden > Lawn & Garden > Gardening > Pots & Planters standard categorization for your products, then you might use the category's Shape metafield to store the shape of each planter (such as cylindrical, rectangular, round, and square). You could then use product.metafields.shopify.shape as a dimension or filter in your reports.
You can then display the total sales by product, filtered by the standard Shape metafield to include only "Rectangular" products, using the following query:
FROM sales
SHOW total_sales
GROUP BY product.title
WHERE product.metafields.shopify.shape CONTAINS 'Rectangular'When you group by a category metafield, all of a product's entries for that metafield are treated as one value. For example, if a planter has both Indoors and Outdoors selected for the category's Suitable space metafield, then its sales are grouped under Indoors, Outdoors rather than counted under each space separately. Planters with no Suitable space entry are grouped as (not set).
You can display your total sales by Suitable space using the following query:
FROM sales
SHOW total_sales
GROUP BY product.metafields.shopify."suitable-space"Custom metafields in ShopifyQL
ShopifyQL supports custom metafields for the following resource types:
- Products
- Variants
- Customers
- Orders
For each of the applicable resource types, ShopifyQL supports the following types of custom metafield:
- Text:
single_line_text_field,multi_line_text_field - Reference:
product_reference - Numbers:
number_integer,number_decimal,id,rating - Link:
url - Dates:
date,date_time - Other:
boolean,color - Arrays:
list.single_line_text_field,list.multi_line_text_field,list.number_integer,list.number_decimal
When creating the metafield, the option to Filter or group data in Analytics must be activated before it can be used as a dimension or filter in Shopify reports.
Custom metafields must be formatted using dot notation in ShopifyQL queries. The formatting for a metafield is: {entity}.metafields.{namespace}.{key}. For example, if you created a custom "Material" metafield for your products to store the type of material each product is made from (such as polyester, cotton, linen, and nylon), then you could use product.metafields.custom.material as a dimension or filter in your reports.
For example, you can display the total sales by product, filtered by the custom Material metafield to include only products with the "organic cotton" material, using the following query:
FROM sales
SHOW total_sales
WHERE product.metafields.custom.material = 'organic cotton'
GROUP BY product.titleYou can also access metafield values directly in ShopifyQL queries. For example, you can analyze customer data based on the values for a custom Loyalty tier metafield being greater than tier 2:
FROM customers
SHOW total_amount_spent
WHERE metafields.custom.loyalty_tier > 2
GROUP BY metafields.custom.loyalty_tierIn the previous example, the customers resource entity is declared in the FROM statement, so it isn't necessary to include it again in the GROUP BY or WHERE statements.
App events
Apps that are installed on your store can send events to Shopify, such as an email sent by a marketing app or a reward redeemed in a loyalty app. You can report on those events by querying FROM app_events, and group them by app or by time period.
The app event data that you can query depends on the apps that are installed on your store, and on whether each app's developer sends events to Shopify.
Apps can send standard events, which use an event name formatted as shopify.{category}.{event}, such as shopify.marketing.email_sent. Each event has its own metrics and dimensions. For example, the shopify.marketing.email_sent event has an emails_sent metric, and dimensions such as campaign_id and message_type.
Review the following table to learn about the fields that are available for every app event.
| Field | Type | Description |
|---|---|---|
app_name | Dimension | The name of the app that sent the event. Group by this field to compare the same metric across apps. |
event_handle | Dimension | The name of the event, such as shopify.marketing.email_sent. |
event_count | Metric | The number of events that apps sent. |
latest_event_timestamp | Metric | The date and time of the most recent event. |
For example, to compare the number of emails that each of your marketing apps sent over the last 30 days, your query is:
FROM app_events
SHOW emails_sent
GROUP BY app_name
TIMESERIES day
SINCE -30dYou can't query the app_events dataset together with another dataset in the same query. For example, FROM sales, app_events isn't supported.
Custom app events in ShopifyQL
Besides standard events, some apps define their own custom events, with metrics and dimensions that are specific to the app. For example, an appointment booking app with the handle bookings might define an appointment_booked event. The event could have an appointments metric for the number of appointments that customers book, and a service_type dimension for the type of service that each appointment is for.
In ShopifyQL queries, format custom app event fields using dot notation: event.{app}.{event}.{field}. The {app} part is the app's handle or API key, depending on which one the app's developer chose. For example, the booking app's appointments metric is event.bookings.appointment_booked.appointments.
If part of a field name includes a hyphen, then you must surround that part with double quotes ("). For example, if the booking app's handle is bookings-app, then the field is event."bookings-app".appointment_booked.appointments.
Each field from a custom app event is available only for the event that defines it. In the event_handle dimension, custom events use the name {app}.{event}, such as bookings.appointment_booked.
In query results and CSV exports, fields from custom app events use the labels that the app gives them.
Dimensions from custom app events are available only for the last 30 days of data. If your query groups or filters by one, then use a date range that starts within the last 30 days, such as SINCE -7d.
For example, to compare the number of appointments that customers booked for each service type over the last 7 days, your query is:
FROM app_events
SHOW event.bookings.appointment_booked.appointments
GROUP BY event.bookings.appointment_booked.service_type
TIMESERIES day
SINCE -7dMetaobjects
You can use the fields from your metaobjects as dimensions or filters in your ShopifyQL queries when the metaobject is referenced by a metafield on a supported resource type. ShopifyQL supports metaobject fields for the following resource types:
- Products
- Variants
- Customers
- Orders
The referencing metafield must be a single metaobject reference or a list of metaobject references. Fields from a metaobject that's referenced through a Mixed reference metafield can't be used in a query, and not every metaobject field type is supported.
Metaobject fields are formatted using dot notation that extends the referencing metafield with the metaobject field. The formatting is: {entity}.metafields.{namespace}.{key}.{field}, where {namespace}.{key} is the reference metafield and {field} is the metaobject field that you want to use.
For example, suppose your products reference a Designer metaobject through a custom designer metafield, and the metaobject has a country field. You can display total sales grouped by the designer's country using the following query:
FROM sales
SHOW total_sales
GROUP BY product.metafields.custom.designer.country