Sub topic 5
Writing efficient queries
This chapter assumes you can write SELECT, WHERE, GROUP BY and JOIN. It also assumes you know the DuneSQL types and the raw, decoded and curated table layers from earlier chapters. Here you will learn why some Dune queries finish in seconds and others time out, and which habits keep your queries on the fast side.
Why efficiency matters on Dune
DuneSQL runs on a Trino-based distributed engine. Table data is stored in columnar files, and large tables are split into partitions by date. Two consequences follow:
- The cost of a query is driven mostly by how much data the engine must read, not by how many rows you return.
- Reading less data depends on telling the engine early which partitions and columns you need.
Dune also meters usage. Longer and heavier executions use more credits on paid plans, and the free tier has limits on execution time and resources. A query that scans years of data to answer a question about last week wastes both time and budget. It also makes your dashboards slow for everyone who opens them.
How the engine reads a table
Picture a table such as dex.trades as a stack of daily folders. Each folder holds columnar files, so each column can be read on its own.
The date filter removes whole days. The column list removes whole columns. Everything after that point works on a much smaller set of data. Both steps happen before your joins and aggregations, so they matter most.
Rule 1: filter on the partition column
Each layer has its own date columns:
| Table type | Example | Partition-friendly date column |
|---|---|---|
| Curated | `dex.trades` | `block_date` |
| Decoded events | `erc20_ethereum.evt_Transfer` | `evt_block_date` |
| Decoded calls | many `*_call_*` tables | `call_block_date` |
| Raw | `ethereum.transactions` | `block_date` (and `block_time`) |
Decoded event and call tables also carry a timestamp column such as evt_block_time. Use the date column for the range filter, because it matches how the data is partitioned. You can still group by the timestamp afterward.
This query reads thirty days of Ethereum DEX trades:
SELECT
block_date,
SUM(amount_usd) AS volume_usd
FROM dex.trades
WHERE blockchain = 'ethereum'
AND block_date >= current_date - INTERVAL '30' DAY
GROUP BY 1
ORDER BY 1Now compare a version that hides the partition column inside a function:
SELECT
date_trunc('day', block_time) AS day,
SUM(amount_usd) AS volume_usd
FROM dex.trades
WHERE blockchain = 'ethereum'
AND CAST(block_date AS varchar) >= '2026-10-28'
GROUP BY 1
ORDER BY 1This second query may still return correct numbers. The problem is that wrapping the partition column in a cast or function can stop the engine from using the filter to skip partitions. It also compares strings where it should compare dates. Keep the partition column bare on the left side of the comparison, and put the computed value on the right.
Rule 2: select only the columns you need
Columnar storage means each column you name costs extra reading. SELECT * pulls every column, including wide ones such as data or input in raw tables.
Avoid this:
SELECT *
FROM erc20_ethereum.evt_Transfer
WHERE evt_block_date >= current_date - INTERVAL '1' DAYPrefer this:
SELECT
evt_block_time,
"from",
"to",
value
FROM erc20_ethereum.evt_Transfer
WHERE evt_block_date >= current_date - INTERVAL '1' DAY
AND contract_address = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48The names from and to are reserved words, so they need double quotes. The USDC address is written as an unquoted 0x... literal, which DuneSQL treats as varbinary. Do not wrap it in single quotes, or you will compare text to bytes and get no matches or an error.
Note that LIMIT does not make a query cheaper when it has an ORDER BY or aggregation. The engine must still read and sort everything before it can cut the result. A LIMIT alone, with no sort, can stop early. Do not rely on it to protect a heavy query.
Rule 3: narrow rows before you join or aggregate
Order your logic so the data shrinks as early as possible:
- Filter by date and chain.
- Filter by contract, token or project.
- Aggregate to the grain you need.
- Join the small aggregated result to anything else.
A common pattern is a common table expression (CTE) that does the narrowing and a final query that works on its output:
WITH recent AS (
SELECT
project,
taker,
amount_usd
FROM dex.trades
WHERE blockchain = 'ethereum'
AND block_date >= current_date - INTERVAL '7' DAY
)
SELECT
project,
SUM(amount_usd) AS volume_usd,
approx_distinct(taker) AS approx_traders
FROM recent
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10Trino's optimizer often pushes filters down on its own, so a CTE is not a magic speed-up. Its value is readability and a clear place to put the narrowing step.
Two further habits help with joins:
- Repeat the date filter on both sides of a join. Joining two large event tables on a key without date bounds on each forces both to be scanned in full. If you join on a transaction hash, also bound
block_dateon both tables. - Join on the narrowest key that is correct. Joining on
tx_hashalone can match across chains in multichain tables. Includeblockchainwhere the table has it.
Rule 4: use approximate and cheap functions when exactness is not needed
COUNT(DISTINCT x) on a large column needs a lot of memory. approx_distinct(x) returns an estimate with a small standard error (about 2.3% by default in Trino) and is much lighter. For a headline "active traders" chart this is usually acceptable. For a number you will reconcile to the unit, such as treasury accounting, use the exact count over a small, tightly filtered range.
Other cheap-by-default habits:
- Use
UNION ALL, notUNION, unless you need deduplication.UNIONadds a sort. - Use
LIKEon short, decoded text columns only after the date filter has narrowed the data. - Avoid
ORDER BYon large intermediate results. Sort only the final, small output.
Rule 5: choose the highest table layer that answers the question
Curated tables such as dex.trades already join logs to decoded pool data and add prices. Rebuilding that from ethereum.logs means scanning far more data and redoing work that has been done for you. Use this order of preference:
- A curated table, if it has the metric.
- A decoded table for a specific contract or event.
- Raw
transactions,logsortraces, only when nothing higher exists.
When you must use raw logs, filter on contract_address and on topic0 (the event signature hash) as well as on date. Those columns cut the rows read long before any decoding in your SQL.
Measuring instead of guessing
Do not tune by instinct. Use what the editor shows you:
- Run the query on a short window first, such as one day, and note the execution time.
- Widen to seven days and then thirty. If time grows roughly in line with the window, the query scales predictably. If it grows much faster, look for a join without date bounds.
- Check the execution details after a run to see how much data was processed.
- Prefix a query with
EXPLAINto see the plan and confirm the filters appear in the table scans.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| No date filter | Full-history scan, timeouts | Add a bare partition-column filter |
| `SELECT *` on a decoded or raw table | Extra columns read | List needed columns |
| Function wrapped around `block_date` | Partition pruning may be lost | Compare the bare column to a computed value |
| Quoted address literal | Type mismatch, empty results | Use unquoted `0x...` varbinary |
| Joining two big tables without date bounds | Both scanned in full | Bound each side |
| `COUNT(DISTINCT)` on huge ranges | Memory pressure | Use `approx_distinct` when an estimate is fine |
| Rebuilding a curated metric from raw logs | Much more data and logic | Start from the curated table |
Exercise
A teammate's query counts daily unique senders of USDC transfers using SELECT * FROM erc20_ethereum.evt_Transfer WHERE contract_address = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 and then groups in Python after downloading the result. It times out. Name three changes that make it cheaper, and write the improved query for the last 7 days.
Show answer
Add a partition filter on evt_block_date, replace SELECT * with only the needed columns, and aggregate inside SQL instead of downloading rows (using approx_distinct if an estimate is acceptable). For example:
SELECT
evtblockdate AS day,
approxdistinct("from") AS uniquesenders
FROM erc20ethereum.evtTransfer
WHERE contractaddress = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
AND evtblockdate >= currentdate - INTERVAL '7' DAY
GROUP BY 1
ORDER BY 1
Exercise
Why might WHERE CAST(block_date AS varchar) >= '2026-10-28' run slower than WHERE block_date >= DATE '2026-10-28', even though both express the same range?
Show answer
The cast wraps the partition column in a function, which can stop the engine from using the filter to skip whole date partitions. It also compares strings instead of dates. The second form leaves the column bare, so the engine can prune partitions and read only the days in range.