Query
Details and Options
- Query can perform complex filtering, reorganization, and aggregation of arbitrary rectangular and hierarchical data, typically returning further rectangular or hierarchical data.
- Query can operate on a Dataset object or an arbitrary nested expression consisting of lists and associations.
- Query can be seen as a generalization of Part that allows computations to be performed in the process of traversing an expression or dataset.
- The operatori can be any of the following forms:
-
Query[…],{op1,op2,…},… subquery operators
- In Query [operator1,…][expr], the operatori are applied at successively deeper levels in expr, but any given one may be applied either while "descending" into expr or while "ascending" out of it. In general, part specifications and filtering operators are "descending" operators. Aggregation operators, subquery operators, and arbitrary functions are "ascending" operators. Query [][expr] returns expr.
- A "descending" operator is applied to corresponding parts of the original dataset, before subsequent operators are applied at deeper levels. Descending operators have the feature that they do not change the structure of deeper levels of the data when applied at a certain level. This ensures that subsequent operators will encounter subexpressions whose structure is identical to the corresponding levels of the original dataset. The simplest descending operator is All , which selects all parts at a given level and therefore leaves the structure of the data at that level unchanged.
- An "ascending" operator is applied after all subsequent operators have been applied to deeper levels. Whereas descending operators correspond to the levels of the original data, ascending operators correspond to the levels of the result. Unlike descending operators, ascending operators do not necessarily preserve the structure of the data on which they operate. Unless an operator is specifically recognized to be descending, it is assumed to be ascending.
- The "descending" part operators specify which elements to take at a level before applying any subsequent operators to deeper levels:
-
All apply subsequent operators to each part of a list or associationi;;j take parts i through j and apply subsequent operators to each parti take only part i and apply subsequent operators to itKeys take keys of an association and apply subsequent operators to each keyValues take values of an association and apply subsequent operators to each value{part1,part2,…} take given parts and apply subsequent operators to each part
- The "descending" filtering operators specify how to rearrange or filter elements at a level before applying subsequent operators to deeper levels:
-
DeleteMissing drop elements with head Missing
- The "ascending" aggregation operators combine or summarize the results of applying subsequent operators to deeper levels:
-
Total total all quantities in the resultCatenate catenate the elements of lists or associations togetherCounts give association that counts occurrences of values in the resultCountDistinct give number of distinct values in the result
- The "ascending" subquery operators perform a subquery after applying subsequent operators to deeper levels:
-
Query[…] perform a subquery on the result{op1,op2,…} apply multiple operators at once to the result, yielding a listop1/* op2/* … apply op1, then apply op2 at the same level, etc.<|key1op1,key2op2,…|> apply multiple operators at once to the result, yielding an association with the given keys{key1op1,key2op2,…} apply different operators to specific parts in the result
- When one or more descending operators are composed with one or more ascending operators (e.g. desc/*asc), the descending part will be applied, then subsequent operators will be applied to deeper levels, and lastly the ascending part will be applied to the result.
- The special descending operator GroupBy [spec] will introduce a new association at the level at which it appears and can be inserted or removed from an existing query without affecting the behavior of other operators.
- The syntax GroupBy ["string"] can be used as a synonym for GroupBy [Key ["string"]]. The same syntax is also available for SortBy , CountsBy , MaximalBy , MinimalBy , and DeleteDuplicatesBy .
- The following options can be given:
-
- Possible values for FailureAction include:
-
None ignore all messages and failures"Abort" abort the entire query when a message is encountered (default)"Drop" drop the results of operations that issue messages"Encapsulate" wrap operations that issue messages in a Failure object"Replace" replace the results of operations that issue messages with Missing ["Failed"]
- The option MissingBehavior describes how numeric and other functions should treat expressions with head Missing . Possible values include:
-
- The option PartBehavior describes how operators that refer to nonexistent parts are evaluated. Possible values include:
-
Automatic invoke special rules for invalid i;;j, missing i, etc.
Examples
open all close allBasic Examples (1)
Construct tabular data on which to perform queries:
data = {
<|"a" -> 1, "b" -> "x", "c" -> {1}|>,
<|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,
<|"a" -> 3, "b" -> "z", "c" -> {3}|>,
<|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>};Take a specific row:
Query[2] @ dataApply a function to a specific column:
Query[Total, "a"] @ dataTake the contents of a column after selecting the rows:
Query[Select[#a < 5&], "b"] @ dataScope (1)
Construct tabular data on which to perform queries:
data = {
<|"a" -> 1, "b" -> "x", "c" -> {1}|>,
<|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,
<|"a" -> 3, "b" -> "z", "c" -> {3}|>,
<|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,
<|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,
<|"a" -> 6, "b" -> "z", "c" -> {}|>};Take a set of rows:
Query[1 ;; 3] @ dataTake a specific row:
Query[2] @ dataTake a specific element from a specific row:
Query[3, "a"] @ dataQuery[4, "b"] @ dataQuery[5, "c"] @ dataTake the contents of a specific column:
Query[All, "a"] @ dataQuery[All, "b"] @ dataQuery[All, "c"] @ dataTake a specific part within a column:
Query[All, "c", 1] @ dataTake a subset of the rows and columns:
Query[1 ;; 4, {"a", "b"}] @ dataApply a function to a specific column:
Query[Total, "a"] @ dataQuery[StringJoin, "b"] @ dataQuery[Catenate, "c"] @ dataPartition the data based on a column, applying the rest of the query to each group:
Query[GroupBy["b"], Catenate, "c"] @ dataApply a function to each row:
Query[All, Reverse] @ dataApply a function both to each row and to the entire result:
Query[Reverse, Reverse] @ dataApply a function f to every element in every row:
Query[All, All, f] @ dataApply specific operators to each column independently:
Query[All, {"a" -> f, "b" -> g, "c" -> h}] @ dataConstruct a new table by specifying operators that will compute each column:
Query[All, "c" /* <|"ctotal" -> Total, "clength" -> Length|>] @ dataUse the same technique to rename columns:
Query[All, <|"A" -> "a", "B" -> "b", "C" -> "c"|>] @ dataSelect specific rows based on a criterion:
Query[Select[#a < 5&]] @ dataTake the contents of a column after selecting the rows:
Query[Select[#a < 5&], "b"] @ dataTake a subset of the available columns after selecting the rows:
Query[Select[#a < 5&], {"b", "c"}] @ dataTake a value from the first row satisfying a criterion:
Query[SelectFirst[#a > 5&], "b"] @ dataSort the rows by a criterion:
Query[SortBy[Length[#c]&]] @ dataTake the rows that give the maximal value of a scoring function:
Query[MaximalBy[Length[#c]&]] @ dataDelete rows that duplicate a criterion:
Query[DeleteDuplicatesBy["b"]] @ dataCompose an ascending and a descending operator to aggregate values of a column after filtering the rows:
Query[Select[#b == "z"&] /* Total, "a"] @ dataDo the same thing by composing Total with the Query :
(Query[Select[#b == "z"&], "a"] /* Total) @ dataOptions (4)
FailureAction (2)
Create sample data:
list = Range[-2, 2]The setting FailureActionNone takes no special action on the result:
Query[All, 1 / #&, FailureAction -> None][list]The setting FailureAction ->"Encapsulate" encapsulates failed results in a Failure object:
Query[All, 1 / #&, FailureAction -> "Encapsulate"][list]The setting FailureAction ->"Replace" replaces failed results with a placeholder. For the function Query , this placeholder is a Missing object:
Query[All, 1 / #&, FailureAction -> "Replace"][list]The setting FailureAction ->"Drop" causes failed results to be dropped from the final expression:
Query[All, 1 / #&, FailureAction -> "Drop"][list]The setting FailureAction ->"Abort" aborts the computation, returning a Failure object instead:
Query[All, 1 / #&, FailureAction -> "Abort"][list]The setting FailureAction ->{"Drop",f} can be used to perform an action before dropping a failed result:
list = Range[-2, 2]Query[All, 1 / #&, FailureAction -> {"Drop", Print}][list]The setting FailureAction ->{"Replace",f} can be used to specify a replacement that is a function of the failure:
Query[All, 1 / #&, FailureAction -> {"Replace", #["StyledMessage"]&}][list]MissingBehavior (1)
The default option value MissingBehavior ->Automatic applies special rules to operators that encounter Missing :
Query[Total] @ {1, 2, 3, Missing[]}Use MissingBehavior ->None to specify the ordinary behavior of Missing for all operators:
Query[Total, MissingBehavior -> None] @ {1, 2, 3, Missing[]}PartBehavior (1)
The default option value PartBehavior ->Automatic invokes special behavior for operators that would otherwise fail:
Query[1 ;; 5] @ {1, 2, 3}Using PartBehavior ->None specifies that the ordinary behavior of Part should be used:
Query[1 ;; 5, PartBehavior -> None] @ {1, 2, 3}Properties & Relations (2)
Query […] can apply any number of operators:
data = RandomInteger[10, {3, 3}]Query[All, Select[EvenQ]][data]For zero applied operators, Query [][data] returns data:
Query[][data]Query is the operator form of the query language supported by Dataset :
Query["b", Total] @ <|"a" -> {1, 2}, "b" -> {3, 4}|>Dataset[<|"a" -> {1, 2}, "b" -> {3, 4}|>]["b", Total]Before being applied, Query expressions are "compiled" into ordinary compositions of ordinary Wolfram Language functions and their operator forms. To see the compiled form of a Query , use Normal :
Query[All, f]//NormalQuery[f, g]//NormalQuery[GroupBy["a"], Total]//NormalRelated Guides
Related Workflows
- Analyze a Computable Dataset ▪
- Select Elements in a Dataset ▪
- Extract Columns in a Dataset
History
Text
Wolfram Research (2014), Query, Wolfram Language function, https://reference.wolfram.com/language/ref/Query.html.
CMS
Wolfram Language. 2014. "Query." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/Query.html.
APA
Wolfram Language. (2014). Query. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Query.html
BibTeX
@misc{reference.wolfram_2026_query, author="Wolfram Research", title="{Query}", year="2014", howpublished="\url{https://reference.wolfram.com/language/ref/Query.html}", note=[Accessed: 16-August-2026]}
BibLaTeX
@online{reference.wolfram_2026_query, organization={Wolfram Research}, title={Query}, year={2014}, url={https://reference.wolfram.com/language/ref/Query.html}, note=[Accessed: 16-August-2026]}