PGBENCH(1)
Okay bestie, this is PGBENCH(1) โ aka pgbench โ from the PostgreSQL 14.24 Documentation. Benchmark queen behavior, honestly. ๐
โจ NAME โจ
pgbench โ run a benchmark test on PostgreSQL. That's the whole vibe. ๐
๐ฆ SYNOPSIS ๐ฆ
pgbench -i [option...] [dbname]
pgbench [option...] [dbname]
๐ DESCRIPTION ๐
Okay so pgbench is a simple program for running benchmark tests on PostgreSQL. It runs the same sequence of SQL commands over and over, possibly in multiple concurrent database sessions, and then calculates the average transaction rate (transactions per second). Iconic, lowkey. ๐
By default, pgbench tests a scenario that is loosely based on TPC-B, involving five SELECT, UPDATE, and INSERT commands per transaction. But it is easy to test other cases by writing your own transaction script files. Main character flexibility. โจ
Typical output from pgbench looks like this:
transaction type: <builtin: TPC-B (sort of)>
scaling factor: 10
query mode: simple
number of clients: 10
number of threads: 1
number of transactions per client: 1000
number of transactions actually processed: 10000/10000
latency average = 11.013 ms
latency stddev = 7.351 ms
initial connection time = 45.758 ms
tps = 896.967014 (without initial connection time)
The first six lines report some of the most important parameter settings. The next line reports the number of transactions completed and intended (the latter being just the product of number of clients and number of transactions per client); these will be equal unless the run failed before completion. (In -T mode, only the actual number of transactions is printed.) The last line reports the number of transactions per second. Math girlie moment. ๐งฎ๐ธ
The default TPC-B-like transaction test requires specific tables to be set up beforehand. pgbench should be invoked with the -i (initialize) option to create and populate these tables. (When you are testing a custom script, you don't need this step, but will instead need to do whatever setup your test needs.) Initialization looks like:
pgbench -i [ other-options ] dbname
where dbname is the name of the already-created database to test in. (You may also need -h, -p, and/or -U options to specify how to connect to the database server.) ๐ซถ
โ ๏ธ Caution:pgbench -icreates four tablespgbench_accounts,pgbench_branches,pgbench_history, andpgbench_tellers, destroying any existing tables of these names. Be very careful to use another database if you have tables having these names! This is not a drill, bestie. ๐
At the default โscale factorโ of 1, the tables initially contain this many rows:
pgbench_branchesโ1pgbench_tellersโ10pgbench_accountsโ100000pgbench_historyโ0
You can (and, for most purposes, probably should) increase the number of rows by using the -s (scale factor) option. The -F (fillfactor) option might also be used at this point. Highkey useful. ๐ฅ
Once you have done the necessary setup, you can run your benchmark with a command that doesn't include -i, that is:
pgbench [ options ] dbname
In nearly all cases, you'll need some options to make a useful test. The most important options are -c (number of clients), -t (number of transactions), -T (time limit), and -f (specify a custom script file). See below for a full list. ๐
๐ฅ OPTIONS ๐ฅ
The following is divided into three subsections. Different options are used during database initialization and while running benchmarks, but some options are useful in both cases. Slay. โจ
๐ Initialization Options ๐
pgbench accepts the following command-line initialization arguments:
dbnameโ Specifies the name of the database to test in. If this is not specified, the environment variablePGDATABASEis used. If that is not set, the user name specified for the connection is used. Environment variable fallback chain, we love her. ๐-i,--initializeโ Required to invoke initialization mode.-I init_steps,--init-steps=init_stepsโ Perform just a selected set of the normal initialization steps.init_stepsspecifies the initialization steps to be performed, using one character per step. Each step is invoked in the specified order. The default isdtgvp. The available steps are:d(Drop) โ Drop any existingpgbenchtables.t(create Tables) โ Create the tables used by the standardpgbenchscenario, namelypgbench_accounts,pgbench_branches,pgbench_history, andpgbench_tellers.gorG(Generate data, client-side or server-side) โ Generate data and load it into the standard tables, replacing any data already present.- With
g(client-side data generation), data is generated inpgbenchclient and then sent to the server. This uses the client/server bandwidth extensively through aCOPY. Usinggcauses logging to print one message every100,000rows while generating data for thepgbench_accountstable. - With
G(server-side data generation), only small queries are sent from thepgbenchclient and then data is actually generated in the server. No significant bandwidth is required for this variant, but the server will do more work. UsingGcauses logging not to print any progress message while generating data. - The default initialization behavior uses client-side data generation (equivalent to
g).
- With
v(Vacuum) โ InvokeVACUUMon the standard tables.p(create Primary keys) โ Create primary key indexes on the standard tables.f(create Foreign keys) โ Create foreign key constraints between the standard tables. (Note that this step is not performed by default.)
-F fillfactor,--fillfactor=fillfactorโ Create thepgbench_accounts,pgbench_tellersandpgbench_branchestables with the given fillfactor. Default is100.-n,--no-vacuumโ Perform no vacuuming during initialization. (This option suppresses thevinitialization step, even if it was specified in-I.)-q,--quietโ Switch logging to quiet mode, producing only one progress message per 5 seconds. The default logging prints one message each100,000rows, which often outputs many lines per second (especially on good hardware). This setting has no effect ifGis specified in-I.-s scale_factor,--scale=scale_factorโ Multiply the number of rows generated by the scale factor. For example,-s 100will create10,000,000rows in thepgbench_accountstable. Default is1. When the scale is20,000or larger, the columns used to hold account identifiers (aidcolumns) will switch to using larger integers (bigint), in order to be big enough to hold the range of account identifiers. Big numbers, big slay. ๐ข๐--foreign-keysโ Create foreign key constraints between the standard tables. (This option adds thefstep to the initialization step sequence, if it is not already present.)--index-tablespace=index_tablespaceโ Create indexes in the specified tablespace, rather than the default tablespace.--partition-method=NAMEโ Create a partitionedpgbench_accountstable withNAMEmethod. Expected values arerangeorhash. This option requires that--partitionsis set to non-zero. If unspecified, default isrange.--partitions=NUMโ Create a partitionedpgbench_accountstable withNUMpartitions of nearly equal size for the scaled number of accounts. Default is0, meaning no partitioning.--tablespace=tablespaceโ Create tables in the specified tablespace, rather than the default tablespace.--unlogged-tablesโ Create all tables as unlogged tables, rather than permanent tables.
๐ Benchmarking Options ๐
pgbench accepts the following command-line benchmarking arguments:
-b scriptname[@weight],--builtin=scriptname[@weight]โ Add the specified built-in script to the list of scripts to be executed. Available built-in scripts are:tpcb-like,simple-updateandselect-only. Unambiguous prefixes of built-in names are accepted. With the special namelist, show the list of built-in scripts and exit immediately. Optionally, write an integer weight after@to adjust the probability of selecting this script versus other ones. The default weight is1. See below for details.-c clients,--client=clientsโ Number of clients simulated, that is, number of concurrent database sessions. Default is1.-C,--connectโ Establish a new connection for each transaction, rather than doing it just once per client session. This is useful to measure the connection overhead. Connection overhead? We're measuring her. ๐ญ-d,--debugโ Print debugging output.-D varname=value,--define=varname=valueโ Define a variable for use by a custom script (see below). Multiple-Doptions are allowed.-f filename[@weight],--file=filename[@weight]โ Add a transaction script read fromfilenameto the list of scripts to be executed. Optionally, write an integer weight after@to adjust the probability of selecting this script versus other ones. The default weight is1. (To use a script file name that includes an@character, append a weight so that there is no ambiguity, for examplefilen@me@1.) See below for details.-j threads,--jobs=threadsโ Number of worker threads withinpgbench. Using more than one thread can be helpful on multi-CPU machines. Clients are distributed as evenly as possible among available threads. Default is1.-l,--logโ Write information about each transaction to a log file. See below for details.-L limit,--latency-limit=limitโ Transactions that last more thanlimitmilliseconds are counted and reported separately, as late. When throttling is used (--rate=...), transactions that lag behind schedule by more thanlimitms, and thus have no hope of meeting the latency limit, are not sent to the server at all. They are counted and reported separately as skipped. Late and skipped are different categories, bestie. Keep up. ๐โจ-M querymode,--protocol=querymodeโ Protocol to use for submitting queries to the server:simple: use simple query protocol.extended: use extended query protocol.prepared: use extended query protocol with prepared statements.
In prepared mode, pgbench reuses the parse analysis result starting from the second query iteration, so pgbench runs faster than in other modes. The default is simple query protocol. (See Chapter 53 for more information.)
-n,--no-vacuumโ no vacuuming before the test runs, periodt. You literally need this if you're running a custom test scenario that doesn't include the standard tablespgbench_accounts,pgbench_branches,pgbench_history, andpgbench_tellers. ๐-N,--skip-some-updatesโ runs the built-in simple-update script. It's just shorthand for-b simple-update, bestie. โจ-Psec,--progress=secโ shows a progress report every sec seconds ๐. The report gives you the time since the run started, the TPS since the last report, and the transaction latency average + standard deviation since the last report. Under throttling (-R), the latency is computed against the transaction's scheduled start time, not when it actually began โ so it also folds in the average schedule lag time. iykyk.-r,--report-latenciesโ after the benchmark finishes, reports the average per-statement latency (that's execution time from the client's perspective) for each command ๐. See below for the deets.-Rrate,--rate=rateโ execute transactions targeting the specified rate instead of going as fast as possible (which is the default, no cap fr). The rate is in transactions per second. If your target rate is above the max possible rate, the rate limit won't impact the results at all.
The rate is targeted by starting transactions along a Poisson-distributed schedule time line โจ. The expected start time schedule moves forward based on when the client first started, not when the previous transaction ended. That approach means when transactions go past their original scheduled end time, later ones can totally catch up again. ๐ฆ
When throttling is active, the transaction latency reported at the end of the run is calculated from the scheduled start times โ so it includes the time each transaction had to wait for the previous one to finish. That wait time is called the schedule lag time, and its average and maximum get reported separately too. The transaction latency with respect to the actual transaction start time (i.e. the time spent executing the transaction in the database) can be computed by subtracting the schedule lag time from the reported latency. Math girlie hours ๐ฅ
If --latency-limit is used together with --rate, a transaction can lag behind so much that it's already over the latency limit when the previous transaction ends โ because latency is calculated from the scheduled start time. Those transactions are not sent to the server; they're skipped altogether and counted separately. ๐
A high schedule lag time is a big flashing sign that the system cannot process transactions at the specified rate, with the chosen number of clients and threads. When the average transaction execution time is longer than the scheduled interval between each transaction, each successive transaction falls further behind, and the schedule lag time keeps increasing the longer the test run goes. When that happens, you'll have to reduce the specified transaction rate. Sorry bestie, that's the vibe check. ๐ญ
-sscale_factor,--scale=scale_factorโ report the specified scale factor in pgbench's output. With the built-in tests you don't need this; the correct scale factor is detected by counting the rows in thepgbench_branchestable. But when you're testing only custom benchmarks (the-foption), the scale factor gets reported as1unless you use this option. ๐-S,--select-onlyโ runs the built-in select-only script. Shorthand for-b select-only. Simple as that, queen ๐-ttransactions,--transactions=transactionsโ the number of transactions each client runs. Default is10. โญ-Tseconds,--time=secondsโ run the test for this many seconds instead of a fixed number of transactions per client.-tand-Tare mutually exclusive โ pick one, not both ๐.-v,--vacuum-allโ vacuum all four standard tables before running the test. If you use neither-nnor-v, pgbench will vacuum thepgbench_tellersandpgbench_branchestables, and will truncatepgbench_history. ๐งนโจ--aggregate-interval=secondsโ length of the aggregation interval, in seconds. May be used only with the-loption. With this, the log contains per-interval summary data, as described below. ๐--log-prefix=prefixโ set the filename prefix for the log files created by--log. The default ispgbench_log. ๐๏ธ--progress-timestampโ when showing progress (option-P), use a timestamp (Unix epoch) instead of the number of seconds since the beginning of the run. The unit is seconds, with millisecond precision after the dot. This helps compare logs generated by various tools. ๐ฐ๏ธ--random-seed=seedโ set the random generator seed. This seeds the system random number generator, which then produces a sequence of initial generator states, one for each thread. Values for seed can be:time(the default โ the seed is based on the current time),rand(use a strong random source, failing if none is available), or an unsigned decimal integer value. The random generator gets invoked explicitly from a pgbench script (random...functions) or implicitly (for instance, option--rateuses it to schedule transactions). When explicitly set, the value used for seeding is shown on the terminal. Any value allowed for seed may also be provided through the environment variablePGBENCH_RANDOM_SEED. To ensure the provided seed impacts all possible uses, put this option first or use the environment variable. ๐ฒ
Setting the seed explicitly lets you reproduce a pgbench run exactly โ as far as random numbers are concerned. Since random state is managed per thread, that means the exact same pgbench run for an identical invocation, if there's one client per thread and there are no external or data dependencies. From a statistical viewpoint, reproducing runs exactly is a bad idea, because it can hide the performance variability or improve performance unduly (e.g. by hitting the same pages as a previous run). BUT it may also be a huge help for debugging โ for instance, re-running a tricky case that leads to an error. Use wisely, bestie ๐
--sampling-rate=rateโ sampling rate, used when writing data into the log, to reduce the amount of log generated. If this option is given, only the specified fraction of transactions are logged.1.0means all transactions get logged;0.05means only 5% of transactions get logged. ๐ธ
Remember to take the sampling rate into account when processing the log file! For example, when computing TPS values you need to multiply the numbers accordingly (e.g. with a 0.01 sample rate, you'll only get 1/100 of the actual TPS). Don't let the math lie to you ๐ญ
--show-script=scriptnameโ show the actual code of builtin script scriptname on stderr, then exit immediately. Peek behind the curtain โจ
๐ Common Options ๐
pgbench also accepts the following common command-line arguments for connection parameters:
-hhostname,--host=hostnameโ the database server's host name ๐ฅ๏ธ-pport,--port=portโ the database server's port number ๐-Ulogin,--username=loginโ the user name to connect as ๐ซถ-V,--versionโ print the pgbench version and exit. Slay ๐-?,--helpโ show help about pgbench command line arguments, and exit. When in doubt ๐
๐ฆ EXIT STATUS ๐ฆ
A successful run exits with status 0. Exit status 1 indicates static problems, like invalid command-line options ๐. Errors during the run โ database errors, script problems, that whole mess โ result in exit status 2. In that latter case, pgbench will still print partial results, so at least you get something ๐โจ
๐ฑ ENVIRONMENT ๐ฑ
PGDATABASEPGHOSTPGPORTPGUSER
Those are your default connection parameters ๐ซถ.
This utility, like most other PostgreSQL utilities, uses the environment variables supported by libpq (see Section 34.15). ๐
The environment variable PG_COLOR specifies whether to use color in diagnostic messages. Possible values are always, auto and never. Aesthetic diagnostics, we love to see it ๐
๐ NOTES ๐
๐ญ What Is the โTransactionโ Actually Performed in pgbench?
pgbench executes test scripts chosen randomly from a specified list. The scripts may include built-in scripts specified with -b and user-provided scripts specified with -f. Each script may be given a relative weight specified after an @ so as to change its selection probability. The default weight is 1. Scripts with a weight of 0 are ignored. โ๏ธ
The default built-in transaction script (also invoked with -b tpcb-like) issues seven commands per transaction over randomly chosen aid, tid, bid and delta. The scenario is inspired by the TPC-B benchmark, but it is not actually TPC-B โ hence the name. Iconic fake-out ๐
BEGIN;UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;SELECT abalance FROM pgbench_accounts WHERE aid = :aid;UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);END;
If you select the simple-update built-in (also -N), steps 4 and 5 aren't included in the transaction. This avoids update contention on these tables, but it makes the test case even less like TPC-B. ๐ซ
If you select the select-only built-in (also -S), only the SELECT is issued. Chill vibes only ๐ฆ
๐ง Custom Scripts ๐ง
pgbench has support for running custom benchmark scenarios by replacing the default transaction script (described above) with a transaction script read from a file (the -f option). In this case a โtransactionโ counts as one execution of a script file. โจ
A script file contains one or more SQL commands terminated by semicolons. Empty lines and lines beginning with -- are ignored. Script files can also contain โmeta commandsโ, which are interpreted by pgbench itself, as described below. ๐
Note ๐ Before PostgreSQL 9.6, SQL commands in script files were terminated by newlines, and so they could not be continued across lines. Now a semicolon is required to separate consecutive SQL commands (though an SQL command does not need one if it's followed by a meta command). If you need to create a script file that works with both old and new versions of pgbench, be sure to write each SQL command on a single line ending with a semicolon. Time-travel compatibility, we love her ๐ฐ๏ธ๐
So basically there's this whole variable-substitution thing for script files, and it's lowkey so useful bestie. โจ Variable names have to be letters (and yes, non-Latin letters totally count ๐
), digits, and underscores โ just make sure the first character isn't a digit, okay? You can set variables with the command-line -D option (we already talked about that one), or with the meta commands coming up below.
On top of whatever you preset with -D, there are a few variables that get preset automatically for you โ they're in Table 282, and honestly they're kind of iconic:
client_idโ a unique number that identifies the client session, and it starts from zero ๐default_seedโ the seed that hash and pseudorandom permutation functions use by defaultrandom_seedโ the random generator seed (unless you overwrite it with-D, of course)scaleโ the current scale factor, slay
If you specify a value for any of these with -D, your value wins over the automatic preset. Periodt. Once a variable is set, you drop its value into an SQL command by writing :variablename. And when you're running more than one client session, each session gets its own set of variables โ no sharing, no drama ๐ฆ. Also pgbench supports up to 255 variable uses in one statement, FYI. Don't ask for more, that's the limit.
๐ธ Script File Meta Commands ๐ธ
Okay so meta commands begin with a backslash (\) and normally they run to the end of the line โ but plot twist, you can continue them onto more lines by writing backslash-return. Arguments to a meta command are separated by white space. These are the supported ones, and yes, we're going through all of them:
โจ \gset [prefix] and \aset [prefix]
These two can end SQL queries, and they literally take the place of the terminating semicolon (;).
When you use \gset, the preceding SQL query is expected to return one row, and its columns get stored into variables named after the column names โ prefixed with prefix if you gave one.
When you use \aset, all the combined SQL queries (the ones separated by \;) have their columns stored into variables named after column names, again prefixed with prefix if provided. If a query returns no row, then no assignment is made, and you can test the variable for existence to detect that. If a query returns more than one row, the last value is what's kept. ๐
Heads up bestie:\gsetand\asetcannot be used in pipeline mode, because the query results aren't available yet by the time the commands would need them. Not me, not you, just how it is ๐
The following example puts the final account balance from the first query into variable abalance, and fills variables p_two and p_three with integers from the third query. The result of the second query is discarded. The result of the two last combined queries are stored in variables four and five. (Iconic behavior, honestly.)
UPDATE pgbench_accounts
SET abalance = abalance + :delta
WHERE aid = :aid
RETURNING abalance \gset
-- compound of two queries
SELECT 1 \;
SELECT 2 AS two, 3 AS three \gset p_
SELECT 4 AS four \; SELECT 5 AS five \aset
โจ \if expression, \elif expression, \else, \endif
This little group implements nestable conditional blocks, similarly to psql's \if expression. Conditional expressions are identical to the ones you use with \set, and non-zero values are interpreted as true. So cute, so conditional ๐
โจ \set varname expression
Sets variable varname to a value calculated from expression. The expression may contain:
- the
NULLconstant - Boolean constants
TRUEandFALSE - integer constants such as
5432 - double constants such as
3.14159 - references to variables, like
:variablename - operators with their usual SQL precedence and associativity
- function calls
- SQL
CASEgeneric conditional expressions - parentheses
Functions and most operators return NULL on NULL input.
For conditional purposes, non zero numerical values are TRUE, and zero numerical values and NULL are FALSE.
Warning bestie: too large or small integer and double constants, as well as integer arithmetic operators (+,-,*and/), raise errors on overflows. So like, maybe don't. ๐ญ
When no final ELSE clause is provided to a CASE, the default value is NULL.
Examples โ look at these, they're giving main character energy:
\set ntellers 10 * :scale
\set aid (1021 * random(1, 100000 * :scale)) % \
(100000 * :scale) + 1
\set divx CASE WHEN :x <> 0 THEN :y/:x ELSE NULL END
โจ \sleep number [us | ms | s]
Causes script execution to sleep for the specified duration, in microseconds (us), milliseconds (ms) or seconds (s). If you leave the unit off, seconds are the default. number can be either an integer constant or a :variablename reference to a variable that has an integer value. Nap time ๐ดโจ
Example:
\sleep 10 ms
โจ \setshell varname command [argument ...]
Sets variable varname to the result of the shell command command with the given argument(s). The command must return an integer value through its standard output.
command and each argument can be either a text constant or a :variablename reference to a variable. And okay listen ๐ซถ โ if you want to use an argument that starts with a colon, write an additional colon at the beginning of the argument. Sneaky but it works.
Example:
\setshell variable_to_be_assigned command literal_argument :variable ::literal_starting_with_colon
โจ \shell command [argument ...]
Same as \setshell, but the result of the command is just... discarded. Gone. Not kept. Bye ๐จ
Example:
\shell command literal_argument :variable ::literal_starting_with_colon
โจ \startpipeline and \endpipeline
These commands delimit the start and end of a pipeline of SQL statements. In pipeline mode, statements are sent to the server without waiting for the results of previous statements. See Section 34.5 for the whole story. Pipeline mode requires the use of extended query protocol, ngl.
๐ Built-in Operators ๐
The arithmetic, bitwise, comparison and logical operators listed in Table 283 are built into pgbench, and you can absolutely use them in expressions appearing in \set. The operators are listed in increasing precedence order. Except as noted, operators taking two numeric inputs will produce a double value if either input is double โ otherwise they produce an integer result. Math girlies rise ๐
๐ Table 283. pgbench Operators ๐
okay bestie, here's the whole operator menu โ every single one, no skipping ๐ these are the little symbols that glue your expressions together inside pgbench scripts, and each one takes the types on the left of the arrow and hands you back the type on the right. slay.
boolean OR boolean โ booleanโ logical OR, the "either one works, I'm chill" of booleans โจ example:5 or 0 โ TRUEboolean AND boolean โ booleanโ logical AND, the "both or nothing" vibe check ๐ธ example:3 and 0 โ FALSENOT boolean โ booleanโ logical NOT, flips it, iconic ๐ example:not false โ TRUEboolean IS [NOT] (NULL|TRUE|FALSE) โ booleanโ boolean value tests, for when you gotta know what it is, not just whether it's truthy ๐ example:1 is null โ FALSEvalue ISNULL|NOTNULL โ booleanโ nullness tests, i.e. "does this thing even exist" ๐ฅ example:1 notnull โ TRUEnumber = number โ booleanโ equal, fr fr โญ example:5 = 4 โ FALSEnumber <> number โ booleanโ not equal, the classic ๐ฆ example:5 <> 4 โ TRUEnumber != number โ booleanโ also not equal, same energy, different spelling ๐ example:5 != 5 โ FALSEnumber < number โ booleanโ less than ๐ example:5 < 4 โ FALSEnumber <= number โ booleanโ less than or equal to ๐ example:5 <= 4 โ FALSEnumber > number โ booleanโ greater than ๐ example:5 > 4 โ TRUEnumber >= number โ booleanโ greater than or equal to ๐ example:5 >= 4 โ TRUEinteger | integer โ integerโ bitwise OR, lowkey the nerdiest slay ๐ง example:1 | 2 โ 3integer # integer โ integerโ bitwise XOR, yes it's#, no that's not a typo ๐ example:1 # 3 โ 2integer & integer โ integerโ bitwise AND, main character bitwise energy ๐ฅ example:1 & 3 โ 1~ integer โ integerโ bitwise NOT, flips every bit, chaos but make it math ๐ญ example:~ 1 โ -2integer << integer โ integerโ bitwise shift left, move it over bestie โจ example:1 << 2 โ 4integer >> integer โ integerโ bitwise shift right, other direction, same icon status ๐ฆ example:8 >> 2 โ 2number + number โ numberโ addition, the basics, still ate ๐ธ example:5 + 4 โ 9number - number โ numberโ subtraction, periodt ๐ example:3 - 2.0 โ 1.0number * number โ numberโ multiplication, go off ๐ example:5 * 4 โ 20number / number โ numberโ division โ and huge heads up: if both inputs are integers, it truncates the result towards zero ๐ example:5 / 3 โ 1integer % integer โ integerโ modulo (remainder), the "what's left over" girlie ๐ example:3 % 2 โ 1- number โ numberโ negation, just a little minus out front, no thoughts head empty โญ example:
โ .PP - 2.0 โ -2.0 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โจ Built-In Functions โจ
okay so this is the fun part โ pgbench comes with a whole little squad of functions built in ๐
and you can absolutely use them in any expression that shows up inside \set. like, they're just there for you. no imports, no installing anything, no "wait do I need a library for this" โ none of that. iconic behavior fr fr ๐ซถ
so the functions listed in Table 284 are built into pgbench and may be used in expressions appearing in \set. that's the whole vibe โ you've got Table 284, that's your guest list, and if a function's on it, it's welcome at the \set party ๐
ngl bestie, keep Table 284 open in another tab while you're writing expressions โ it's giving cheat sheet and it's gonna save you ๐ญ
๐ abs ( number ) โ same type as input
Absolute value, bestie โ negative becomes positive, no cap.
abs(-17) โ 17
๐ซถ debug ( number ) โ same type as input
Prints the argument to stderr and then hands it right back to you. It's giving "I'm just gonna say it out loud and then return it" energy.
debug(5432.1) โ 5432.1
โจ double ( number ) โ double
Casts to double. That's it, that's the whole function, and honestly iconic for it.
double(5432) โ 5432.0
๐ธ exp ( number ) โ double
Exponential โ e raised to the power you gave it. e is that special math girlie, iykyk.
exp(1.0) โ 2.718281828459045
๐ greatest ( number [, ... ] ) โ double if any argument is double, else integer
Picks the largest value out of all the arguments. Main character of the argument list, lowkey.
greatest(5, 4, 3, 2) โ 5
๐
hash ( value [, seed ] ) โ integer
This is literally just an alias for hash_murmur2. Same vibes, shorter name.
hash(10, 5432) โ -5817877081768721676
๐ฆ hash_fnv1a ( value [, seed ] ) โ integer
Computes an FNV-1a hash. A whole different hash flavor, and it ate.
hash_fnv1a(10, 5432) โ -7793829335365542153
๐ hash_murmur2 ( value [, seed ] ) โ integer
Computes a MurmurHash2 hash. Yes that's really the name, and yes it's adorable.
hash_murmur2(10, 5432) โ -5817877081768721676
โญ int ( number ) โ integer
Casts to integer. Watch it do actual math first, though โ the example is a whole little journey:
int(5.4 + 3.8) โ 9
๐ง least ( number [, ... ] ) โ double if any argument is double, else integer
Picks the smallest value among the arguments. The introvert of the number list, respectfully.
least(5, 4, 3, 2.1) โ 2.1
๐ ln ( number ) โ double
Natural logarithm. Pairs perfectly with exp, they're a matching set fr fr.
ln(2.718281828459045) โ 1.0
๐ mod ( integer, integer ) โ integer
Modulo, aka the remainder. Not me explaining division leftovers like it's gossip, but here we are.
mod(54, 32) โ 22
๐ฅ permute ( i, size [, seed ] ) โ integer
Permuted value of i, in the range [0, size). This is the new position of i (modulo size) in a pseudorandom permutation of the integers 0...size-1, parameterized by seed, see below. Very "shuffle the deck but remember the deck" of it.
permute(0, 4) โ an integer between 0 and 3
๐ pi () โ double
Approximate value of ฯ. Yeah they just put ฯ in there, we love a constant with range.
pi() โ 3.14159265358979323846
๐ pow ( x, y ) โ double
๐ power ( x, y ) โ double
x raised to the power of y. Two names, one slay.
pow(2.0, 10) โ 1024.0
๐ซง random ( lb, ub ) โ integer
Computes a uniformly-distributed random integer in [lb, ub]. Every number in the range gets a fair shot, periodt.
random(1, 10) โ an integer between 1 and 10
๐บ random_exponential ( lb, ub, parameter ) โ integer
Computes an exponentially-distributed random integer in [lb, ub], see below. Skewed distribution, so some values are way more likely than others.
random_exponential(1, 10, 3.0) โ an integer between 1 and 10
๐ random_gaussian ( lb, ub, parameter ) โ integer
Computes a Gaussian-distributed random integer in [lb, ub], see below. Bell curve behavior, very "most of us are average" of it.
random_gaussian(1, 10, 2.5) โ an integer between 1 and 10
random_zipfian ( lb, ub, parameter ) โ integerโ computes a Zipfian-distributed random integer in[lb, ub]โ more on that whole vibe below ๐
random_zipfian(1, 10, 1.5) โ an integer between 1 and 10
sqrt ( number ) โ doubleโ square root, literally just that, no cap ๐งฎ
sqrt(2.0) โ 1.414213562
So the random function hands you values from a uniform distribution, meaning every value inside the range you gave it has an equal shot. Fair. Balanced. Iconic. ๐
But random_exponential, random_gaussian and random_zipfian each want an extra double parameter, and that little number is what decides the exact shape of the distribution. It's giving "choose your own destiny". ๐ฎ
- Exponential โ
parametershapes the distribution by truncating a quickly-decreasing exponential distribution atparameter, then projecting onto integers between the bounds. To be precise, with
f(x) = exp(-parameter * (x - min) / (max - min + 1)) / (1 - exp(-parameter))
then value i between min and max inclusive is drawn with probability: f(i) - f(i + 1).
Intuitively: the bigger the parameter, the more often values close to min get accessed, and the less often values close to max do. The closer parameter is to 0, the flatter (more uniform) the access distribution gets. A crude approximation of the distribution is that the most frequent 1% of values in the range, close to min, are drawn parameter% of the time. And heads up bestie โ the parameter value must be strictly positive. ๐จ
- Gaussian โ the interval is mapped onto a standard normal distribution (the classical bell-shaped Gaussian curve), truncated at
-parameteron the left and+parameteron the right. Values in the middle of the interval are more likely to be drawn. To be precise, ifPHI(x)is the cumulative distribution function of the standard normal distribution, with meanmudefined as(max + min) / 2.0, with
f(x) = PHI(2.0 * parameter * (x - mu) / (max - min + 1)) /
(2.0 * PHI(parameter) - 1)
then value i between min and max inclusive is drawn with probability: f(i + 0.5) - f(i - 0.5).
Intuitively: the larger the parameter, the more frequently values close to the middle of the interval are drawn, and the less frequently values close to the min and max bounds. About 67% of values are drawn from the middle 1.0 / parameter, that is a relative 0.5 / parameter around the mean, and 95% in the middle 2.0 / parameter, that is a relative 1.0 / parameter around the mean. For instance, if parameter is 4.0, 67% of values are drawn from the middle quarter (1.0 / 4.0) of the interval (i.e., from 3.0 / 8.0 to 5.0 / 8.0) and 95% from the middle half (2.0 / 4.0) of the interval (second and third quartiles). And the minimum allowed parameter value is 2.0. Don't try to go lower, it will absolutely not slay. ๐
โโ๏ธ
- Zipfian โ
random_zipfiangenerates a bounded Zipfian distribution.parameterdefines how skewed the distribution is. The larger theparameter, the more frequently values closer to the beginning of the interval are drawn. The distribution is such that, assuming the range starts from 1, the ratio of the probability of drawingkversus drawingk+1is((k+1)/k)**parameter. For example,random_zipfian(1, ..., 2.5)produces the value1about(2/1)**2.5 = 5.66times more frequently than2, which itself is produced(3/2)**2.5 = 2.76times more frequently than3, and so on. ๐
pgbench's implementation is based on "Non-Uniform Random Variate Generation", Luc Devroye, p. 550-551, Springer 1986. Due to limitations of that algorithm, the parameter value is restricted to the range [1.001, 1000]. That's the whole box, no wiggle room. ๐ฆ
Note ๐ซถ When designing a benchmark which selects rows non-uniformly, be aware that the rows chosen may be correlated with other data such as IDs from a sequence or the physical row ordering, which may skew performance measurements. To avoid this, you may wish to use the permute function, or some other additional step with similar effect, to shuffle the selected rows and remove such correlations.
Hash functions hash, hash_murmur2 and hash_fnv1a accept an input value and an optional seed parameter. In case the seed isn't provided, the value of :default_seed is used, which is initialized randomly unless set by the command-line -D option. ๐ฒ
permute accepts an input value, a size, and an optional seed parameter. It generates a pseudorandom permutation of integers in the range [0, size), and returns the index of the input value in the permuted values. The permutation chosen is parameterized by the seed, which defaults to :default_seed, if not specified. Unlike the hash functions, permute ensures that there are no collisions or holes in the output values. Input values outside the interval are interpreted modulo the size. The function raises an error if the size is not positive.
permute can be used to scatter the distribution of non-uniform random functions such as random_zipfian or random_exponential so that values drawn more often are not trivially correlated. For instance, the following pgbench script simulates a possible real world workload typical for social media and blogging platforms where a few accounts generate excessive load: ๐ฑโจ
\set size 1000000
\set r random_zipfian(1, :size, 1.07)
\set k 1 + permute(:r, :size)
In some cases several distinct distributions are needed which don't correlate with each other, and this is when the optional seed parameter comes in handy: ๐ฑ
\set k1 1 + permute(:r, :size, :default_seed + 123)
\set k2 1 + permute(:r, :size, :default_seed + 321)
A similar behavior can also be approximated with hash: ๐
\set size 1000000
\set r random_zipfian(1, 100 * :size, 1.07)
\set k 1 + abs(hash(:r)) % :size
However, since hash generates collisions, some values will not be reachable and others will be more frequent than expected from the original distribution. So likeโฆ not a perfect dupe, bestie. ๐
As an example, the full definition of the built-in TPC-B-like transaction is:
\set aid random(1, 100000 * :scale)
\set bid random(1, 1 * :scale)
\set tid random(1, 10 * :scale)
\set delta random(-5000, 5000)
BEGIN;
UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;
SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;
UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;
INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
END;
This script allows each iteration of the transaction to reference different, randomly-chosen rows. (This example also shows why it's important for each client session to have its own variables โ otherwise they'd not be independently touching different rows.) Main character energy: every session gets its own โจloreโจ. ๐ซถ
๐ Per-Transaction Logging ๐
With the -l option (but without the --aggregate-interval option), pgbench writes information about each transaction to a log file. The log file will be named prefix.nnn, where prefix defaults to pgbench_log, and nnn is the PID of the pgbench process. The prefix can be changed by using the --log-prefix option. If the -j option is 2 or higher, so that there are multiple worker threads, each will have its own log file. The first worker will use the same name for its log file as in the standard single worker case. The additional log files for the other workers will be named prefix.nnn.mmm, where mmm is a sequential number for each worker starting with 1. ๐๏ธ
The format of the log is:
client_id transaction_no time script_no time_epoch time_us [ schedule_lag ]
where client_id indicates which client session ran the transaction, transaction_no counts how many transactions have been run by that session, time is the total elapsed transaction time in microseconds, script_no identifies which script file was used (useful when multiple scripts were specified with -f or -b), and time_epoch/time_us are a Unix-epoch time stamp and an offset in microseconds (suitable for creating an ISO 8601 time stamp with fractional seconds) showing when the transaction completed. The schedule_lag field is the difference between the transaction's scheduled start time, and the time it actually started, in microseconds. It is only present when the --rate option is used. When both --rate and --latency-limit are used, the time for a skipped transaction will be reported as skipped. โฑ๏ธ
Here is a snippet of a log file generated in a single-client run:
0 199 2241 0 1175850568 995598
0 200 2465 0 1175850568 998079
0 201 2513 0 1175850569 608
0 202 2038 0 1175850569 2663
Another example with --rate=100 and --latency-limit=5 (note the additional schedule_lag column):
0 81 4621 0 1412881037 912698 3005
0 82 6173 0 1412881037 914578 4304
0 83 skipped 0 1412881037 914578 5217
0 83 skipped 0 1412881037 914578 5099
0 83 4722 0 1412881037 916203 3108
0 84 4142 0 1412881037 918023 2333
0 85 2465 0 1412881037 919759 740
In this example, transaction 82 was late, because its latency (6.173 ms) was over the 5 ms limit. The next two transactions were skipped, because they were already late before they were even started. ๐ญ F in the chat for those two.
When running a long test on hardware that can handle a lot of transactions, the log files can become very large. The --sampling-rate option can be used to log only a random sample of transactions. ๐ธ
๐ Aggregated Logging ๐
With the --aggregate-interval option, a different format is used for the log files:
interval_start num_transactions sum_latency sum_latency_2 min_latency max_latency [ sum_lag sum_lag_2 min_lag max_lag [ skipped ] ]
okay so, picking up right where the fields left off: interval_start is the start of the interval (as a Unix epoch time stamp), num_transactions is the number of transactions within the interval, sum_latency is the sum of the transaction latencies within the interval, sum_latency_2 is the sum of squares of the transaction latencies within the interval, min_latency is the minimum latency within the interval, and max_latency is the maximum latency within the interval.
The next fields โ sum_lag, sum_lag_2, min_lag, and max_lag โ are only present if the --rate option is used. They give you stats about the time each transaction had to wait for the previous one to finish, i.e., the difference between each transaction's scheduled start time and the time it actually started. The very last field, skipped, is only present if the --latency-limit option is used, too. It counts the number of transactions skipped because they would have started too late. Each transaction is counted in the interval when it was committed.
here's a lil example output, bestie:
1345828501 5601 1542744 483552416 61 2573
1345828503 7884 1979812 565806736 60 1479
1345828505 7208 1979422 567277552 59 1391
1345828507 7685 1980268 569784714 60 1398
1345828509 7073 1979779 573489941 236 1411
notice that while the plain (unaggregated) log file shows which script was used for each transaction, the aggregated log does not. so if you need per-script data, you need to aggregate the data on your own. no cap.
๐ Per-Statement Latencies ๐
With the -r option, pgbench collects the elapsed transaction time of each statement executed by every client. It then reports an average of those values โ referred to as the latency for each statement โ after the benchmark has finished.
For the default script, the output will look similar to this:
starting vacuum...end.
transaction type: <builtin: TPC-B (sort of)>
scaling factor: 1
query mode: simple
number of clients: 10
number of threads: 1
number of transactions per client: 1000
number of transactions actually processed: 10000/10000
latency average = 10.870 ms
latency stddev = 7.341 ms
initial connection time = 30.954 ms
tps = 907.949122 (without initial connection time)
statement latencies in milliseconds:
0.001 \set aid random(1, 100000 * :scale)
0.001 \set bid random(1, 1 * :scale)
0.001 \set tid random(1, 10 * :scale)
0.000 \set delta random(-5000, 5000)
0.046 BEGIN;
0.151 UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;
0.107 SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
4.241 UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;
5.245 UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;
0.102 INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
0.974 END;
If multiple script files are specified, the averages are reported separately for each script file.
heads up, bestie: collecting the additional timing information needed for per-statement latency computation adds some overhead. this will slow average execution speed and lower the computed TPS. the amount of slowdown varies significantly depending on platform and hardware. comparing average TPS values with and without latency reporting enabled is a good way to measure if the timing overhead is significant. ๐
๐ฑ Good Practices ๐ฑ
honestly? it is very easy to use pgbench to produce completely meaningless numbers. here are some guidelines to help you get useful results.
- never believe any test that runs for only a few seconds. use the
-tor-Toption to make the run last at least a few minutes, so as to average out noise. in some cases you could need hours to get numbers that are reproducible. it's a good idea to try the test run a few times, to find out if your numbers are reproducible or not. - for the default TPC-B-like test scenario, the initialization scale factor (
-s) should be at least as large as the largest number of clients you intend to test (-c); else you'll mostly be measuring update contention. there are only-srows in thepgbench_branchestable, and every transaction wants to update one of them, so-cvalues in excess of-swill undoubtedly result in lots of transactions blocked waiting for other transactions. - the default test scenario is also quite sensitive to how long it's been since the tables were initialized: accumulation of dead rows and dead space in the tables changes the results. to understand the results you must keep track of the total number of updates and when vacuuming happens. if autovacuum is enabled it can result in unpredictable changes in measured performance.
- a limitation of
pgbenchis that it can itself become the bottleneck when trying to test a large number of client sessions. this can be alleviated by runningpgbenchon a different machine from the database server, although low network latency will be essential. it might even be useful to run severalpgbenchinstances concurrently, on several client machines, against the same database server.
๐ Security ๐
if untrusted users have access to a database that has not adopted a secure schema usage pattern, do not run pgbench in that database. pgbench uses unqualified names and does not manipulate the search path. periodt. ๐ซถ
mwah ๐ this page is PostgreSQL 14.24, dated 2026 โ go get those reproducible numbers, bestie โจ๐ฆ
๐ฆ where this page comes from
- opensuse-leap 16.0: postgresql14-contrib 14.24-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql14-contrib 14.24-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql14-contrib 14.24-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql14-contrib 14.24-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms