Skip to content

title: BQL Reference description: Beancount Query Language syntax reference ​

BQL Reference ​

BQL (Beancount Query Language) is a SQL-like language for querying beancount ledgers.

Basic Syntax ​

sql
SELECT columns
WHERE condition
GROUP BY columns
ORDER BY columns
LIMIT n

Comments ​

A query may hold /* ... */ comments wherever it may hold whitespace, as in bean-query:

sql
/* Net worth, by currency. */
SELECT sum(position) AS net_worth  /* a total, not a running balance */
WHERE account ~ '^(Assets|Liabilities):'

A comment may span lines and end the query without a newline after it. It does not nest (the first */ closes it), text inside a string is never a comment, and an unclosed /* is an error.

-- is not a comment, in bean-query or here: SELECT 3--2 is 3 - -2. Text other than whitespace and comments after the ; that ends a query is an error; bean-query drops it without a word.

SELECT Clause ​

Columns ​

sql
/* Basic columns */
SELECT account, date, narration, payee, position

/* All columns */
SELECT *

/* Expressions */
SELECT account, sum(position) AS total

/* Functions */
SELECT year(date), month(date), sum(cost(position))

Available Columns ​

Each row in a default SELECT is one posting from one transaction. The columns below are evaluated against that pair. Posting-level columns vary across postings in the same transaction; transaction-level columns are identical for every posting in a given transaction. A ? after a type means the column may be NULL. StringSet columns are queried with IN / NOT IN, not = or ~.

Transaction columns

ColumnTypeDescription
dateDateTransaction date
flagStringTransaction flag (*, !, etc.)
payeeString?Transaction payee, or NULL
narrationStringTransaction narration
descriptionString"payee | narration" if payee set, else narration
tagsStringSetAll #tag values on the transaction
linksStringSetAll ^link values on the transaction
accountsStringSetThe accounts of every posting in the transaction, sorted, each once
year, month, dayIntegerDate parts (shortcuts for year(date) etc.)
idInteger?Stable directive index (matches Python beancount's id)
typeStringAlways "transaction" for default SELECT
entryObjectWhole transaction as a structured object (date, flag, payee, narration, tags, links, meta, accounts)

Posting columns

ColumnTypeDescription
accountStringThis posting's account
other_accountsStringSetThe accounts of every other posting in the transaction, sorted, each once
positionPosition?Units + cost (when present)
unitsAmount?Just the units (number + currency)
numberNumber?The numeric part of units
currencyString?The currency part of units
costAmount?Per-posting cost basis, total
cost_numberNumber?Per-unit cost ({} syntax)
cost_currencyString?Cost currency
cost_dateDate?Cost lot date
cost_labelString?Cost label
has_costBooleanWhether this posting carries a cost
weightAmount?Cost-converted amount used for balancing
priceAmount?Posting's @/@@ price annotation
posting_flagString?Per-posting flag, distinct from the transaction's flag
metaMetadataThis posting's metadata (see Metadata Functions)

Cumulative / contextual columns

ColumnTypeDescription
balanceInventory?Cumulative running total across WHERE-filtered postings (matches bean-query; an AVERAGE account is shown as its pool, see below)
account_balanceInventory?Per-account running balance, independent of WHERE. Within a transaction it follows booking: a sale never reduces a lot bought earlier in the same transaction (see below)

account_balance realizes lots through the booking engine, the same way report balances does. Booking reads each sale against the inventory before its transaction plus the transaction's earlier sales, never its purchases, so the row for a posting shows the account after the transaction's postings up to and including it, read that way. For an AVERAGE account or a {*} sale, a purchase written earlier in the same transaction therefore stays out of the pool the sale is taken from, matching the cost the journal books the sale at. balance adds positions as bean-query does, except for an AVERAGE account's.

An AVERAGE account is shown as its pool on every surface, before a sale and after one: BALANCES, sum(position), balance, account_balance, JOURNAL and report balances. A pool is one lot per commodity, cost currency and side (long or short), undated, at the weighted-average cost of the lots it holds; X held at a USD cost and at a EUR cost are two pools. Booking is unchanged underneath: the dated lots stay for report capgains. In balance, an AVERAGE account's rows are realized as sum(position) realizes them (below), so after a sale it shows the pool that remains, not the lots bought plus the sale as a negative lot.

Source location columns

ColumnTypeDescription
filenameString?Source file the directive came from
linenoInteger?Line number in that file
locationString?"filename:lineno" shortcut

Attribute access ​

A structured value takes .name to read one of its fields, as in bean-query. Attributes chain, so position.units.number is the number of the posting's units.

ValueAttributes
amount (price, weight, units(...), cost(...), #balances.amount, ...)number, currency
position (position)units (an amount), cost (a cost, NULL without one)
cost (position.cost)number (per unit), currency, date, label
transaction (entry)date, flag, payee, narration, tags, links, meta, accounts
open on #accountsdate, account, currencies, booking, meta
close on #accountsdate, account, meta
date (date, open.date, position.cost.date, ...)year, month, day
sql
SELECT date, position.units.number, position.cost.date WHERE position.cost IS NOT NULL

SELECT account, open.date, close.date FROM #accounts

An attribute an amount, position or date does not have is an error. On a structured object (entry, a cost, open, close) a missing field is NULL, as an absent payee is, and so is a misspelled one. An attribute of NULL is NULL.

Column Aliases ​

sql
SELECT account AS acc, sum(position) AS balance
SELECT year(date), sum(cost(position)) AS "Total spent" GROUP BY 1

Keywords, column names, function names and table names are case-insensitive, as in bean-query: SELECT ACCOUNT reads the account column. An unquoted alias is folded to lower case (AS Total heads the column total). An alias in double quotes keeps its case and may start with a digit or hold spaces (AS "2023"); write "" for a " inside it.

A string in double quotes that is exactly the name of a column of the table being read is that column, in any clause, as in bean-query: SELECT "account" reads the account column (headed "account"), and SELECT "x" FROM (SELECT account AS x) reads the subquery's x. Any other double-quoted string is a string (WHERE account ~ "Cash", SELECT "ACCOUNT"), and a single-quoted one always is. Write single quotes for a string that must stay one, such as a metadata key: meta('account'). In PIVOT BY, a double-quoted name always names a target (PIVOT BY "2023", account).

WHERE Clause ​

Comparison Operators ​

sql
WHERE date = 2024-01-15
WHERE date > 2024-01-01
WHERE date >= 2024-01-01
WHERE date < 2024-12-31
WHERE date <= 2024-12-31
WHERE date != 2024-01-15

String Matching ​

sql
/* Exact match */
WHERE account = "Assets:Bank:Checking"

/* Regex match (case-insensitive by default) */
WHERE account ~ "Assets:Bank"
WHERE narration ~ "coffee"
WHERE payee ~ "Amazon"

Regular Expressions ​

Patterns are Python regular expressions, read as bean-query's Python re reads them: x ~ p is re.search(p, x, re.IGNORECASE), so it matches anywhere in x, ignoring case (anchor it with ^ or $), and x !~ p is its negation. has_account(p) and JOURNAL 'p' match accounts the same way. grep and grepn search case-sensitively, subst is re.sub (groups are \1 or \g<name> in the replacement; $1 is literal text), and findfirst matches from the start of each element, case-sensitively, trying them in sorted order.

A construct Python has and rledger's regex engine cannot express is an error naming it, never a different match: lookahead and lookbehind, backreferences, conditional and atomic groups, possessive quantifiers, \N{...}, and the (?x) flag. subst also refuses a pattern that can match the empty string, which re.sub replaces differently. Two divergences remain, on non-ASCII or multi-line text only: case folding is Unicode simple case folding (Python also matches i with the dotless ı), and $ matches only at the very end, where Python's also matches before a final newline.

\b and \B match where Python's do wherever that can be decided exactly. Python and rledger's regex engine disagree on whether some 13,000 non-ASCII characters are word characters (combining accents written separately, vowel signs, emoji joiners, superscripts, and characters newer than an older Python's Unicode), so a pattern with \b or \B refuses a text holding one of them, naming it (the text contains U+0301 ...), rather than answering differently. On any other text the answer is Python's, in every Python from 3.9 to 3.14. (?a)\b is the ASCII word boundary, which both agree on everywhere: it never refuses. (?a) also makes \d, \s and \w ASCII, and folds only ASCII letters when ignoring case. \B alone on an empty text is refused too, since Python 3.14 matches it there and earlier Pythons do not. In a query, AND and OR stop at a left operand that decides them, as bean-query's do, so flag = '*' AND narration ~ '\bx' only matches the narrations of the rows it keeps.

Logical Operators ​

sql
WHERE account ~ "Assets" AND date >= 2024-01-01
WHERE account ~ "Income" OR account ~ "Expenses"
WHERE NOT account ~ "Equity"

NULL Checks ​

sql
WHERE payee IS NOT NULL
WHERE payee IS NULL

IN Operator ​

IN does scalar membership against a literal list, and set membership against a StringSet column.

sql
/* Scalar in a literal set */
WHERE account IN ("Assets:Bank", "Assets:Cash")
WHERE currency IN ("USD", "EUR")

/* Scalar in a column-valued set */
WHERE "vacation" IN tags
WHERE "Assets:Investments:Cash-USD" IN other_accounts

/* Negated form */
WHERE "draft" NOT IN tags
WHERE account NOT IN ("Equity:Opening", "Equity:Closing")

Set columns ​

tags, links, accounts, and other_accounts are StringSet-typed. Equality (=) and regex (~) don't apply to sets; the only operators that work are IN and NOT IN. To filter a transaction by which other accounts appear on its postings, put the account literal on the left:

sql
/* All dividend postings whose other side(s) include Cash-USD */
SELECT date, narration, account, position
WHERE account ~ '^Income:Investment:Dividend'
  AND 'Assets:Investments:Cash-USD' IN other_accounts

other_accounts is the set of the accounts of every other posting in the same transaction: only the current posting is left out, so its own account still appears when another posting in the transaction also uses it, as in bean-query. That is what makes the "find rows where this posting was paired with X" query work.

GROUP BY Clause ​

sql
SELECT account, sum(position)
GROUP BY account

/* Multiple columns */
SELECT year(date), month(date), sum(position)
GROUP BY year(date), month(date)

/* By position (1-indexed) */
SELECT year(date), sum(position)
GROUP BY 1

ORDER BY Clause ​

sql
ORDER BY date
ORDER BY date DESC
ORDER BY account ASC

/* Multiple columns */
ORDER BY year(date), month(date)

/* By expression */
ORDER BY sum(position) DESC

Amounts sort by currency, then number, so each currency's values stay together: -5.00 EUR, 5.00 EUR, -5 USD, 5 USD. Positions sort by units currency (USD, EUR, JPY, CAD, GBP, AUD, NZD, CHF first, as in beancount, then the rest alphabetically), then cost, then units; an inventory by its positions sorted, compared in turn. NULL sorts first in ascending order.

LIMIT Clause ​

sql
LIMIT 10
LIMIT 100

PIVOT BY Clause ​

Pivot results to create columns from row values:

sql
/* Expenses by category and year, pivoted by year */
SELECT root(account, 2), year(date), sum(cost(position))
WHERE account ~ "Expenses"
GROUP BY 1, 2
PIVOT BY 2

Note: PIVOT BY must reference a SELECT output column, either by name or by its 1-indexed position; pivoting by an arbitrary expression (for example, PIVOT BY YEAR(date)) is not supported.

The new columns are the second column's values sorted by value, NULL first, as bean-query sorts them. The rows follow the query's ORDER BY, applied before the pivot, and are sorted by the first column's values when there is none. LIMIT counts the pivoted rows.

Aggregate Functions ​

FunctionDescription
sum(position)Sum positions
count(*)Count rows
first(x)First value
last(x)Last value
min(x)Minimum value: the first value ORDER BY x would give (NULLs skipped)
max(x)Maximum value: the first value ORDER BY x DESC would give (NULLs skipped)
avg(x)Average value

Examples ​

sql
SELECT account, sum(position) GROUP BY account
SELECT count(*) WHERE account ~ "Expenses"
SELECT min(date), max(date)

min and max work on numbers, strings, dates, booleans (false < true), amounts, positions and inventories, in ORDER BY's order. Amounts compare by currency, then number, so across currencies the result follows the currency order, not size: max(units(position)) over 5 EUR and 3 USD is 3 USD. bean-query answers 5 EUR there; see section 15 of the compatibility notes.

sum(position) over the postings of one AVERAGE account (booking AVERAGE through its open or the ledger's booking_method option; with GROUP BY account, or a WHERE that keeps one account) shows the account's holding the way booking realizes it: the selected postings are replayed through the booking engine, as BALANCES does, and each pool (commodity, cost currency and side) is then shown as one lot at its weighted-average cost. A long and a short stay apart, so 3 X {102 USD} beside -2 X {101 USD} is shown as both, never netted into one lot. Every other sum adds positions, as bean-query does.

When the selected postings cannot be realized on their own, because a WHERE keeps a sale but not enough of the purchases it sold from, the result is the plain sum of those postings: the sale appears as a negative lot at the cost it was booked at, beside the purchases that were kept. balance does the same for those rows, and so does BALANCES for an account partly selected by its FROM or WHERE. Python beancount has no AVERAGE booking, so there is no bean-query answer to compare with.

Window Functions ​

Window functions are a rustledger extension: bean-query has no OVER clause and rejects these queries as a syntax error. A window function gives a value on every posting row, computed over the rows of its window:

sql
SELECT date, account, number,
       row_number() OVER (PARTITION BY account ORDER BY date),
       min(number) OVER (PARTITION BY account ORDER BY date),
       max(number) OVER (PARTITION BY account)
FunctionDescription
row_number()Position of the row in its partition, from 1
rank()Rank by the window's ORDER BY; tied rows share a rank and leave a gap
dense_rank()As rank(), without the gaps
min(x)Minimum of x over the window frame
max(x)Maximum of x over the window frame

OVER takes an optional PARTITION BY list, which splits the rows into independent groups, and an optional ORDER BY list, which orders the rows within each group. Each window function uses its own OVER clause. Window functions cannot be combined with GROUP BY or aggregates, and explicit frames (ROWS BETWEEN ...) are not supported.

min and max use SQL's default frame. Without an ORDER BY the frame is the whole partition, so each row gets the partition's minimum or maximum. With an ORDER BY, the frame runs from the first row of the partition through the current row and the rows that tie with it on the ORDER BY values, so the result is a running minimum or maximum. Values compare as in the aggregate min and max: NULLs are skipped, a frame with nothing else is NULL, and amounts, positions and inventories compare in ORDER BY's order (an amount by currency, then number).

Scalar Functions ​

Date Functions ​

FunctionDescriptionExample
year(date)Extract year2024
month(date)Extract month3
day(date)Extract day15
quarter(date)Extract quarter1
weekday(date)Day-of-week name (Mon..Sun)Fri
today()Current date2024-03-15
yearmonth(date)First of that month, as a date2024-03-01

Amount Functions ​

FunctionDescription
cost(position)Convert to cost basis
units(position)Get units (number + currency)
currency(position)Get currency
commodity(amount)Get the currency of an amount
number(amount)Extract number from amount
neg(x)Negate a number, amount, position or inventory; a position keeps its cost
abs(x)Absolute value of a number, position or inventory; a position keeps its cost
possign(x, account)Flip the sign for a credit-normal account (Income, Liabilities, Equity, including name_* renames), unchanged otherwise; takes a number, amount, position or inventory
filter_currency(x, currency)The positions of a position or inventory held in currency, else NULL; a position gives itself or NULL

Negating or taking the absolute value of an inventory keeps each lot's cost; a lot's exact total is rebuilt as units x per-unit, as after an Inventory::merge.

commodity() and currency() overlap but are not interchangeable. commodity() takes an amount, which is how bean-query spells it, so commodity(units(position)) and commodity(cost(position)) let you ask for the units currency and the cost currency separately — on 2 HOOL {10.00 USD} they return HOOL and USD. currency(position) takes a position and always answers about its units; it is a rustledger extension that bean-query rejects. Prefer commodity() in queries you want to run under both.

cost(position) over the position column is what the posting's units cost, signed like its units, and matches its weight. A lot of 3 X bought at a total cost of 500 USD costs 500, though its per-unit cost is 500/3 rounded, and the sale that empties it costs -500, so an emptied account's sum(cost(position)) is exactly zero. bean-query multiplies the rounded per-unit cost back out and gives 500.0000000000000000000000001. BALANCES AT COST values a held lot at its total the same way, and JOURNAL ... AT COST shows each row's exact cost and a running balance of them. SELECT ... FROM #postings gives the same cost(position) and weight(position) as the default FROM, and so does a subquery that passes the posting column through, as in FROM (SELECT account, position), renamed, nested, or from its SELECT *. A column the subquery computes (units(position) AS position), or one from a DISTINCT or grouped subquery, is a value and has no posting to read: its weight skips any price (units × per-unit for a lot held at cost, else its units), and its cost is units × per-unit, rounded as the per-unit cost is.

cost() of an inventory, such as cost(sum(position)), is an inventory of what each lot cost, per currency, as in bean-query: an account holding 30 USD and 207 EUR of cost gives 207 EUR, 30 USD. sum(position) keeps each lot's exact total, so cost(sum(position)) equals sum(cost(position)) over the same rows. number() of it gives the number when there is one currency and NULL when there are several.

String Functions ​

FunctionDescription
length(str)String length
upper(str)Convert to uppercase
lower(str)Convert to lowercase
root(account, n)First n account segments
leaf(account)Last account segment
parent(account)All but last segment
findfirst(regex, set)First element, in sorted order, that the regex matches from its start, else NULL
grep(regex, str)The part of str the regex matches, else NULL
grepn(regex, str, n)Group n of the regex's match in str, else NULL
subst(regex, replacement, str)str with every match replaced, as Python's re.sub
has_account(regex)True if any posting on the entry has a matching account

has_account() asks about the whole entry, not the current posting, so it is true on every row of a transaction that touches a matching account. It also works as an entry filter: BALANCES FROM has_account('Assets').

A posting column in a FROM filter (account, number, position, ...) is a row filter instead, as in beanquery: FROM account ~ 'Bank' keeps the bank postings only, the same as WHERE account ~ 'Bank', applied after OPEN ON, CLOSE and CLEAR. BALANCES' WHERE filters the postings before they are summed, as bean-query's does, so BALANCES WHERE x is BALANCES FROM x, and both are SELECT account, sum(position) WHERE x GROUP BY account: BALANCES WHERE year = 2024 sums each account's 2024 postings, a sale in 2024 of a lot bought earlier showing as a negative lot. An account every one of whose postings is selected shows its booked total. Because the WHERE reads postings, balance and account_balance are refused there: to filter accounts by their total, use SELECT account, sum(position) ... GROUP BY account HAVING .... PRINT prints whole entries, so it rejects a posting column in its FROM; use PRINT FROM has_account('Bank').

Metadata Functions ​

Beancount metadata can live on a transaction (the line under the header, before any postings) or on a posting (indented one level deeper than the posting itself). BQL exposes three lookup functions because the distinction matters at query time:

FunctionLooks atUse when
meta(key)Posting metadata onlyThe key is set per-posting (e.g. a lot-id on one leg of a transfer)
entry_meta(key)Transaction metadata onlyThe key is set on the transaction header (e.g. a budget-category shared by every posting)
any_meta(key)Posting first, then transactionYou don't know or don't care which level it's set on

All three return NULL when the key is absent at the relevant level — so a WHERE meta('foo') = 'bar' filter quietly drops every row when foo was actually set on the transaction.

getitem(map, key) reads one key of any metadata map, such as entry.meta, and is NULL when the key is absent. With a third argument, getitem(map, key, default) returns default instead, as bean-query does: getitem(entry.meta, 'concept', narration). The default replaces only a missing key, not a key written with no value.

Commodity metadata is separate, because it lives on a commodity directive rather than on any transaction or posting:

FunctionReturns
commodity_meta(currency)The whole metadata map of that currency's commodity directive
commodity_meta(currency, key)One key from it
currency_meta(...)Alias for commodity_meta, same two forms

Both return NULL for a currency with no commodity directive, and for a key that directive does not set. A currency declared more than once resolves to the last declaration.

beancount
2024-01-15 * "Grocery Store"
  budget-category: "food"          ; on the transaction
  Expenses:Food:Groceries  85.00 USD
    receipt-id: "R-12345"          ; on this posting only
  Assets:Bank:Checking
sql
/* Doesn't match: budget-category is on the transaction, not the posting. */
SELECT account WHERE meta('budget-category') = 'food'

/* Matches every posting in the transaction. */
SELECT account WHERE entry_meta('budget-category') = 'food'

/* Matches whichever level happens to carry the key. */
SELECT account WHERE any_meta('budget-category') = 'food'

/* Matches only the Expenses posting, since receipt-id is per-posting. */
SELECT account WHERE meta('receipt-id') = 'R-12345'

This mirrors Python bean-query's meta / entry_meta / any_meta exactly, so queries are portable between the two engines.

To ask whether a key is set at all, test the map for the key with IN. Like bean-query, IN on a metadata map looks at its keys, on the posting's meta, on entry.meta, and on the meta columns of the system tables:

sql
/* Postings that carry a receipt-id, whatever its value. */
SELECT account WHERE 'receipt-id' IN meta

/* Transactions with no budget-category on the header. */
SELECT DISTINCT narration WHERE 'budget-category' NOT IN entry.meta

IN on the entry column is the one divergence from bean-query: the column is a structured object here, so 'narration' IN entry asks whether the entry HAS a narration field, where bean-query searches its field values. Metadata maps are what IN is written against.

Examples ​

sql
/* Expense by category */
SELECT root(account, 2) AS category, sum(cost(position))
WHERE account ~ "Expenses"
GROUP BY category

/* Monthly totals */
SELECT year(date) AS y, month(date) AS m, sum(cost(position))
GROUP BY y, m
ORDER BY y, m

Position and Amount ​

BQL distinguishes between:

  • Position: Amount with cost basis (e.g., 10 AAPL {150.00 USD})
  • Amount: Simple number with currency (e.g., 1500.00 USD)

Converting Positions ​

sql
/* Get cost in operating currency */
SELECT sum(cost(position))

/* Get units (number + currency) */
SELECT sum(units(position))

/* Get currency */
SELECT currency(position)

Date Literals ​

Dates without quotes:

sql
WHERE date = 2024-01-15
WHERE date >= 2024-01-01 AND date < 2024-04-01

Date Arithmetic ​

A date takes a whole number of days on either side of +, and gives a date back:

sql
WHERE date >= 2026-07-01 AND date < 2026-07-01 + 365
SELECT 2026-07-01 - 30 AS a_month_earlier

Subtracting one date from another gives the number of days between them:

sql
SELECT max(date) - min(date) AS days_covered

The count has to be whole. 2026-07-01 + 0.5 is an error rather than a guess, because a date has day resolution; a whole-valued decimal such as 30.0 is fine. date_add(date, days) spells the same shift as a function, and date + interval(n, 'day') spells it with the unit named -- interval also takes week, month, quarter and year.

Filtering by Tag ​

sql
WHERE "vacation" IN tags
WHERE "project" IN tags
sql
WHERE "trip-2024" IN links

PRINT ​

PRINT writes entries back as ledger text, each in rledger format's canonical form, with postings aligned within the entry:

sql
PRINT FROM has_account('Assets:Bank') OPEN ON 2024-01-01

It prints the entries the FROM clause leaves. OPEN ON gives the open directives still active at the date, the last price of each currency pair, the opening-balance summaries, and every entry from the date on. CLOSE ON cuts off at the date, and CLOSE and CLEAR add their conversion and transfer entries. The filter reads each entry, whatever its type, the way the #entries table does: narration is NULL on an open, and has_account(regex) matches the accounts the entry names.

Subqueries ​

A subquery can be used as the source of a FROM clause:

sql
SELECT account, total
FROM (SELECT account, sum(position) AS total GROUP BY account)

Examples ​

Account Balances ​

sql
SELECT account, sum(position)
GROUP BY account
ORDER BY account

Monthly Expenses ​

sql
SELECT year(date), month(date), sum(cost(position))
WHERE account ~ "Expenses"
GROUP BY 1, 2
ORDER BY 1, 2

Top Spending Categories ​

sql
SELECT root(account, 2), sum(cost(position))
WHERE account ~ "Expenses"
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10

Transactions with Payee ​

sql
SELECT date, payee, narration, account, position
WHERE payee ~ "Amazon"
ORDER BY date DESC

Net Worth ​

sql
SELECT sum(cost(position))
WHERE account ~ "Assets" OR account ~ "Liabilities"

Year-over-Year ​

sql
/* Run separate queries for each year */
SELECT root(account, 2), sum(cost(position)) AS "2023"
WHERE account ~ "Expenses" AND year(date) = 2023
GROUP BY 1
ORDER BY 1

SELECT root(account, 2), sum(cost(position)) AS "2024"
WHERE account ~ "Expenses" AND year(date) = 2024
GROUP BY 1
ORDER BY 1

Output Formats ​

bash
# Text (default)
rledger query ledger.beancount "SELECT ..."

# CSV
rledger query -f csv ledger.beancount "SELECT ..."

# JSON
rledger query -f json ledger.beancount "SELECT ..."

Tips ​

Use Regex for Account Matching ​

sql
/* Match all bank accounts */
WHERE account ~ "Assets:Bank"

/* Match any asset */
WHERE account ~ "^Assets:"

Group by Account Hierarchy ​

sql
/* Top-level categories */
SELECT root(account, 1), sum(position) GROUP BY 1

/* Two levels deep */
SELECT root(account, 2), sum(position) GROUP BY 1

Date Range Filtering ​

sql
/* This year */
WHERE year(date) = year(today())

/* This month */
WHERE year(date) = year(today()) AND month(date) = month(today())

/* Specific date range */
WHERE date >= 2024-01-01 AND date < 2024-02-01

See Also ​