Query table
Use the Query table Wrk Action to retrieve data from your Datastore tables using SQL. You can filter and sort rows, combine tables, calculate summaries, and work with nested data. Results are returned as JSON for use in your Wrkflow.
Application
- Tables
Inputs (what you have)
| Name | Description | Data Type | Required? | Example |
|---|---|---|---|---|
| SQL query | One read-only SQL query against your Datastore tables. Include _id in the SELECT clause when you need the row ID. | Text (Long) | Yes | SELECT _id, name FROM customers LIMIT 100 |
Outputs (what you get)
| Name | Description | Data Type | Required? | Example |
|---|---|---|---|---|
| Total number of rows | The number of rows returned in Output JSON, after filtering, grouping, and any result limit. | Number | No | 1 |
| Output JSON | A JSON array containing the query results. Each object contains the selected fields or calculated values. | Text (Long) | No | [{"name":"Alex"}] |
For a query such as SELECT COUNT(*) AS total FROM orders, Total number of rows is 1. The number of matching orders is the total value inside Output JSON.
Outcomes
| Name | Description |
|---|---|
| Success | The query completed successfully. |
Write your first query
Enter your query in SQL query. Replace the example table and field names with names from your own Datastore:
SELECT _id, name, email
FROM customers
WHERE status = 'active'
ORDER BY name ASC, _id ASC
LIMIT 100
This returns up to 100 active customers, sorted by name and then row ID. Select only the fields you need, or use SELECT * to return all columns. Include _id explicitly when a later Wrk Action needs the row ID.
Each table exposes _id, columns for the keys stored in its rows, and the datastore_created_at and datastore_updated_at timestamps as ISO 8601 text.
Use single quotes for text values, such as 'active'. Quote table or field names containing spaces or special characters with double quotes or backticks, such as "Customer List".
Supported SQL
Datastore supports the SQL capabilities below, with the restrictions listed under Unsupported syntax. Each query must read at least one of your Datastore tables and return a single read-only result. A query can begin with SELECT or use WITH to define common table expressions before its final SELECT.
| Capability | Supported syntax and functions |
|---|---|
| Select and shape results | SELECT, DISTINCT, aliases with AS |
| Filter rows | WHERE, =, ==, !=, <>, >, <, >=, <=, BETWEEN, IN, NOT IN, IS NULL, IS NOT NULL, AND, OR |
| Sort and page results | ORDER BY, ASC, DESC, LIMIT, OFFSET |
| Combine tables | JOIN, INNER JOIN, LEFT JOIN, comma joins, ON, USING |
| Use subqueries | Subqueries in FROM, IN, EXISTS, and scalar subqueries in the select list |
| Define reusable query steps | Common table expressions with WITH, including WITH RECURSIVE |
| Combine result sets | UNION, UNION ALL |
| Summarize data | GROUP BY, HAVING, COUNT, COUNT(DISTINCT ...), MIN, MAX, AVG, SUM, TOTAL, GROUP_CONCAT |
| Rank or compare rows | Window functions including ROW_NUMBER, RANK, LAG, LEAD, NTILE, and SUM(...) OVER (...). Include PARTITION BY. |
| Apply conditional logic | CASE, IIF, COALESCE, NULLIF, CAST |
| Work with text | LIKE, GLOB, COLLATE NOCASE, UPPER, LOWER, SUBSTR, REPLACE, TRIM, INSTR, LENGTH, printf, format |
| Work with dates | date, datetime, strftime, julianday, unixepoch, and modifiers such as '+1 month' or 'start of month' |
| Calculate values | ROUND, ABS, sqrt, power, floor, ceil, ln, mod, pi |
| Work with JSON | json_extract, ->, ->>, json_each, json_tree, json_array_length, json_object, json_group_array, json_valid |
Example queries
These examples use illustrative tables and fields. Update the names to match your Datastore.
Filter and page results
Use WHERE to select matching rows, ORDER BY to define their order, and LIMIT with OFFSET to retrieve a page:
SELECT _id, customer, amount
FROM orders
WHERE amount >= 100 AND status IN ('open', 'pending')
ORDER BY amount DESC, _id ASC
LIMIT 10 OFFSET 20
This skips the first 20 matching rows and returns the next 10. A unique sort field such as _id makes the order consistent when other sort values are equal.
Combine data from two tables
Use LEFT JOIN to keep every order, including orders without a matching customer:
SELECT o._id AS order_id, o.amount, c.tier AS customer_tier
FROM orders AS o
LEFT JOIN "Customer List" AS c ON c.name = o.customer
LIMIT 100
Use INNER JOIN when you only want rows with a match in both tables. Give result columns unique names with AS, especially when selecting fields with the same name from different tables.
Summarize and filter groups
Use GROUP BY to summarize rows and HAVING to filter the summaries:
SELECT customer, COUNT(*) AS order_count, SUM(amount) AS total_amount
FROM orders
GROUP BY customer
HAVING COUNT(*) >= 5
ORDER BY total_amount DESC
LIMIT 100
To group orders by month, use strftime('%Y-%m', placed) in the select list and group by its alias.
Filter using another query
Use a subquery to find customers with open orders:
SELECT _id, name
FROM "Customer List"
WHERE name IN (
SELECT customer FROM orders WHERE status = 'open'
)
LIMIT 100
Find each customer's latest order
A common table expression creates a named intermediate result. Here, a window function ranks each customer's orders so the final query can select the latest:
WITH ranked AS (
SELECT _id, customer, placed,
ROW_NUMBER() OVER (
PARTITION BY customer ORDER BY placed DESC, _id DESC
) AS row_number
FROM orders
)
SELECT _id, customer, placed
FROM ranked
WHERE row_number = 1
LIMIT 100
Window functions require PARTITION BY. To treat all rows as one group, use OVER (PARTITION BY 1 ORDER BY _id).
Read nested values and arrays
Use dotted paths to read nested object fields:
SELECT _id, meta.region AS region
FROM orders
WHERE meta.region = 'east'
LIMIT 100
Use json_each to return one result row per array item:
SELECT o._id AS order_id, t.value AS tag
FROM orders AS o, json_each(o.meta, '$.tags') AS t
LIMIT 100
To read a specific array item, use json_extract(meta, '$.tags[0]'). Array indexes in dotted paths, such as meta.tags.0, are not supported.
How values are compared
Use the following rules when writing comparisons and calculations in Datastore queries.
Numbers and text
Use an unquoted number for a numeric comparison. For example, amount >= 50 matches both the number 50 and numeric text such as "50", but does not match nonnumeric text such as "N/A".
A quoted value is text. amount = '50' only matches the text "50". Likewise, amount > '60' compares text values, so use amount > 60 when you intend a numeric comparison.
When comparing two columns, including join keys, numeric text "50" does not equal the number 50. Keep the types of your join fields consistent.
Sorting, arithmetic, and aggregate functions handle mixed values as shown below. For a column containing 100, "50", "N/A", and 75:
| Expression | Result |
|---|---|
ORDER BY amount ASC | 75, 100, "50", "N/A": numbers sort before text. |
MAX(amount) | "N/A": text sorts above numbers. |
SUM(amount) | 225: numeric text is converted to a number; other text counts as zero. |
AVG(amount) | 56.25: nonnumeric text counts as zero and is included in the average. |
CAST(amount AS REAL) | Converts the values to 100, 50, 0, and 75. |
For numeric calculations, filter out unwanted values first. WHERE typeof(amount) IN ('integer', 'real') keeps stored numbers only. A comparison with a numeric literal also accepts numeric text, for example WHERE amount >= 0 when you want nonnegative amounts.
Booleans
Compare boolean fields explicitly: use WHERE flag = true or WHERE flag = false. A stored boolean is distinct from a number, so flag = 1 does not match true.
Avoid WHERE flag, WHERE flag IS TRUE, and IIF(flag, ...): stored true values are treated as false in these expressions. Use IIF(flag = true, ..., ...) instead.
Dates
Use ISO 8601 date values, such as '2025-04-01' or '2025-04-01T00:00:00Z'. A comparison against an ISO date literal is treated as a date comparison and only matches ISO date text. For example, placed >= '2025-04-01' can match 2025-04-15T10:00:00Z.
Use date functions for calculations, such as date(placed, '+1 month') or strftime('%Y-%m', placed).
Missing values and JSON
Use IS NULL to find null or missing values and IS NOT NULL to exclude them. The != and NOT IN operators also match null and missing values. For example, status != 'open' includes rows with no status. Add AND status IS NOT NULL if you want to exclude those rows.
Stored objects and arrays are returned as JSON objects and arrays. Stored strings remain strings, even when their contents look like JSON.
Names, quotes, and text matching
- Table and field names normally ignore case. If two keys differ only by case, such as
Websiteandwebsite, use the exact spelling to select the intended key. A spelling that matches neither exactly, such asWEBSITE, fails. - Single quotes are recommended for text values. Double-quoted values are treated as text only when no column has that name, so single quotes avoid ambiguity.
LIKEignores case for ASCII letters. Use%to match any sequence of characters and_to match one character. UseGLOBwhen you need case-sensitive matching.
Query limits
SQL queries load data from the referenced Datastore tables into an in-memory SQLite database. The table limits below apply to the SQL-query workload, not the amount of data a Datastore table can store.
| Limit | Maximum |
|---|---|
| Combined rows in the tables read by a query | 200,000 rows |
| Combined size of the tables read by a query | 200 MB (209,715,200 bytes) |
| Query runtime | 30 seconds |
| Rows in the result | 10,000 rows |
Both table limits apply across all tables read by the query. Filtering rows with WHERE or returning fewer rows with LIMIT does not reduce the size of the source tables. Use LIMIT to keep results within the result limit.
SQL queries can exceed these limits even when only one row matches, because the limits apply to the source tables rather than the returned results.
Use selective filters and return only the fields you need, but keep frequently queried tables small as well. Archive older records outside the active table, or separate historical records from current work according to your retention requirements.
Unsupported syntax
Datastore queries do not support the following SQL syntax:
| Unsupported syntax | What to use instead |
|---|---|
RIGHT JOIN | Reverse the table order and use LEFT JOIN. |
FULL OUTER JOIN | No direct equivalent is supported. A single LEFT JOIN does not include unmatched rows from both tables. |
CROSS JOIN | Use a comma join, such as FROM a, b. |
INTERSECT, EXCEPT | Use a subquery with IN or NOT EXISTS, depending on the result you need. |
A window with only ORDER BY | Add PARTITION BY, such as OVER (PARTITION BY 1 ORDER BY _id). |
Window frames such as ROWS BETWEEN ..., or named windows such as WINDOW w AS ... | These forms are not supported. |
Square brackets around names, such as [Customer List] | Use double quotes or backticks. |
Array indexes in dotted paths, such as meta.tags.0 | Use json_extract(meta, '$.tags[0]'). |
REGEXP | Use LIKE or GLOB for supported pattern matching. |
generate_series | Use a recursive common table expression that reads a Datastore table. |
Queries cannot modify data or database settings. INSERT, UPDATE, DELETE, CREATE, PRAGMA, and multiple statements in one query are not allowed. Use the appropriate Datastore Wrk Actions to create, update, or delete rows.
Queries must read a Datastore table. A standalone expression such as SELECT 1 or SELECT date('now') is not supported. Add FROM with one of your tables and LIMIT 1; this returns a result only if that table contains a row.
Result column names must be unique. For example, replace SELECT a.name, b.name with SELECT a.name AS first_name, b.name AS second_name.
Troubleshooting
Table-size errors
If the Wrk Action returns the following error:
Unable to run the SQL query: The tables a query references can hold up to 209715200 bytes in total. Query smaller tables.
- Review every table referenced by the query, including joined tables. A small output does not mean the source data fits within the query limits.
- Reduce the active data in those tables, or query a smaller table containing only the records needed for the task. Preserve any required historical records before removing them from the active table.
- Run the query again using Wrk Action Testing before resuming the Wrkflow.
Other query errors
If the Datastore service cannot run a query, it returns INVALID_QUERY with a message explaining the reason. Check the message for unsupported syntax, duplicate result names, or exceeded limits. A failed query is different from a valid query that finds no matching rows.
If results differ from what you expect, check the types of the stored values, use explicit boolean comparisons, and review the rules under How values are compared.