Docs
DocumentationQuery ReferenceAPI Reference
Open Console→→
DocumentationQuery ReferenceAPI Reference

Introduction

Query reference overview

APL

IntroductionSample queriesAll features
Functions
Scalar functions
Array functions
Overview
array_concat
array_extract
array_iff
array_index_of
array_length
array_reverse
array_rotate_left
array_rotate_right
array_select_dict
array_shift_left
array_shift_right
array_slice
array_sort_asc
array_sort_desc
array_split
array_sum
bag_has_key
bag_keys
bag_pack
bag_zip
isarray
len
pack_array
pack_dictionary
strcat_array
Conditional functions
Overview
case
iff
Conversion functions
Overview
dynamic_to_json
ensure_field
isbool
toarray
tobool
todatetime
todouble, toreal
todynamic
tohex
toint, tolong
tostring
totimespan
Datetime functions
Overview
ago
datetime_add
datetime_diff
datetime_part
dayofmonth
dayofweek
dayofyear
endofday
endofmonth
endofweek
endofyear
getmonth
getyear
hourofday
monthofyear
now
startofday
startofmonth
startofweek
startofyear
unixtime_microseconds_todatetime
unixtime_milliseconds_todatetime
unixtime_nanoseconds_todatetime
unixtime_seconds_todatetime
week_of_year
GenAI functions
Overview
genai_concat_contents
genai_conversation_turns
genai_cost
genai_estimate_tokens
genai_extract_assistant_response
genai_extract_function_results
genai_extract_system_prompt
genai_extract_tool_calls
genai_extract_user_prompt
genai_get_content_by_index
genai_get_content_by_role
genai_get_pricing
genai_get_role
genai_has_tool_calls
genai_input_cost
genai_is_truncated
genai_message_roles
genai_output_cost
Hash functions
Overview
hash
hash_md5
hash_sha1
hash_sha256
hash_sha512
IP functions
Overview
format_ipv4
format_ipv4_mask
geo_info_from_ip_address
has_any_ipv4
has_any_ipv4_prefix
has_ipv4
has_ipv4_prefix
ipv4_compare
ipv4_is_in_range
ipv4_is_in_any_range
ipv4_is_match
ipv4_is_private
ipv4_netmask_suffix
ipv6_compare
ipv6_is_in_any_range
ipv6_is_in_range
ipv6_is_match
parse_ipv4
parse_ipv4_mask
Mathematical functions
Overview
abs
acos
asin
atan
atan2
cos
cot
degrees
exp
exp2
exp10
gamma
isfinite
isinf
isint
isnan
log
log2
log10
loggamma
max_of
min_of
not
pi
pow
radians
rand
range
round
set_difference
set_has_element
set_intersect
set_union
sign
sin
sqrt
tan
Metadata functions
Overview
column_ifexists
cursor_current
ingestion_time
Pair functions
Overview
find_pair
pair
parse_pair
Rounding functions
Overview
bin
bin_auto
ceiling
floor
String functions
Overview
base64_decode_toarray
base64_decode_tostring
base64_encode_fromarray
base64_encode_tostring
coalesce
countof
countof_regex
extract
extract_all
format_bytes
format_url
gettype
indexof
indexof_regex
isascii
isempty
isnotempty
isnotnull
isnull
parse_bytes
parse_csv
parse_json
parse_path
parse_url
parse_urlquery
quote
regex_quote
replace
replace_regex
replace_string
reverse
split
strcat
strcat_delim
strcmp
string_size
strlen
strrep
strip_ansi_escapes
substring
tolower
totitle
toupper
translate
trim
trim_end
trim_end_regex
trim_regex
trim_space
trim_start
trim_start_regex
unicode_codepoints_from_string
unicode_codepoints_to_string
url_decode
url_encode
SQL functions
Overview
parse_sql
format_sql
Time series functions
Overview
series_abs
series_acos
series_add
series_asin
series_atan
series_ceiling
series_cos
series_cosine_similarity
series_divide
series_dot_product
series_equals
series_exp
series_fft
series_fill_backward
series_fill_const
series_fill_forward
series_fill_linear
series_fir
series_floor
series_greater
series_greater_equals
series_ifft
series_iir
series_less
series_less_equals
series_log
series_magnitude
series_max
series_min
series_multiply
series_not_equals
series_pearson_correlation
series_pow
series_sign
series_sin
series_stats
series_stats_dynamic
series_subtract
series_sum
series_tan
Type functions
Overview
isimei
ismap
isreal
iscc
isstring
isutf8
Aggregation functions
Overview
arg_min
arg_max
avg
avgif
count
countif
dcount
dcountif
histogram
histogramif
make_list
make_list_if
make_set
make_set_if
max
maxif
min
minif
percentile
percentileif
percentiles_array
percentiles_arrayif
phrases
rate
spotlight
stdev
stdevif
sum
sumif
topk
topkif
variance
varianceif
Operators
Tabular operators
Overview
count
distinct
extend
extend-valid
externaldata
getschema
join
limit
lookup
make-series
mv-expand
order
parse
parse-kv
parse-where
project
project-away
project-keep
project-rename
project-reorder
redact
sample
search
sort
summarize
take
top
union
where
Scalar operators
Set membership operators
Overview
in
!in
in~
!in~
Logical
Numerical
String
Reference
Entity names
Map fields
Null values
Scalar data types
Set statement
Special field attributes
Migrate
Splunk SPL
SQL
Sumo Logic

MPL

Language featuresSample queriesMigrate
APL/Operators

union

This page explains how to use the union operator in APL.

The union operator in APL allows you to combine the results of two or more queries into a single output. The operator is useful when you need to analyze or compare data from different datasets or tables in a unified manner. By using union, you can merge multiple sets of records, keeping all data from the source tables without applying any aggregation or filtering.

The union operator is particularly helpful in scenarios like log analysis, tracing OpenTelemetry events, or correlating security logs across multiple sources. You can use it to perform comprehensive investigations by bringing together information from different datasets into one query.

Union of two datasets

To understand how the union operator works, consider these datasets:

Server requests

_timestatusmethodtrace_id
12:10200GET1
12:15200POST2
12:20503POST3
12:25200POST4

App logs

_timetrace_idmessage
12:121foo
12:213bar
13:3527baz

Performing a union on Server requests and Application logs would result in a new dataset with all the rows from both DatasetA and DatasetB.

A union of requests and logs would produce the following result set:

_timestatusmethodtrace_idmessage
12:10200GET1
12:121foo
12:15200POST2
12:20503POST3
12:213bar
12:25200POST4
13:3527baz

This result combines the rows and merges types for overlapping fields.

Usage

Syntax

APL
T1 | union [withsource=FieldName] [T2], [T3], ...

Parameters

  • T1, T2, T3, ...: Tables or query results you want to combine into a single output.
  • withsource: Optional, adds a field to the output where each value specifies the source dataset of the row. Specify the name of this additional field in FieldName.

Returns

The union operator returns all rows from the specified tables or queries. If fields overlap, they're merged. Non-overlapping fields are retained in their original form.

Use case examples

In log analysis, you can use the union operator to combine HTTP logs from different sources, such as web servers and security systems, to analyze trends or detect anomalies.

Query

APL
['sample-http-logs']
| union ['security-logs']
| where status == '500'

Output

_timeidstatusurimethodgeo.citygeo.countryreq_duration_ms
2024-10-17 12:34:56user123500/api/loginGETLondonUK345
2024-10-17 12:35:10user456500/api/update-profilePOSTBerlinGermany123

This query combines two datasets (HTTP logs and security logs) and filters the combined data to show only those entries where the HTTP status code is 500.

When working with OpenTelemetry traces, you can use the union operator to combine tracing information from different services for a unified view of system performance.

Query

APL
['otel-demo-traces']
| union ['otel-backend-traces']
| where ['service.name'] == 'frontend' and status_code == 'error'

Output

_timetrace_idspan_id['service.name']kindstatus_code
2024-10-17 12:36:10trace-1234span-567frontendservererror
2024-10-17 12:38:20trace-7890span-345frontendclienterror

This query combines traces from two different datasets and filters them to show only errors occurring in the frontend service.

For security logs, the union operator is useful to combine logs from different sources, such as intrusion detection systems (IDS) and firewall logs.

Query

APL
['sample-http-logs']
| union ['security-logs']
| where ['geo.country'] == 'Germany'

Output

_timeidstatusurimethodgeo.citygeo.countryreq_duration_ms
2024-10-17 12:34:56user789200/api/loginGETBerlinGermany245
2024-10-17 12:40:22user456404/api/nonexistentGETMunichGermany532

This query combines web and security logs, then filters the results to show only those records where the request originated from Germany.

Other examples

Basic union

This example combines all rows from github-push-event and github-pull-request-event without any transformation or filtering.

APLRun in Playground
['github-push-event']
| union ['github-pull-request-event']

Filter after union

This example combines the datasets, and then filters the data to only include rows where the method is GET.

APLRun in Playground
['sample-http-logs']
| union ['github-issues-event']
| where method == "GET"

Aggregate after union

This example combines the datasets and summarizes the data, counting the occurrences of each combination of content_type and actor.

APLRun in Playground
['sample-http-logs']
| union ['github-pull-request-event']
| summarize Count = count() by content_type, actor

Filter and project specific data from combined log sources

This query combines GitHub pull request event logs and GitHub push events, filters by actions made by github-actions[bot], and displays key event details such as time, repository, commits, head , id.

APLRun in Playground
['github-pull-request-event']
| union ['github-push-event']
| where actor == "github-actions[bot]"
| project _time, repo, ['id'], commits, head

Union with field removing

This example removes the content_type and commits field in the datasets sample-http-logs and github-push-event before combining the datasets.

APLRun in Playground
['sample-http-logs']
| union ['github-push-event']
| project-away content_type, commits

Filter after union

This example performs a union and then filters the resulting set to only include rows where the method is GET.

APLRun in Playground
['sample-http-logs']
| union ['github-issues-event']
| where method == "GET"

Union with order by

After the union, the result is ordered by the type field.

APLRun in Playground
['sample-http-logs']
| union hn
| order by type

Union with joint conditions

This example performs a union and then filters the resulting dataset for rows where content_type contains the letter a and city is seattle.

APLRun in Playground
['sample-http-logs']
| union ['github-pull-request-event']
| where content_type contains "a" and ['geo.city']  == "Seattle"

Union and count unique values

After the union, the query calculates the number of unique geo.city and repo entries in the combined dataset.

APLRun in Playground
['sample-http-logs']
| union ['github-push-event']
| summarize UniqueNames = dcount(['geo.city']), UniqueData = dcount(repo)

Union using withsource

The example below returns the union of all datasets that match the pattern github* and counts the number of events in each.

APLRun in Playground
union withsource=dataset github*
| summarize count() by dataset

Union with wildcards

The union operator supports wildcards to combine multiple datasets matching a pattern. Use * to match all datasets, or a suffix pattern like github* to match datasets starting with a prefix.

Warning

The wildcard * is useful to match multiple datasets, but it increases query complexity and decreases performance.

Using union * to query all datasets is very expensive. Avoid it in production. Use specific dataset names or prefix patterns instead.

Match all datasets:

APL
union *
| summarize count() by dataset

Match datasets with a prefix:

APL
union withsource=dataset github*
| summarize count() by dataset

Best practices for the union operator

To maximize the effectiveness of the union operator in APL, here are some best practices to consider:

  • Before using the union operator, ensure that the fields being merged have compatible data types.
  • Use project or project-away to include or exclude specific fields. This can improve performance and the clarity of your results, especially when you only need a subset of the available data.

Other query languages

Was this page helpful?
Suggest edits on GitHub
PrevioustopNextwhere
On this page
Union of two datasetsUsageSyntaxParametersReturnsUse case examplesOther examplesBasic unionFilter after unionAggregate after unionFilter and project specific data from combined log sourcesUnion with field removingFilter after unionUnion with order byUnion with joint conditionsUnion and count unique valuesUnion using withsourceUnion with wildcardsBest practices for the union operatorOther query languages