Topspin exists to make sharing sports statistics fun. The topspin query language (tql) exists to query sports data, embed that data into blog posts or dedicated visualizations, and share that content with the internet. This documentation serves to describe the capabilities and usage of tql. Send any feedback to @joe307bad on x.
from nfl.players
where position = QB and season >= 2015 and dropbacks >= 300
select rank, player, team, season, dropbacks,ratio(pass_epa, dropbacks), cpoe, cpoe_percentile
orderbyratio(pass_epa, dropbacks) desclimit 25
answers with # · Player · Team · Season · DB · PaEPA / DB · CPOE · CPOE %ile
Every start scored 0 to 100 against the other quarterbacks who played that week, with a dash for any week he took fewer than 20 dropbacks: a bye, an injury, or a day on the bench.
from nfl.player_weeks
where season = 2025 and position = QB and dropbacks >= 20
select player, week,percentile(sum(pass_epa))
groupby player, week
pivotby week
limit 32
Rate, park-adjusted value and total wins scored as one number over 500 plate appearances, so the top takes being good in all three ways.
from mlb.hitters
where season >= 2015 and pa >= 500
select player, team, season, pa, ops, wrc_plus, war,composite(ops, wrc_plus, war)
orderbycomposite(ops, wrc_plus, war) desclimit 25
answers with Player · Team · Season · PA · OPS · wRC+ · WAR · OPS + wRC+ + WAR composite
Every season since 2000 in the 99th percentile of WAR among 150-inning pitchers, a bar that moves with the era instead of sitting at a fixed win total.
from mlb.pitchers
where season >= 2000 and ip >= 150
select player, team, season, ip, era, fip, war, war_percentile
keep war_percentile >= 99
orderby war desclimit 50
answers with Player · Team · Season · IP · ERA · FIP · WAR · WAR %ile
The 100 highest-scoring games since 1996, beside where each night's true shooting ranked that season, because volume and efficiency are not the same night.
from nba.player_games
where season >= 1996 and minutes >= 20
select season, game_date, player, team, minutes, pts, ts_pct, ts_pct_percentile
orderby pts desclimit 100
answers with Season · Date · Player · Team · MIN · PTS · TS% · TS% %ile
33 of them work on every table; 10 need something of the table they are asked of — a date column to read a
period off, a column the table says is its biggest — and each says which
tables have it. 1 clause is written in a workspace query, over the answers of the queries in a folder
rather than over a table.
Reading a table
fromclauseevery table
from <league>.<table>
The one table a query reads
Every query names its relation once. from mlb reads that league's default table; naming the table outright is what the rest of the document is checked against, so a column that does not exist there is an error while you are still typing rather than a 400 later.
from mlb.hitters
select player, team, season, pa, avg, ops, wrc_plus, war
orderby war desclimit 100
against mlb.hitters
selectclauseevery table
select <column>, <call>, …
The columns the answer carries
Columns of the table, folds over them, percentiles, composites, arithmetic — anything the table can build. Left off, a table shows the columns it says are its default.
from mlb.hitters
select player, team, season, pa, avg, ops, wrc_plus, war
orderby war desclimit 100
against mlb.hitters
asmodifierevery table
select <column> as <heading>
Renames a column's heading and nothing else
A name in this language is canonical: order by, group by, keep, highlight and pivot all go on naming the column the way the table does, and only the heading changes. That is what makes a rename safe — two spellings of one call stay one column.
from mlb.hitters
select player, team, pa as PA
orderby pa desclimit 10
against mlb.hitters
letclauseevery table
let <name> = <value> · $<name>
A value written once and referred to as $name
Substituted anywhere a value appears — inside a filter, a limit, a span, the right-hand side of a benchmark. A document that asks the same question of three seasons changes one line.
let year = 2026
from mlb.hitters
where season =$yearselect player, team, season
orderby pa desclimit 10
against mlb.hitters
limitclauseevery table
limit <n>
How many rows come back
Every table has a ceiling of its own that a query cannot raise, so a limit is a request rather than a promise. The ceiling is listed with the table.
from mlb.hitters
select player, team, season, pa, avg, ops, wrc_plus, war
orderby war desclimit 100
against mlb.hitters
order byclauseevery table
order by <column> asc|desc
Which end of the answer comes first
Any column the query can build, including a fold, a percentile or a piece of arithmetic. desc unless the query says otherwise.
from mlb.hitters
select player, team, season, pa
orderby pa desclimit 10
against mlb.hitters
#modifierevery table
# a note to whoever reads this next
A comment, to the end of the line
Stripped before anything is parsed, so a comment can sit on a clause line or on one of its own.
# Hitter seasons — One row per hitter per season, from FanGraphs' batting leaderboards.from mlb.hitters
select player, team, season, pa, avg, ops, wrc_plus, war
orderby war desclimit 100
against mlb.hitters
Choosing rows
whereclauseevery table
where <column> =|!=|>|>=|<|<= <value>
Chooses the rows the question is about
Runs before anything else, which makes it the clause that chooses the *population*: a percentile ranks within the rows where matched, and narrowing to one player would leave him ranked against himself. That is what keep is for.
from mlb.hitters
where season = 2026
select player, pa
orderby pa desclimit 10
against mlb.hitters
andclauseevery table
and <column> <op> <value>
Continues whichever filter clause came last
On its own line it adds to the where, having, keep or highlight above it, so a long list of conditions reads down the page instead of along one line.
from mlb.hitters
where season = 2026 and pa > 0
select player, pa
orderby pa desclimit 10
against mlb.hitters
havingclauseevery table
having <fold> <op> <value>
Filters the groups a fold made
where chooses rows and runs before the fold; having chooses groups and runs after it. “Players with at least 200 career home runs” is a having, because nothing in a single season's row knows the career total.
from mlb.hitters
select player,sum(pa)
groupby player
havingsum(pa) > 0
orderbysum(pa) desclimit 10
against mlb.hitters
keepclauseevery table
keep <ranked column> <op> <value>
where, moved one layer out — after the ranking
The rows survive with the standing they had among every row the filters matched, which is what makes a one-player card possible. It is also the only filter clause that accepts a percentile, a standing or a composite: those are windows, illegal in a where and perfectly ordinary in a predicate over the select that produced them.
from mlb.hitters
where season = 2026
select player, pa, pa_percentile
keep pa_percentile >= 90
orderby pa_percentile desclimit 10
against mlb.hitters
highlightclauseevery table
highlight <column> <op> <value>
Points at rows instead of choosing them
Written in the same words as a filter and reaching no SQL at all: the rows that came back are the rows that would have come back anyway, and the marked ones are tinted in the table and named in the chart. One line is one rule, and every condition on it has to hold; two lines name two subjects.
from mlb.hitters
select player, season, pa
highlight season = 2026
orderby pa desclimit 10
against mlb.hitters
ofmodifierevery table
where <column> >= <fold>(<column>) of <dimension> <value> · where <column> >= <n>% of <fold>(<column>)
A threshold that is another row rather than a number
“Everyone paid at least what he was paid” is a question nobody can write as a number, because the number is different in every season. The right-hand side is looked up once per population — the same population a percentile ranks within — and max reduces it when the subject turns up more than one row. Leave the row out and it is the leader instead: where dropbacks >= 40% of max(dropbacks) keeps the passers with at least 40% of the most dropbacks among the rows the other filters choose, so a qualifier rises as a season goes on and a player who missed half of it drops below the bar by himself. A share in front works on either form, and in having the leader is of the groups: having sum(tgt) >= 35% of max(sum(tgt)).
from mlb.hitters
where pa >=max(pa) of season 2026
select player, pa
orderby pa desclimit 10
against mlb.hitters
Shaping the answer
group byclauseevery table
group by <column>, …
Folds the rows sharing these keys into one
What a sum sums over. Grouping on a display name that two people share would fold two careers into one, so a column that has an identity apart from its label is grouped on the identity and still comes back labelled.
from mlb.hitters
select player,count(*),sum(pa)
groupby player
orderbysum(pa) desclimit 10
against mlb.hitters
thenclauseevery table
<query>
then
<query over its answer>
Folds the answer a second time
Some questions are two folds and cannot be written as one. “How many quarterbacks has each club given more than a hundred dropbacks” needs a row per club-quarterback to apply the threshold, and then a row per club to count the survivors — and folding straight to the club destroys the pairs the count is made of. then closes a stage: everything under it is a query over the rows the lines above it returned, named by their output headings. having filters the groups one fold made; this makes new ones.
from mlb.hitters
select player, season,count(*)
groupby player, season
havingcount(*) > 10
thenselect player,count(*) as Seasons
groupby player
orderbycount(*) desclimit 10
against mlb.hitters
join onclauseworkspace queries
join on <column>, …
Names the columns a workspace's answers are paired by
Only in a workspace query, which is the only place there are answers to pair. Without it the key is inferred — the columns every query in the folder selects — and inferring is wrong twice: when the shared key is finer than the question (two answers keyed by club *and* season, joined on the club) and when one answer is at a coarser grain than another. Writing the key allows the second, so a query holding one row per club is repeated across the many rows of a query holding one per club-quarterback, which is the ordinary business of putting a group's fact beside its detail rows. Exactly one answer may keep several rows per key; only(…) is how the broadcast ones are read.
pivot byclauseevery table
pivot by <dimension>
Reads the answer as a matrix
One column of clubs becomes thirty columns of numbers. Which columns exist is something the *rows* say rather than the plan, so a pivot is one of the four clauses that never compile, with highlight, pair and hint — and a matrix is also a chart: thirty columns along a month are thirty lines.
from mlb.hitters
select player, season,sum(pa)
groupby player, season
pivotby season
limit 25
against mlb.hitters
first / lastclause64 tables
first <n> <unit> · last <n> <unit>
Only part of each career, before anything else runs
The count restarts per player on a player table and per club on a team table, and it counts *distinct* values rather than rows — a pitcher traded in July has two rows for one season, and “his first two seasons” does not mean one season played twice. The units a table counts in are listed with it.
from mlb.hitters
first 3 seasons
select player,sum(pa)
groupby player
orderbysum(pa) desclimit 10
The career total, the season total, the club's total for the month — whatever the group by made a group of. A rate is not added but rebuilt from the two columns it divides, so a folded ERA is the earned runs over the innings rather than the mean of four seasons' ERAs.
from mlb.hitters
select player,sum(pa)
groupby player
orderbysum(pa) desclimit 10
against mlb.hitters
avg(…)callevery table
avg(<column>)
The mean of a stat, with rates rebuilt rather than averaged
A rate that says what it divides folds by adding both sides and dividing once. That is the difference between a career ERA and the average of four season ERAs, in which a three-inning September counts as much as a 180-inning season.
from mlb.hitters
select player,avg(pa)
groupby player
orderbyavg(pa) desclimit 10
against mlb.hitters
min(…)callevery table
min(<column>)
The smallest value in each group
Reaches further than the arithmetic folds: a season and a date sort, so min(season) is a debut and min(game_date) is the first game the group covers.
from mlb.hitters
select player,min(pa)
groupby player
orderbymin(pa) desclimit 10
against mlb.hitters
max(…)callevery table
max(<column>)
The largest value in each group
min's twin, and the way a folded span says which seasons it folded. It cannot say *whose* the biggest number was — picking a row is not arithmetic — which is what top is for.
from mlb.hitters
select player,max(pa)
groupby player
orderbymax(pa) desclimit 10
against mlb.hitters
count(…)callevery table
count(*) · count(<column>)
How many rows a group swallowed
count(*) counts the rows themselves; count(<column>) counts the ones where that column has a value. The denominator of most rates a query writes for itself.
from mlb.hitters
select player,count(pa)
groupby player
orderbycount(pa) desclimit 10
against mlb.hitters
distinct(…)callevery table
distinct(<column>) · count(distinct <column>)
How many different values a group holds
count(passer) over Pittsburgh's plays is fifteen thousand snaps, because it counts rows. distinct(passer) is the number of quarterbacks who threw them, because it counts values. Also spelled count(distinct passer), which is the same column under the same name.
from mlb.hitters
select player,distinct(season)
groupby player
orderbydistinct(season) desclimit 10
against mlb.hitters
only(…)callevery table
only(<column>)
The one value in the group, and an error if there are two
For the column that is a fact about the group rather than something to fold: a club's win percentage standing beside each of its quarterbacks. sum is wrong about it and avg is right only by accident, and neither says so. only says what was meant — there is one value here — and fails loudly when a group turns out to hold more, which is a grain mistake caught rather than averaged away.
from mlb.hitters
where season = 2026
select player,only(season)
groupby player
orderbyonly(season) desclimit 10
against mlb.hitters
latest(…)callevery table
latest(<column>)
The newest row's value, rather than a number
Which club a player ended at, without splitting his career into one row per club. Not arithmetic but a row picked by recency, so only a table that says which of its rows is newest has it.
from mlb.hitters
select player,latest(player)
groupby player
orderbycount(*) desclimit 10
against mlb.hitters
top(…)call19 tables
top(<column>)
The value on the group's biggest row
max(salary) says what the biggest number was and cannot say whose it was. top(player) picks the row the table calls its biggest, so select max(salary), top(player) answers both halves of the question at once.
from mlb.arbitration
select player,top(player)
groupby player
orderbycount(*) desclimit 10
The plain arithmetic mean, whatever the column says about itself
avg on a rate rebuilds the division, which is right for a career number and wrong for “what was his average game”. mean counts a three-minute appearance exactly once, like a start — the less defensible number more often than not, which is why it has to be asked for by name.
from mlb.hitters
select player,mean(pa)
groupby player
orderbymean(pa) desclimit 10
against mlb.hitters
median(…)callevery table
median(<column>)
The middle value in the group — half above it, half below
The summary to reach for when the column has a long tail on one side, because a mean does not survive one: a pitch that missed its target by a hundred inches is a glove the camera lost rather than a pitch, and it drags a mean the way a hundred good pitches cannot drag it back. It is also the one fold that cannot be rebuilt from parts — two medians do not combine into a third — so a table that publishes one, like mlb.command, computes it rather than folding it, and this is how to ask for the same number at a grain that table does not carry.
from mlb.hitters
select player,median(pa)
groupby player
orderbymedian(pa) desclimit 10
against mlb.hitters
mode(…)callevery table
mode(<column>)
The commonest value in the group
latest(team) is where a traded player ended the season; mode(team) is where he spent it, and a season summary usually means the second.
from mlb.hitters
select player,mode(player)
groupby player
orderbycount(*) desclimit 10
against mlb.hitters
Time
year(…)call26 tables
year(<date column>)
Reads a date as the year it falls in
The calendar year a date falls in — the coarsest period, and the one that differs from a season wherever a sport's season spans two years. No table declares a period column: every date column of every table can be read as one, so a period groups, sorts and filters like any other dimension.
from mlb.pitcher_games
select player,year(game_date),sum(bf)
groupby player,year(game_date)
orderbyyear(game_date) asclimit 20
Three months at a time, written 2024-Q2. Long enough to smooth a slump and short enough to still be inside one season. No table declares a period column: every date column of every table can be read as one, so a period groups, sorts and filters like any other dimension.
from mlb.pitcher_games
select player,quarter(game_date),sum(bf)
groupby player,quarter(game_date)
orderbyquarter(game_date) asclimit 20
The month a date falls in, written 2024-06. The period most questions about a stretch of a season mean. No table declares a period column: every date column of every table can be read as one, so a period groups, sorts and filters like any other dimension.
from mlb.pitcher_games
select player,month(game_date),sum(bf)
groupby player,month(game_date)
orderbymonth(game_date) asclimit 20
The ISO week, written 2024-W23. The finest period a date can be read as, and the one that lines up across sports whose weeks are not numbered the same way. No table declares a period column: every date column of every table can be read as one, so a period groups, sorts and filters like any other dimension.
from mlb.pitcher_games
select player,week(game_date),sum(bf)
groupby player,week(game_date)
orderbyweek(game_date) asclimit 20
Not the month alone but the season so far: grouped by a period, it accumulates along that period. A rate accumulates both of its sides and divides once at the end, so a season-to-date rate is weighted by the playing time behind it rather than by the number of months.
from mlb.pitcher_games
where season = 2026
select player,month(game_date),as_of(bf)
groupby player,month(game_date)
orderbymonth(game_date) asclimit 25
Ranked over every row the filters matched, counting only the rows that have a value — so a stat half the table is missing does not compress everybody into the top half. 100 is always the good end, whichever direction the stat reads. The population has to be pinned first, because a season ranked against all of history is not a stricter answer but a wrong one.
from mlb.hitters
where season = 2026
select player, pa, pa_percentile
orderby pa_percentile desclimit 10
against mlb.hitters
percentile(…)callevery table
percentile(<fold>) · percentile(<fold> lower)
Where a folded group ranks among the other groups
The suffix ranks a row; this ranks what a fold made. When the query groups by part of the population rather than pinning it — a month, a season — the window partitions by those keys, so each month's clubs are ranked among themselves.
Which end is the good one comes from the stat, so a hundred lands on the good end without being asked for. count(*) is the one fold with no opinion — counting a club's home runs is an achievement and counting the quarterbacks it has had to try is the opposite — so a second word may name it: percentile(count(*) lower) puts the club with the most at zero. It overrides a declared end too, on the rare reading that wants the other one.
from mlb.hitters
select player,sum(pa),percentile(sum(pa))
groupby player
orderbysum(pa) desclimit 10
against mlb.hitters
standing(…)callevery table
standing(<column>) · standing(<column> lower)
The same window, read as a place — 1 being best
standing(wrc_plus) is 1 for the league leader. Ties genuinely tie, and the direction follows what the stat says about which end is good, so a standing of 1 is an achievement whether the number is large or small. Where the column has no such opinion — count(*) — a second word names it, exactly as it does for a percentile: standing(count(*) lower) makes first place the club that has needed the fewest.
from mlb.hitters
where season = 2026
select player, pa,standing(pa)
orderby pa desclimit 10
against mlb.hitters
composite(…)call62 tables
composite(<stat>, <stat>, …)
One 0-100 score standing for several stats at once
The mean of the parts' percentiles, ranked over every row the filters matched. Fold the parts — composite(sum(war), avg(era)) — and it scores a span of seasons rather than a single one, in which case the population is the groups and nothing needs pinning. A weight is a share rather than a coefficient.
from mlb.hitters
where season = 2026
select player, games, pa,composite(games, pa)
orderbycomposite(games, pa) desclimit 10
For the rates a single fold cannot produce — ratio(sum(games), count(*)) is games per season. Both sides fold or neither does, a zero denominator reads empty rather than failing, and the division is done in decimal rather than in whole numbers.
from mlb.hitters
select player,count(*),ratio(sum(pa),count(*))
groupby player
orderbyratio(sum(pa),count(*)) desclimit 10
against mlb.hitters
calc(…)call62 tables
calc(<expression>)
Arithmetic over any columns the table can build
Four operators and two functions, over names that all resolve through the table — so the shape is open and the vocabulary is closed. calc(standing(a) - standing(b)) is the gap between two rankings, which is the one thing neither a declared column nor a ratio can reach. All the leaves fold or none of them do.
from mlb.hitters
where season = 2026
select player, games, pa,calc(standing(games) - standing(pa))
orderbycalc(standing(games) - standing(pa)) desclimit 10
Prints a column's values as words, changing nothing else
The one call that reaches no SQL and changes no value: the column selects, filters, orders, folds and plots exactly as it did, and the rules are read at the moment a cell becomes text. = on a string compares case-insensitively; the ordering operators are numeric and refuse to compare text.
from mlb.hitters
select player, pa, format(pa,> 0 -> "on the board",<= 0 -> "nothing yet")
orderby pa desclimit 10
against mlb.hitters
pairclauseevery table
pair <column> with <column>, …
Draws two columns of the answer in one
A stat and its percentile are one reading, and a table of twelve stats with their percentiles is twenty-four columns wide. pair war with war_percentile keeps the first column — its heading, its width, its sort — and draws the second inside its cells after the value, wearing whatever it wore on its own: a percentile keeps its badge. Nothing else changes. Both columns are still in the answer under their own names, so order by, a chart and a workspace query see two columns, because two is what there are. A column can move into one other column, and a column others moved into stays where it is; a column may take several.
from mlb.hitters
where season = 2026
select player, pa, pa_percentile
pair pa with pa_percentile
orderby pa desclimit 10
against mlb.hitters
hintclause62 tables
hint <column> as "<text>"
Shows a sentence on a heading when the pointer rests on it
A heading is a word or two, and some columns need a sentence — a composite is one number standing for three stats, and Score says nothing about which three. hint composite(era, fip, war) as "ERA + FIP + WAR" puts the sentence on the heading, shown as the browser's own tooltip when the pointer rests there. Nothing else changes: not the rows, not the cells, not the columns or their order. One line per hint, since the sentence is free text; a column takes one, and on a column that already carries a caveat the hint is what the heading shows.
from mlb.hitters
where season = 2026
select player, games, pa, ab,composite(games, pa, ab) as Score
hintcomposite(games, pa, ab) as "G + PA + AB"
orderbycomposite(games, pa, ab) desclimit 10
Season leaderboards. The only source here carrying wRC+, fWAR, FIP and Def, which is why a night without FanGraphs is recorded as a gap rather than a failure.
Command measured from broadcast video: the catcher's glove detected before the pitch, the centre-field camera solved against the drawn strike zone, and the target inferred from where the pitcher actually throws relative to it. 2024 on, and the only source here that can say where a pitch was *meant* to go. Published under CC BY-NC-SA 4.0.
The R client the NBA pipeline reads the league through, and the publisher of the season assets it reads — the league's own dashboards, box scores, shots and possessions, one file per season rather than a request per game. The same sportsdataverse project as nflverse, and the same idea.
The league's official play-by-play feed — every snap, its participants and its result. The expected-points and win-probability columns are nflfastR's models fitted to it, not anything the NFL publishes.
The open data project the NFL pipeline reads every source through, via its nflreadr R client. The play-by-play build and the weekly box scores are nflfastR's own computation.
Hand-charted advanced tables: pressures, hurries, drops, broken and missed tackles. Charted rather than tracked, which is why it disagrees with Next Gen Stats at the margins.
Expert consensus rankings — the average of many published rankings, with the disagreement between them kept beside it. An opinion rather than a measurement, and the only source here that is about a game not yet played.
The league's own feeds — its stats reports, GameCenter play-by-play, shift charts, standings and records site — read through three undocumented APIs. Every hockey number here is the NHL's except xg, which is nhlscraper's model on the NHL's plays.
The R client the NHL pipeline reads the league's APIs through, and the publisher of the NHL_DB play-by-play snapshots and the expected-goals model on them. Its bundled contract records are the one table here with no league feed behind them.