Reference guide for built-in SQL functions and operators in CockroachDB
CockroachDB supports a comprehensive set of built-in SQL functions and operators for use in scalar expressions, aggregate operations, and window functions.
In the cockroach sql shell, use \hf [function] to get inline help about a specific function.
-- Current timestampSELECT now();SELECT current_timestamp();-- Current dateSELECT current_date();-- Current timeSELECT current_time();-- Statement time (stable within transaction)SELECT statement_timestamp();
-- Add/subtract intervalsSELECT now() + INTERVAL '1 day';SELECT now() - INTERVAL '1 hour';-- Date differenceSELECT age(TIMESTAMP '2024-01-01', TIMESTAMP '2020-01-01');-- Extract partsSELECT extract(year FROM now());SELECT extract(month FROM now());SELECT extract(day FROM now());
-- Format timestampSELECT to_char(now(), 'YYYY-MM-DD HH24:MI:SS');-- Parse string to timestampSELECT to_timestamp('2024-01-25', 'YYYY-MM-DD');-- Truncate to periodSELECT date_trunc('day', now());SELECT date_trunc('hour', now());SELECT date_trunc('month', now());
Perform calculations across sets of rows related to the current row.
Ranking
Offset Functions
Aggregates
-- Row numberSELECT username, created_at, row_number() OVER (ORDER BY created_at) AS rnFROM users;-- Rank with gapsSELECT product, price, rank() OVER (ORDER BY price DESC) AS rankFROM products;-- Dense rank (no gaps)SELECT product, price, dense_rank() OVER (ORDER BY price DESC) AS rankFROM products;
-- Previous row valueSELECT date, amount, lag(amount, 1) OVER (ORDER BY date) AS prev_amountFROM sales;-- Next row valueSELECT date, amount, lead(amount, 1) OVER (ORDER BY date) AS next_amountFROM sales;-- First and last valuesSELECT date, amount, first_value(amount) OVER (ORDER BY date) AS first_amt, last_value(amount) OVER (ORDER BY date) AS last_amtFROM sales;
-- Running totalSELECT date, amount, sum(amount) OVER (ORDER BY date) AS running_totalFROM sales;-- Moving averageSELECT date, amount, avg(amount) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) AS moving_avg_7daysFROM sales;-- Partition by categorySELECT category, product, price, avg(price) OVER (PARTITION BY category) AS category_avgFROM products;