Analytic SQL Syntax¶
Learn the syntax of Analytic SQL. This guide covers all the language features you need to write powerful analytic queries.
Table of Contents¶
Basic Operations¶
FROM - Start with a table¶
Every Analytic SQL query starts with from:
This selects all columns from the users table.
SELECT - Choose columns¶
Use select to specify which columns you want:
WHERE - Filter rows¶
Filter rows with where:
Filtering¶
Comparison Operators¶
==- equals!=- not equals<,>,<=,>=- comparisonsis null/is not null- null checksin/not in- membership checks
Logical Operators¶
and- logical ANDor- logical ORnot- logical NOT
String Matching¶
Aggregations¶
GROUP BY¶
Group rows and compute aggregates:
The # symbol is shorthand for COUNT(*).
Multiple Aggregations¶
You can compute multiple aggregates in a single group by:
from sales
group by product (
sum(amount) as revenue,
avg(amount) as avg_order_value,
min(amount) as min_order,
max(amount) as max_order,
# as order_count
)
Aggregation Functions¶
#orcount(*)- count rowssum(column)- sum valuesavg(column)- average valuesmin(column)- minimum valuemax(column)- maximum value
Sorting & Limiting¶
SORT¶
Sort results with sort:
Multiple Sort Columns¶
TAKE - Limit results¶
Use take to limit the number of rows:
Date Functions¶
Date Extraction¶
Extract parts of dates:
Available functions:
- year(date) - extract year
- month(date) - extract month
- day(date) - extract day
- date(date) - extract date (remove time)
Date Truncation¶
Date Formatting¶
Joins¶
INNER JOIN¶
LEFT JOIN¶
Multiple Joins¶
from orders
join users on orders.user_id == users.id
join products on orders.product_id == products.id
select
users.name,
products.name as product_name,
orders.amount
Common Patterns¶
Top N by Group¶
Find the top 5 products by revenue in each category:
Time Series Analysis¶
Daily revenue for the last 30 days:
from orders
where date >= date("now") - 30
group by date(date) (
sum(amount) as daily_revenue,
# as order_count
)
sort date
Cohort Analysis¶
User signups by month:
Filtered Aggregations¶
Count active users per country:
Complete Example¶
Here's a complete query that demonstrates multiple features:
from orders
where date >= "2024-01-01"
and status == "completed"
join products on orders.product_id == products.id
group by products.category (
sum(orders.amount) as revenue,
avg(orders.amount) as avg_order_value,
# as order_count
)
sort -revenue
take 10
This query: 1. Starts with orders 2. Filters to completed orders from 2024 3. Joins with products 4. Groups by product category 5. Computes revenue, average order value, and order count 6. Sorts by revenue descending 7. Takes the top 10 categories
Next Steps¶
- Examples - See more real-world query patterns
- Language Specification - Complete syntax reference
- Playground - Try writing queries interactively
Ready to write queries? Open the playground →