NEW: The Blockchain Data Engineering Guide is out →NEW: The Blockchain Data Engineering Guide is out →BLACK FRIDAY SALE is live →
defi analytics sqldefi analyticsdefi analytics sql tutorialdune dex.tradessandwich attack detection sqluniswap sqlaave sqlwizardcamp

DeFi Analytics With SQL: DEX, MEV and Lending Queries (2026)

Vincent Charles

Vincent Charles

November 30, 2026 · 19 min read

DeFi Analytics With SQL: DEX, MEV and Lending Queries (2026)

DeFi analytics with SQL means querying swaps, liquidity and lending events as tables. On Dune, most of that work starts in one table, dex.trades, with one row per swap across EVM DEXs and chains, plus lending tables for supply and borrow events and Spellbook tables like dex.sandwiches for MEV.

The SQL is standard. What makes DeFi data hard is the data model: two swap directions in one table, multi-hop transactions, whale trades that wreck averages, events that are not balances, and bots that trade around users in the same block.

This guide walks through seven DeFi analytics SQL queries, from a WETH/USDC execution price to sandwich attack detection. Each one is a real exercise from WizardCamp's DeFi, MEV and protocol pack modules, with the actual question, the reference solution and the real result on a documented sample of Dune data. If you are new to onchain SQL, start with our Dune SQL tutorial and Ethereum SQL tutorial first, then come back here.

Practice these DeFi queries on WizardCamp →

TL;DR:

  • One table does most of the work: dex.trades holds one row per swap across DEXs and chains, with amount_usd already computed.
  • The 7 queries: execution price, swap size outliers, average swap size by chain, Aave supply vs borrow, sandwich victims, backruns per pool and Solana aggregator share.
  • The traps: both swap directions, multi-hop rows that share a hash, means skewed by whales, averages of averages, and events mistaken for balances.
  • They count toward certificates: the queries belong to WizardCamp's DeFi Analytics and MEV parts, the Uniswap and Aave packs and the Solana path.
  • Our data: As of November 29, 2026, 22 of 287 live data roles on the Unchain Data job board mention DeFi, and 16 of those 22 (73%) also ask for SQL.

What is DeFi analytics with SQL?

DeFi analytics with SQL is the practice of measuring decentralized finance protocols, such as DEXs and lending markets, by querying their onchain events with SQL. Typical questions are daily volume, execution prices, liquidity, borrow demand, user counts and MEV. Analysts usually run these queries on Dune, where swaps and lending events are already decoded into shared tables.

Dashboards like DefiLlama answer the common questions for you. SQL is what you need when the question is specific: which pool lost the most to sandwich bots, what share of a chain's volume goes through an aggregator, or whether one whale is behind a volume spike. That is the work crypto data teams hire for.

Which Dune tables hold DeFi data?

The core DeFi tables on Dune are dex.trades for EVM swaps, dex_solana.trades for Solana swaps, dex.sandwiches for detected sandwich attacks, and lending.supply and lending.borrow for supply and borrow events. Each row is one event, so volume, users and prices are aggregations you build yourself.

TableOne row perUse it for
dex.tradesSwap on an EVM DEXVolume, execution price, pools, traders
dex_solana.tradesSwap on a Solana DEXVolume by venue, pair and aggregator
dex.sandwichesLeg of a detected sandwichMEV analysis, victim and attacker checks
lending.supply / lending.borrowSupply or borrow eventDeposits, borrow demand, unique borrowers

Two habits save you time and credits on all of them. Filter on blockchain and on block_date or block_month first, and start with one day before you run a month.

How to use this guide

Run each query in WizardCamp, where it is graded instantly against the reference answer. WizardCamp runs on small, documented samples of real Dune tables in your browser. Most EVM queries below use Ethereum mainnet swaps from January 13 to 15, 2024, the Uniswap query uses Uniswap Labs' public Uniswap V4 volume query, and the Solana query uses one week of dex_solana.trades from August 2026. The numbers are real, but they describe the sample, not the whole chain.

A few differences matter when you move a query to Dune:

  • Table names are shortened. The sandbox calls a sample of dex.trades either trades or dex_trades. On Dune, use dex.trades and add a blockchain = 'ethereum' filter.
  • Hashes and addresses are binary on Dune. They are varbinary and display as 0x.... The sandbox stores them as lowercase hex text, or wraps them in lower(hex(...)).
  • Amounts are already decimal adjusted. In dex.trades, token_bought_amount, token_sold_amount and amount_usd are human readable. The _raw columns are not.

Query 1: Compute the WETH/USDC execution price

From WizardCamp's DeFi Analytics module ("WETH/USDC Execution Price", part 4 of the Ethereum path).

SQL concept: CASE WHEN to handle both directions of a pair. Dune table: dex.trades.

For each WETH/USDC swap, compute the execution price in USDC per WETH, whichever side the trader bought, and exclude every other pair.

SELECT lower(hex(tx_hash)) AS tx_hash,
  CASE WHEN token_bought_symbol = 'WETH' THEN token_sold_amount / token_bought_amount
       WHEN token_sold_symbol   = 'WETH' THEN token_bought_amount / token_sold_amount END AS execution_price_usd_per_weth
FROM trades
WHERE (token_bought_symbol = 'WETH' AND token_sold_symbol = 'USDC') OR (token_bought_symbol = 'USDC' AND token_sold_symbol = 'WETH')
ORDER BY tx_hash ASC, execution_price_usd_per_weth DESC

The sample holds 12 real WETH/USDC swaps, six in each direction. Every execution price lands between 2,513.64 and 2,528.78 USDC per WETH, a spread of about 0.6% over three days. One transaction, 0xb959491c..., appears twice, at 2,524.32 and 2,523.87.

The lesson: dex.trades records each swap from the trader's side, so the same pair shows up as WETH bought for USDC and as USDC bought for WETH. A query that only handles one direction silently drops half the trades, or worse, returns prices around 0.0004 for the other half. The repeated hash is a multi-hop swap: one transaction that routed through two pools emits two rows. Both are real swaps, and the second ORDER BY column is what keeps their order deterministic. On Dune, match token_bought_address and token_sold_address, not symbols, because symbols collide.

Query 2: Flag swap size outliers against the daily median

From WizardCamp's DeFi Analytics module ("DEX Swap Size Outliers", part 4 of the Ethereum path).

SQL concept: PERCENTILE_CONT in a CTE, then join back. Dune table: dex.trades.

Flag every swap whose amount_usd is more than twice the median swap size for its project and day.

WITH daily_median AS (SELECT project, block_date, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount_usd) AS median_usd FROM trades GROUP BY project, block_date)
SELECT lower(hex(t.tx_hash)) AS tx_hash, t.project, t.block_date, t.amount_usd, m.median_usd, t.amount_usd > 2 * m.median_usd AS is_outlier
FROM trades t JOIN daily_median m ON m.project = t.project AND m.block_date = t.block_date
ORDER BY t.block_date ASC, t.project ASC, t.tx_hash ASC, t.amount_usd DESC

The sample is 63 swaps on Uniswap, Curve and SushiSwap, seven per project per day. The query flags 16 of them. The biggest is a real Curve whale swap on January 15, 2024: $2,612,994.68, against a same day Curve median of $44,313.92, about 59 times the median.

The lesson: DeFi volume is heavy tailed, so use the median, not the mean, as your baseline. That one Curve swap pulls the Curve mean for January 15 to $396,511.44, about 9 times the median, so a mean based baseline moves with the very outliers you are trying to catch. The median has to be computed per project and per day, because a $5,000 swap is normal on Curve and large on SushiSwap. And do not deduplicate on tx_hash: on January 14, two Curve rows of $193,126.97 and $191,728.48 share one hash, because they are two hops of the same trade.

Query 3: Compute the average swap size per chain

From WizardCamp's Uniswap Analytics pack ("Average Swap Size by Chain", Ethereum path).

SQL concept: ratio of sums, rounded at the end. Dune table: dex.trades, aggregated by Uniswap Labs.

The table holds one row per chain per day, with total USD volume and the number of swaps. Compute the average swap size per chain.

SELECT blockchain, ROUND(SUM(volume) / SUM(num_swaps), 2) AS avg_swap_usd FROM uniswap_swaps GROUP BY blockchain ORDER BY avg_swap_usd DESC

The sample is 30 chain day rows across six chains, from January 22 to February 2, 2025, derived from Uniswap Labs' public Uniswap V4 volume query.

blockchainavg_swap_usd
ethereum819.03
unichain699.11
base1.98
optimism0.77
polygon0.46
arbitrum0.45

The lesson: never average daily averages. The tempting query, AVG(volume / num_swaps), returns 245.82 for Ethereum instead of 819.03, because it gives a quiet day with a handful of swaps the same weight as a busy one. Total volume divided by total swaps weights every swap equally, which is what "average swap size" means. The same trap shows up in average fee per transaction, average deposit per user and average gas price per day. Ethereum's 98 swaps in this sample carried $80,265.02, while Base needed 285 swaps to reach $563.45.

Query 4: Put Aave supply and borrow side by side

From WizardCamp's Aave Lending pack ("Aave Supply vs Borrow by Token", Ethereum path).

SQL concept: conditional aggregation with SUM(CASE WHEN ...). Dune tables: lending.supply and lending.borrow (Aave V3 events).

For each token, compute total supply volume and total borrow volume side by side.

SELECT token_symbol, SUM(CASE WHEN event_type = 'supply' THEN amount ELSE 0 END) AS total_supply, SUM(CASE WHEN event_type = 'borrow' THEN amount ELSE 0 END) AS total_borrow FROM aave_events GROUP BY token_symbol ORDER BY total_supply DESC

The sample is 100 Aave V3 supply and borrow events from January 13, 2025, with amounts already scaled by token decimals. DAI shows about 1.19 billion supplied against about 3.72 million borrowed. USDC shows about 4.37 million supplied and about 6.18 million borrowed.

The lesson: events are flows, not balances. USDC borrows exceed USDC supply in this window, but that does not mean the market is more than 100% utilized. It means more USDC was borrowed than deposited during these events, while the pool's existing deposits sit outside the sample. Real utilization needs net positions, supply minus withdrawals and borrows minus repayments, ideally from the start of history. Our lending utilization interview question shows that version on Solana lending data.

A single supply event of 100,000,000.3 DAI dominates the DAI total, so check for whales before you report a daily flow. Aave Supply vs Borrow is often available as WizardCamp's free rotating exercise.

Query 5: Detect sandwich attack victims

From WizardCamp's MEV & Order Flow module ("Sandwich Attack Detection", part 6 of the Ethereum path).

SQL concept: a three way self join with ordering conditions. Dune tables: dex.trades and dex.sandwiches.

A sandwich has a front leg and a back leg from the same sender, in the same block and pool, in opposite directions, with at least one event between them. A victim is another sender who trades in the front leg's direction between the two legs. Find the victims.

SELECT front.block_number, front.project_contract_address, front.tx_from AS attacker, victim.tx_from AS victim, victim.amount_usd AS victim_amount_usd
FROM dex_trades front
JOIN dex_trades back ON back.block_number = front.block_number AND back.project_contract_address = front.project_contract_address AND back.tx_from = front.tx_from AND back.tx_hash <> front.tx_hash AND front.token_sold_address = back.token_bought_address AND front.token_bought_address = back.token_sold_address AND front.evt_index + 1 < back.evt_index
JOIN dex_trades victim ON victim.block_number = front.block_number AND victim.project_contract_address = front.project_contract_address AND victim.tx_from <> front.tx_from AND victim.token_bought_address = front.token_bought_address AND victim.token_sold_address = front.token_sold_address AND victim.evt_index BETWEEN front.evt_index AND back.evt_index
ORDER BY front.block_number, front.project_contract_address

The sample is 12 rows copied from dex.trades and dex.sandwiches on Ethereum, January 13, 2024, 13:00 to 13:02 UTC. The query returns three victims, all sandwiched by the same address, 0xae2fc483....

block_numberpoolvictimvictim_amount_usd
189981300x2a7ae6e3... (MICKEY/WETH)0xd75a69a7...4,584.44
189981300x916314ff... (TMNT/WETH)0x3d7f5208...521.01
189981310x15d34b0f... (MINNIE/WETH)0xe0863ab4...233.80

In the first row, the bot sold WETH for MICKEY at event 11 ($782.59), the victim bought MICKEY with WETH at event 29 ($4,584.44), and the bot sold the MICKEY back at event 50 ($800.92).

The lesson: the join conditions are the definition, and each one removes a real false positive.

In block 18,998,138, the sample holds a front and a back leg from another address but no victim trade between them, so the inner join correctly returns nothing: you can only report victims you can see. In block 18,998,130, a trade at event 74 comes after the back leg and in the opposite direction, so it is not a victim. Scope every join to the same block and pool, or one bot's legs will match trades in unrelated pools. The next exercise in the module computes the bot's profit from the legs: in its sample of 30 legs, the same 0xae2fc483... address is behind 14 of the 15 sandwiches.

Query 6: Count backruns per pool

From WizardCamp's MEV & Order Flow module ("Backrun Frequency by Pool", part 6 of the Ethereum path).

SQL concept: LAG over a window partitioned by pool and block. Dune table: dex.trades.

A backrun is a trade whose immediately previous trade in the same pool and block, ordered by evt_index, came from a different sender in the opposite direction. Count backruns per pool.

WITH ordered AS (SELECT project_contract_address, tx_from, token_bought_address, token_sold_address, LAG(tx_from) OVER w AS prev_from, LAG(token_bought_address) OVER w AS prev_bought, LAG(token_sold_address) OVER w AS prev_sold FROM dex_trades WINDOW w AS (PARTITION BY project_contract_address, block_number ORDER BY evt_index)) SELECT project_contract_address AS pool, COUNT(CASE WHEN tx_from <> prev_from AND token_bought_address = prev_sold AND token_sold_address = prev_bought THEN 1 END) AS backrun_count FROM ordered GROUP BY 1 ORDER BY backrun_count DESC, pool ASC

The sample is 50 swaps across 5 pools and 10 consecutive Ethereum blocks, 18,998,130 to 18,998,139. The query finds 14 backruns: 5 in a TRŌLL/WETH pool, 3 in the MICKEY/WETH pool, and 2 each in a MAP/USDT pool, a TROLL/WETH pool and the Uniswap V3 USDC/WETH pool (0x88e6a0c2...).

The lesson: the partition is the whole query. Partition by pool alone and the last trade of one block gets compared with the first trade of the next. Forget the pool and trades in unrelated pools look adjacent. Order by evt_index, because dex.trades has no tx_index. And never group pools by symbol: TROLL and TRŌLL (with a macron) are two different tokens with two different pools, which is exactly why every join and partition here uses addresses.

Query 7: Split Solana DEX volume by aggregator

From WizardCamp's Solana Aggregators and Routing module ("Share of DEX volume routed through each aggregator", Solana path).

SQL concept: a share of total with SUM(...) OVER (). Dune table: dex_solana.trades.

The table holds one week of Solana DEX volume, August 24 to 30, 2026, split by the program that submitted the trade. Return each source's share of the week's volume.

SELECT source_class,
       n_trades,
       n_trades_priced,
       round(volume_usd, 2) AS volume_usd,
       round(volume_usd / sum(volume_usd) OVER (), 4) AS usd_share
FROM dex_source_week
ORDER BY volume_usd DESC
source_classn_tradesn_trades_pricedvolume_usdusd_share
direct69,668,00069,662,7285,722,056,875.440.3257
jupiter23,096,62522,881,8535,466,824,150.950.3112
other_program46,258,90745,595,6493,783,511,866.340.2154
dflow21,324,97221,290,1782,146,226,641.050.1222
okx6,597,7156,597,715277,529,658.930.0158
titan2,323,8922,233,763171,210,501.750.0097

The week totals about $17.57 billion across 169,270,111 swaps.

The lesson: trade share and volume share tell different stories. Direct trades are 41% of swaps but 33% of volume, while Jupiter routes only 14% of swaps and 31% of volume, because its average priced trade is about $239 against about $82 for direct trades. The gap between n_trades and n_trades_priced is the other trap: SUM(amount_usd) skips swaps with no USD price without telling you, and 214,772 Jupiter swaps have none. Our Solana SQL tutorial covers the rest of the Solana data model.

The 7 DeFi SQL patterns at a glance

#QuerySQL conceptDeFi lesson
1WETH/USDC execution priceCASE WHEN on directionEvery pair appears in two directions
2Swap size outliersPERCENTILE_CONT, join backUse the median per project and day, and keep multi-hop rows
3Average swap size by chainRatio of sumsNever average daily averages
4Aave supply vs borrowSUM(CASE WHEN ...)Events are flows, not balances
5Sandwich victimsThree way self joinThe join conditions are the definition of the attack
6Backruns per poolLAG by pool and blockPartition by pool and block, and match on addresses
7Solana aggregator shareSUM(...) OVER ()Trade share and volume share differ, and unpriced swaps vanish

Is DeFi analytics a good skill for a crypto data job?

Yes, especially paired with SQL. As of November 29, 2026, the Unchain Data job board lists 287 live data roles. 22 of them (8%) mention DeFi, at 17 companies including 1inch, Coinbase, Keyrock, Ondo Finance, Robinhood and Wintermute. 16 of those 22 DeFi roles (73%) also ask for SQL, against 60% of all live data roles.

The DeFi roles are mostly data scientist, data engineer, research and head of data positions, with titles like DeFi Analyst at RockawayX and Data & Analytics Lead at 1inch. Few are labeled "data analyst": only 2 of the 43 live roles in our Data Analyst category mention DeFi. Like Ethereum SQL, DeFi analytics is something you prove in a take home test or a portfolio dashboard rather than a keyword you need on your CV. You can browse live roles on the Web3 data analyst job board, and practice the interview side with our crypto data analyst interview questions.

What to learn after these 7 queries

After these seven DeFi analytics SQL queries, learn lending balances and liquidations, then build one protocol dashboard from start to finish. When you start applying, add a portfolio and interview practice, using the links below in that order.

  1. The basics, if you skipped them. The Dune SQL tutorial covers daily DEX volume by project, decimals and stablecoin market share, and the Ethereum SQL tutorial covers blocks, tokens and traces.
  2. Lending in depth. The rest of WizardCamp's DeFi Analytics part covers net supply positions, outstanding debt and bad debt, and the Solana path adds Kamino and marginfi liquidations.
  3. A protocol dashboard. Our guide on how to build a Dune dashboard for a DeFi protocol turns these patterns into a dashboard, and how to query blockchain data without bad metrics covers the double counting traps.
  4. The career side. How to Become a Crypto Data Analyst covers portfolios and where to apply, and Best Blockchain Analytics Courses compares your learning options.

Queries 1 and 2 sit in part 4 of the Ethereum path, which counts toward WizardCamp's Ethereum Blockchain Foundations certificate. Queries 5 and 6 sit in part 6, which counts toward the Advanced Ethereum Analyst certificate. Queries 3 and 4 belong to the Uniswap Analytics and Aave Lending packs, each with its own certificate, and query 7 counts toward Advanced Solana Analyst. WizardCamp has 163 graded exercises on real Ethereum and Solana data, and if you want to learn onchain SQL for DeFi roles, it is the best place to practice, because every exercise runs on real chain data and the grader shows you exactly which rows are wrong.

Frequently Asked Questions

Can you do DeFi analytics with SQL?

Yes. Dune, Allium, Flipside and other platforms decode DeFi events into SQL tables, so you can query swaps, liquidity and lending activity with standard SQL. On Dune, dex.trades covers swaps across most EVM DEXs, dex_solana.trades covers Solana, and Spellbook tables like dex.sandwiches cover MEV.

What is dex.trades on Dune?

dex.trades is Dune's curated table of DEX swaps on EVM chains, with one row per swap. It includes the project, pool address, tokens bought and sold, decimal adjusted amounts, amount_usd, the trader and the event index. Filter on blockchain and block_date or block_month to keep queries fast.

How do you detect a sandwich attack with SQL?

Join the trades table to itself three times. The front and back legs share a block, pool and sender, run in opposite directions in different transactions, and have at least one event between them. A victim is another sender trading in the front leg's direction between the two legs. On Dune, dex.sandwiches gives you detected legs to check your logic against.

What is the difference between DeFi analytics and blockchain analytics?

DeFi analytics measures protocols: volume, liquidity, borrowing, users and MEV. Blockchain analytics often means compliance work, tracing funds and screening wallets for risk. Both use onchain data, but crypto data analyst roles at protocols, funds and exchanges mostly need the DeFi side with SQL.

How long does it take to learn DeFi analytics with SQL?

If you already know SQL and the basics of Dune, you can work through the seven queries in this guide in two or three sessions. If you are new to onchain data, start with WizardCamp's free SQL Foundations module and the Ethereum basics, then move to DEX trades, lending and MEV.

How is this different from the Dune SQL tutorial and the learn onchain SQL post?

The Dune SQL tutorial is Dune syntax and the first ten query patterns. The learn onchain SQL post is how WizardCamp works. This post is a DeFi analytics with SQL tutorial: seven graded queries on dex.trades, lending tables and MEV, with the real results and the traps.

Key Takeaways

  • Start with dex.trades. One row per swap, amount_usd already computed, and a blockchain and date filter on every query.
  • Handle both directions of every pair, and keep multi-hop rows that share a hash.
  • Use medians and ratios of sums. DeFi volume is heavy tailed, and averages of averages lie.
  • Events are flows, not balances. Utilization and TVL need outstanding positions.
  • MEV is a join problem. Same block, same pool, opposite directions, ordered by evt_index, matched on addresses.
  • DeFi roles want SQL. As of November 29, 2026, 16 of the 22 live data roles on the Unchain Data job board that mention DeFi also ask for SQL.

Looking for blockchain data engineering instead? Check out our blockchain data engineering guide.

Practice these 7 DeFi queries on WizardCamp →

Vincent Charles

Vincent Charles

  • Founder of Unchain Data
  • Former data lead at Morpho Labs and Binance
  • Builds Dune dashboards and data pipelines across Ethereum, Solana and Sui
  • Advises VC funds and DeFi protocols on data strategy
  • Featured on BBC for blockchain data research

Ready to practice what you just read?

WizardCamp has interactive SQL exercises on real blockchain data. Write queries, get instant feedback, earn certificates.

Explore WizardCamp