Sub topic 2
Writing efficient queries
This chapter assumes you know basic SQL (SELECT, WHERE, GROUP BY, JOIN), understand transactions, blocks and smart contracts, and have seen ERC-20 tokens and decentralized exchanges (DEXs). You will write queries on Dune, then turn them into charts and read DefiLlama's metrics.
Writing efficient queries
Dune charges compute for each query, so scan less data. Filter on the partition column block_date and select only the columns you need.
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 1- Avoid
SELECT *on large tables. - Do not wrap
block_datein a function. Comparing it directly lets the engine skip partitions.
Making queries reusable with parameters
A parameter is a placeholder that Dune fills in when the query runs. The {{blockchain}} placeholder below lets one query serve many chains.
SELECT
block_date,
project,
SUM(amount_usd) AS volume_usd
FROM dex.trades
WHERE blockchain = '{{blockchain}}'
AND block_date >= current_date - INTERVAL '30' DAY
GROUP BY 1, 2
ORDER BY 1, 3 DESCFrom query results to charts and dashboards
Each query can produce several visualizations, such as a line chart or a table. A dashboard groups these visualizations and can expose the parameters as filters.
A tour of DefiLlama
DefiLlama is a free site that tracks DeFi protocols. Its main dashboards cover:
- TVL (total value locked) by protocol and chain
- DEX volume and protocol fees
- Yields and stablecoin supply
Its public API returns the same underlying data.
What TVL measures and what it leaves out
TVL is the value of assets deposited in a protocol, usually priced in USD. It does not count:
| Item | Included in TVL? |
|---|---|
| Assets deposited by users | Yes |
| Tokens held in the treasury | Often no, depending on the protocol |
| Trading volume | No |
| Fees earned | No |
> Dune and DefiLlama differ in methodology, so compare them only after checking each definition.
Exercise
Why is block_date >= current_date - INTERVAL '30' DAY faster than date_trunc('day', block_time) >= ...?
Show answer
The first form compares the partition column directly, so the engine can skip partitions. Wrapping the column in a function forces a scan of more data.