1PGBENCH(1)               PostgreSQL 13.4 Documentation              PGBENCH(1)
2
3
4

NAME

6       pgbench - run a benchmark test on PostgreSQL
7

SYNOPSIS

9       pgbench -i [option...] [dbname]
10
11       pgbench [option...] [dbname]
12

DESCRIPTION

14       pgbench is a simple program for running benchmark tests on PostgreSQL.
15       It runs the same sequence of SQL commands over and over, possibly in
16       multiple concurrent database sessions, and then calculates the average
17       transaction rate (transactions per second). By default, pgbench tests a
18       scenario that is loosely based on TPC-B, involving five SELECT, UPDATE,
19       and INSERT commands per transaction. However, it is easy to test other
20       cases by writing your own transaction script files.
21
22       Typical output from pgbench looks like:
23
24           transaction type: <builtin: TPC-B (sort of)>
25           scaling factor: 10
26           query mode: simple
27           number of clients: 10
28           number of threads: 1
29           number of transactions per client: 1000
30           number of transactions actually processed: 10000/10000
31           tps = 85.184871 (including connections establishing)
32           tps = 85.296346 (excluding connections establishing)
33
34       The first six lines report some of the most important parameter
35       settings. The next line reports the number of transactions completed
36       and intended (the latter being just the product of number of clients
37       and number of transactions per client); these will be equal unless the
38       run failed before completion. (In -T mode, only the actual number of
39       transactions is printed.) The last two lines report the number of
40       transactions per second, figured with and without counting the time to
41       start database sessions.
42
43       The default TPC-B-like transaction test requires specific tables to be
44       set up beforehand.  pgbench should be invoked with the -i (initialize)
45       option to create and populate these tables. (When you are testing a
46       custom script, you don't need this step, but will instead need to do
47       whatever setup your test needs.) Initialization looks like:
48
49           pgbench -i [ other-options ] dbname
50
51       where dbname is the name of the already-created database to test in.
52       (You may also need -h, -p, and/or -U options to specify how to connect
53       to the database server.)
54
55           Caution
56           pgbench -i creates four tables pgbench_accounts, pgbench_branches,
57           pgbench_history, and pgbench_tellers, destroying any existing
58           tables of these names. Be very careful to use another database if
59           you have tables having these names!
60
61       At the default “scale factor” of 1, the tables initially contain this
62       many rows:
63
64           table                   # of rows
65           ---------------------------------
66           pgbench_branches        1
67           pgbench_tellers         10
68           pgbench_accounts        100000
69           pgbench_history         0
70
71       You can (and, for most purposes, probably should) increase the number
72       of rows by using the -s (scale factor) option. The -F (fillfactor)
73       option might also be used at this point.
74
75       Once you have done the necessary setup, you can run your benchmark with
76       a command that doesn't include -i, that is
77
78           pgbench [ options ] dbname
79
80       In nearly all cases, you'll need some options to make a useful test.
81       The most important options are -c (number of clients), -t (number of
82       transactions), -T (time limit), and -f (specify a custom script file).
83       See below for a full list.
84

OPTIONS

86       The following is divided into three subsections. Different options are
87       used during database initialization and while running benchmarks, but
88       some options are useful in both cases.
89
90   Initialization Options
91       pgbench accepts the following command-line initialization arguments:
92
93       dbname
94           Specifies the name of the database to test in. If this is not
95           specified, the environment variable PGDATABASE is used. If that is
96           not set, the user name specified for the connection is used.
97
98       -i
99       --initialize
100           Required to invoke initialization mode.
101
102       -I init_steps
103       --init-steps=init_steps
104           Perform just a selected set of the normal initialization steps.
105           init_steps specifies the initialization steps to be performed,
106           using one character per step. Each step is invoked in the specified
107           order. The default is dtgvp. The available steps are:
108
109           d (Drop)
110               Drop any existing pgbench tables.
111
112           t (create Tables)
113               Create the tables used by the standard pgbench scenario, namely
114               pgbench_accounts, pgbench_branches, pgbench_history, and
115               pgbench_tellers.
116
117           g or G (Generate data, client-side or server-side)
118               Generate data and load it into the standard tables, replacing
119               any data already present.
120
121               With g (client-side data generation), data is generated in
122               pgbench client and then sent to the server. This uses the
123               client/server bandwidth extensively through a COPY. Using g
124               causes logging to print one message every 100,000 rows while
125               generating data for the pgbench_accounts table.
126
127               With G (server-side data generation), only small queries are
128               sent from the pgbench client and then data is actually
129               generated in the server. No significant bandwidth is required
130               for this variant, but the server will do more work. Using G
131               causes logging not to print any progress message while
132               generating data.
133
134               The default initialization behavior uses client-side data
135               generation (equivalent to g).
136
137           v (Vacuum)
138               Invoke VACUUM on the standard tables.
139
140           p (create Primary keys)
141               Create primary key indexes on the standard tables.
142
143           f (create Foreign keys)
144               Create foreign key constraints between the standard tables.
145               (Note that this step is not performed by default.)
146
147       -F fillfactor
148       --fillfactor=fillfactor
149           Create the pgbench_accounts, pgbench_tellers and pgbench_branches
150           tables with the given fillfactor. Default is 100.
151
152       -n
153       --no-vacuum
154           Perform no vacuuming during initialization. (This option suppresses
155           the v initialization step, even if it was specified in -I.)
156
157       -q
158       --quiet
159           Switch logging to quiet mode, producing only one progress message
160           per 5 seconds. The default logging prints one message each 100,000
161           rows, which often outputs many lines per second (especially on good
162           hardware).
163
164           This setting has no effect if G is specified in -I.
165
166       -s scale_factor
167       --scale=scale_factor
168           Multiply the number of rows generated by the scale factor. For
169           example, -s 100 will create 10,000,000 rows in the pgbench_accounts
170           table. Default is 1. When the scale is 20,000 or larger, the
171           columns used to hold account identifiers (aid columns) will switch
172           to using larger integers (bigint), in order to be big enough to
173           hold the range of account identifiers.
174
175       --foreign-keys
176           Create foreign key constraints between the standard tables. (This
177           option adds the f step to the initialization step sequence, if it
178           is not already present.)
179
180       --index-tablespace=index_tablespace
181           Create indexes in the specified tablespace, rather than the default
182           tablespace.
183
184       --partition-method=NAME
185           Create a partitioned pgbench_accounts table with NAME method.
186           Expected values are range or hash. This option requires that
187           --partitions is set to non-zero. If unspecified, default is range.
188
189       --partitions=NUM
190           Create a partitioned pgbench_accounts table with NUM partitions of
191           nearly equal size for the scaled number of accounts. Default is 0,
192           meaning no partitioning.
193
194       --tablespace=tablespace
195           Create tables in the specified tablespace, rather than the default
196           tablespace.
197
198       --unlogged-tables
199           Create all tables as unlogged tables, rather than permanent tables.
200
201   Benchmarking Options
202       pgbench accepts the following command-line benchmarking arguments:
203
204       -b scriptname[@weight]
205       --builtin=scriptname[@weight]
206           Add the specified built-in script to the list of scripts to be
207           executed. Available built-in scripts are: tpcb-like, simple-update
208           and select-only. Unambiguous prefixes of built-in names are
209           accepted. With the special name list, show the list of built-in
210           scripts and exit immediately.
211
212           Optionally, write an integer weight after @ to adjust the
213           probability of selecting this script versus other ones. The default
214           weight is 1. See below for details.
215
216       -c clients
217       --client=clients
218           Number of clients simulated, that is, number of concurrent database
219           sessions. Default is 1.
220
221       -C
222       --connect
223           Establish a new connection for each transaction, rather than doing
224           it just once per client session. This is useful to measure the
225           connection overhead.
226
227       -d
228       --debug
229           Print debugging output.
230
231       -D varname=value
232       --define=varname=value
233           Define a variable for use by a custom script (see below). Multiple
234           -D options are allowed.
235
236       -f filename[@weight]
237       --file=filename[@weight]
238           Add a transaction script read from filename to the list of scripts
239           to be executed.
240
241           Optionally, write an integer weight after @ to adjust the
242           probability of selecting this script versus other ones. The default
243           weight is 1. (To use a script file name that includes an @
244           character, append a weight so that there is no ambiguity, for
245           example filen@me@1.) See below for details.
246
247       -j threads
248       --jobs=threads
249           Number of worker threads within pgbench. Using more than one thread
250           can be helpful on multi-CPU machines. Clients are distributed as
251           evenly as possible among available threads. Default is 1.
252
253       -l
254       --log
255           Write information about each transaction to a log file. See below
256           for details.
257
258       -L limit
259       --latency-limit=limit
260           Transactions that last more than limit milliseconds are counted and
261           reported separately, as late.
262
263           When throttling is used (--rate=...), transactions that lag behind
264           schedule by more than limit ms, and thus have no hope of meeting
265           the latency limit, are not sent to the server at all. They are
266           counted and reported separately as skipped.
267
268       -M querymode
269       --protocol=querymode
270           Protocol to use for submitting queries to the server:
271
272           •   simple: use simple query protocol.
273
274           •   extended: use extended query protocol.
275
276           •   prepared: use extended query protocol with prepared statements.
277
278           In the prepared mode, pgbench reuses the parse analysis result
279           starting from the second query iteration, so pgbench runs faster
280           than in other modes.
281
282           The default is simple query protocol. (See Chapter 52 for more
283           information.)
284
285       -n
286       --no-vacuum
287           Perform no vacuuming before running the test. This option is
288           necessary if you are running a custom test scenario that does not
289           include the standard tables pgbench_accounts, pgbench_branches,
290           pgbench_history, and pgbench_tellers.
291
292       -N
293       --skip-some-updates
294           Run built-in simple-update script. Shorthand for -b simple-update.
295
296       -P sec
297       --progress=sec
298           Show progress report every sec seconds. The report includes the
299           time since the beginning of the run, the TPS since the last report,
300           and the transaction latency average and standard deviation since
301           the last report. Under throttling (-R), the latency is computed
302           with respect to the transaction scheduled start time, not the
303           actual transaction beginning time, thus it also includes the
304           average schedule lag time.
305
306       -r
307       --report-latencies
308           Report the average per-statement latency (execution time from the
309           perspective of the client) of each command after the benchmark
310           finishes. See below for details.
311
312       -R rate
313       --rate=rate
314           Execute transactions targeting the specified rate instead of
315           running as fast as possible (the default). The rate is given in
316           transactions per second. If the targeted rate is above the maximum
317           possible rate, the rate limit won't impact the results.
318
319           The rate is targeted by starting transactions along a
320           Poisson-distributed schedule time line. The expected start time
321           schedule moves forward based on when the client first started, not
322           when the previous transaction ended. That approach means that when
323           transactions go past their original scheduled end time, it is
324           possible for later ones to catch up again.
325
326           When throttling is active, the transaction latency reported at the
327           end of the run is calculated from the scheduled start times, so it
328           includes the time each transaction had to wait for the previous
329           transaction to finish. The wait time is called the schedule lag
330           time, and its average and maximum are also reported separately. The
331           transaction latency with respect to the actual transaction start
332           time, i.e., the time spent executing the transaction in the
333           database, can be computed by subtracting the schedule lag time from
334           the reported latency.
335
336           If --latency-limit is used together with --rate, a transaction can
337           lag behind so much that it is already over the latency limit when
338           the previous transaction ends, because the latency is calculated
339           from the scheduled start time. Such transactions are not sent to
340           the server, but are skipped altogether and counted separately.
341
342           A high schedule lag time is an indication that the system cannot
343           process transactions at the specified rate, with the chosen number
344           of clients and threads. When the average transaction execution time
345           is longer than the scheduled interval between each transaction,
346           each successive transaction will fall further behind, and the
347           schedule lag time will keep increasing the longer the test run is.
348           When that happens, you will have to reduce the specified
349           transaction rate.
350
351       -s scale_factor
352       --scale=scale_factor
353           Report the specified scale factor in pgbench's output. With the
354           built-in tests, this is not necessary; the correct scale factor
355           will be detected by counting the number of rows in the
356           pgbench_branches table. However, when testing only custom
357           benchmarks (-f option), the scale factor will be reported as 1
358           unless this option is used.
359
360       -S
361       --select-only
362           Run built-in select-only script. Shorthand for -b select-only.
363
364       -t transactions
365       --transactions=transactions
366           Number of transactions each client runs. Default is 10.
367
368       -T seconds
369       --time=seconds
370           Run the test for this many seconds, rather than a fixed number of
371           transactions per client.  -t and -T are mutually exclusive.
372
373       -v
374       --vacuum-all
375           Vacuum all four standard tables before running the test. With
376           neither -n nor -v, pgbench will vacuum the pgbench_tellers and
377           pgbench_branches tables, and will truncate pgbench_history.
378
379       --aggregate-interval=seconds
380           Length of aggregation interval (in seconds). May be used only with
381           -l option. With this option, the log contains per-interval summary
382           data, as described below.
383
384       --log-prefix=prefix
385           Set the filename prefix for the log files created by --log. The
386           default is pgbench_log.
387
388       --progress-timestamp
389           When showing progress (option -P), use a timestamp (Unix epoch)
390           instead of the number of seconds since the beginning of the run.
391           The unit is in seconds, with millisecond precision after the dot.
392           This helps compare logs generated by various tools.
393
394       --random-seed=seed
395           Set random generator seed. Seeds the system random number
396           generator, which then produces a sequence of initial generator
397           states, one for each thread. Values for seed may be: time (the
398           default, the seed is based on the current time), rand (use a strong
399           random source, failing if none is available), or an unsigned
400           decimal integer value. The random generator is invoked explicitly
401           from a pgbench script (random...  functions) or implicitly (for
402           instance option --rate uses it to schedule transactions). When
403           explicitly set, the value used for seeding is shown on the
404           terminal. Any value allowed for seed may also be provided through
405           the environment variable PGBENCH_RANDOM_SEED. To ensure that the
406           provided seed impacts all possible uses, put this option first or
407           use the environment variable.
408
409           Setting the seed explicitly allows to reproduce a pgbench run
410           exactly, as far as random numbers are concerned. As the random
411           state is managed per thread, this means the exact same pgbench run
412           for an identical invocation if there is one client per thread and
413           there are no external or data dependencies. From a statistical
414           viewpoint reproducing runs exactly is a bad idea because it can
415           hide the performance variability or improve performance unduly,
416           e.g., by hitting the same pages as a previous run. However, it may
417           also be of great help for debugging, for instance re-running a
418           tricky case which leads to an error. Use wisely.
419
420       --sampling-rate=rate
421           Sampling rate, used when writing data into the log, to reduce the
422           amount of log generated. If this option is given, only the
423           specified fraction of transactions are logged. 1.0 means all
424           transactions will be logged, 0.05 means only 5% of the transactions
425           will be logged.
426
427           Remember to take the sampling rate into account when processing the
428           log file. For example, when computing TPS values, you need to
429           multiply the numbers accordingly (e.g., with 0.01 sample rate,
430           you'll only get 1/100 of the actual TPS).
431
432       --show-script=scriptname
433           Show the actual code of builtin script scriptname on stderr, and
434           exit immediately.
435
436   Common Options
437       pgbench also accepts the following common command-line arguments for
438       connection parameters:
439
440       -h hostname
441       --host=hostname
442           The database server's host name
443
444       -p port
445       --port=port
446           The database server's port number
447
448       -U login
449       --username=login
450           The user name to connect as
451
452       -V
453       --version
454           Print the pgbench version and exit.
455
456       -?
457       --help
458           Show help about pgbench command line arguments, and exit.
459

EXIT STATUS

461       A successful run will exit with status 0. Exit status 1 indicates
462       static problems such as invalid command-line options. Errors during the
463       run such as database errors or problems in the script will result in
464       exit status 2. In the latter case, pgbench will print partial results.
465

ENVIRONMENT

467       PGDATABASE
468       PGHOST
469       PGPORT
470       PGUSER
471           Default connection parameters.
472
473       This utility, like most other PostgreSQL utilities, uses the
474       environment variables supported by libpq (see Section 33.14).
475
476       The environment variable PG_COLOR specifies whether to use color in
477       diagnostic messages. Possible values are always, auto and never.
478

NOTES

480   What Is the “Transaction” Actually Performed in pgbench?
481       pgbench executes test scripts chosen randomly from a specified list.
482       The scripts may include built-in scripts specified with -b and
483       user-provided scripts specified with -f. Each script may be given a
484       relative weight specified after an @ so as to change its selection
485       probability. The default weight is 1. Scripts with a weight of 0 are
486       ignored.
487
488       The default built-in transaction script (also invoked with -b
489       tpcb-like) issues seven commands per transaction over randomly chosen
490       aid, tid, bid and delta. The scenario is inspired by the TPC-B
491       benchmark, but is not actually TPC-B, hence the name.
492
493        1. BEGIN;
494
495        2. UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid
496           = :aid;
497
498        3. SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
499
500        4. UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid =
501           :tid;
502
503        5. UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid
504           = :bid;
505
506        6. INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES
507           (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
508
509        7. END;
510
511       If you select the simple-update built-in (also -N), steps 4 and 5
512       aren't included in the transaction. This will avoid update contention
513       on these tables, but it makes the test case even less like TPC-B.
514
515       If you select the select-only built-in (also -S), only the SELECT is
516       issued.
517
518   Custom Scripts
519       pgbench has support for running custom benchmark scenarios by replacing
520       the default transaction script (described above) with a transaction
521       script read from a file (-f option). In this case a “transaction”
522       counts as one execution of a script file.
523
524       A script file contains one or more SQL commands terminated by
525       semicolons. Empty lines and lines beginning with -- are ignored. Script
526       files can also contain “meta commands”, which are interpreted by
527       pgbench itself, as described below.
528
529           Note
530           Before PostgreSQL 9.6, SQL commands in script files were terminated
531           by newlines, and so they could not be continued across lines. Now a
532           semicolon is required to separate consecutive SQL commands (though
533           a SQL command does not need one if it is followed by a meta
534           command). If you need to create a script file that works with both
535           old and new versions of pgbench, be sure to write each SQL command
536           on a single line ending with a semicolon.
537
538       There is a simple variable-substitution facility for script files.
539       Variable names must consist of letters (including non-Latin letters),
540       digits, and underscores, with the first character not being a digit.
541       Variables can be set by the command-line -D option, explained above, or
542       by the meta commands explained below. In addition to any variables
543       preset by -D command-line options, there are a few variables that are
544       preset automatically, listed in Table 273. A value specified for these
545       variables using -D takes precedence over the automatic presets. Once
546       set, a variable's value can be inserted into a SQL command by writing
547       :variablename. When running more than one client session, each session
548       has its own set of variables.  pgbench supports up to 255 variable uses
549       in one statement.
550
551       Table 273. pgbench Automatic Variables
552       ┌─────────────┬────────────────────────────┐
553Variable     Description                
554       ├─────────────┼────────────────────────────┤
555       │client_id    │ unique number identifying  │
556       │             │ the client session (starts │
557       │             │ from zero)                 │
558       ├─────────────┼────────────────────────────┤
559       │default_seed │ seed used in hash          │
560       │             │ functions by default       │
561       ├─────────────┼────────────────────────────┤
562       │random_seed  │ random generator seed      │
563       │             │ (unless overwritten with   │
564       │             │ -D)                        │
565       ├─────────────┼────────────────────────────┤
566       │scale        │ current scale factor       │
567       └─────────────┴────────────────────────────┘
568
569       Script file meta commands begin with a backslash (\) and normally
570       extend to the end of the line, although they can be continued to
571       additional lines by writing backslash-return. Arguments to a meta
572       command are separated by white space. These meta commands are
573       supported:
574
575       \gset [prefix] \aset [prefix]
576           These commands may be used to end SQL queries, taking the place of
577           the terminating semicolon (;).
578
579           When the \gset command is used, the preceding SQL query is expected
580           to return one row, the columns of which are stored into variables
581           named after column names, and prefixed with prefix if provided.
582
583           When the \aset command is used, all combined SQL queries (separated
584           by \;) have their columns stored into variables named after column
585           names, and prefixed with prefix if provided. If a query returns no
586           row, no assignment is made and the variable can be tested for
587           existence to detect this. If a query returns more than one row, the
588           last value is kept.
589
590           The following example puts the final account balance from the first
591           query into variable abalance, and fills variables p_two and p_three
592           with integers from the third query. The result of the second query
593           is discarded. The result of the two last combined queries are
594           stored in variables four and five.
595
596               UPDATE pgbench_accounts
597                 SET abalance = abalance + :delta
598                 WHERE aid = :aid
599                 RETURNING abalance \gset
600               -- compound of two queries
601               SELECT 1 \;
602               SELECT 2 AS two, 3 AS three \gset p_
603               SELECT 4 AS four \; SELECT 5 AS five \aset
604
605       \if expression
606       \elif expression
607       \else
608       \endif
609           This group of commands implements nestable conditional blocks,
610           similarly to psql's \if expression. Conditional expressions are
611           identical to those with \set, with non-zero values interpreted as
612           true.
613
614       \set varname expression
615           Sets variable varname to a value calculated from expression. The
616           expression may contain the NULL constant, Boolean constants TRUE
617           and FALSE, integer constants such as 5432, double constants such as
618           3.14159, references to variables :variablename, operators with
619           their usual SQL precedence and associativity, function calls, SQL
620           CASE generic conditional expressions and parentheses.
621
622           Functions and most operators return NULL on NULL input.
623
624           For conditional purposes, non zero numerical values are TRUE, zero
625           numerical values and NULL are FALSE.
626
627           Too large or small integer and double constants, as well as integer
628           arithmetic operators (+, -, * and /) raise errors on overflows.
629
630           When no final ELSE clause is provided to a CASE, the default value
631           is NULL.
632
633           Examples:
634
635               \set ntellers 10 * :scale
636               \set aid (1021 * random(1, 100000 * :scale)) % \
637                          (100000 * :scale) + 1
638               \set divx CASE WHEN :x <> 0 THEN :y/:x ELSE NULL END
639
640       \sleep number [ us | ms | s ]
641           Causes script execution to sleep for the specified duration in
642           microseconds (us), milliseconds (ms) or seconds (s). If the unit is
643           omitted then seconds are the default.  number can be either an
644           integer constant or a :variablename reference to a variable having
645           an integer value.
646
647           Example:
648
649               \sleep 10 ms
650
651       \setshell varname command [ argument ... ]
652           Sets variable varname to the result of the shell command command
653           with the given argument(s). The command must return an integer
654           value through its standard output.
655
656           command and each argument can be either a text constant or a
657           :variablename reference to a variable. If you want to use an
658           argument starting with a colon, write an additional colon at the
659           beginning of argument.
660
661           Example:
662
663               \setshell variable_to_be_assigned command literal_argument :variable ::literal_starting_with_colon
664
665       \shell command [ argument ... ]
666           Same as \setshell, but the result of the command is discarded.
667
668           Example:
669
670               \shell command literal_argument :variable ::literal_starting_with_colon
671
672   Built-in Operators
673       The arithmetic, bitwise, comparison and logical operators listed in
674       Table 274 are built into pgbench and may be used in expressions
675       appearing in \set. The operators are listed in increasing precedence
676       order. Except as noted, operators taking two numeric inputs will
677       produce a double value if either input is double, otherwise they
678       produce an integer result.
679
680       Table 274. pgbench Operators
681       ┌────────────────────────────────────────┐
682       │                                        │
683       │       Operator                         │
684       │                                        │
685       │              .PP Description           │
686       │                                        │
687       │              .PP Example(s)            │
688       ├────────────────────────────────────────┤
689       │                                        │
690boolean OR booleanboolean
691       │                                        │
692       │              .PP Logical OR            │
693       │                                        │
694       │              .PP 5 or 0 → TRUE         │
695       ├────────────────────────────────────────┤
696       │                                        │
697boolean AND booleanboolean
698       │                                        │
699       │              .PP Logical AND           │
700       │                                        │
701       │              .PP 3 and 0 → FALSE       │
702       ├────────────────────────────────────────┤
703       │                                        │
704       │       NOT booleanboolean
705       │                                        │
706       │              .PP Logical NOT           │
707       │                                        │
708       │              .PP not false → TRUE      │
709       ├────────────────────────────────────────┤
710       │                                        │
711boolean IS [NOT]                 │
712       │       (NULL|TRUE|FALSE) → boolean
713       │                                        │
714       │              .PP Boolean value tests   │
715       │                                        │
716       │              .PP 1 is null → FALSE     │
717       ├────────────────────────────────────────┤
718       │                                        │
719value ISNULL|NOTNULL → boolean
720       │                                        │
721       │              .PP Nullness tests        │
722       │                                        │
723       │              .PP 1 notnull → TRUE      │
724       ├────────────────────────────────────────┤
725       │                                        │
726number = numberboolean
727       │                                        │
728       │              .PP Equal                 │
729       │                                        │
730       │              .PP 5 = 4 → FALSE         │
731       ├────────────────────────────────────────┤
732       │                                        │
733number <> numberboolean
734       │                                        │
735       │              .PP Not equal             │
736       │                                        │
737       │              .PP 5 <> 4 → TRUE         │
738       ├────────────────────────────────────────┤
739       │                                        │
740number != numberboolean
741       │                                        │
742       │              .PP Not equal             │
743       │                                        │
744       │              .PP 5 != 5 → FALSE        │
745       ├────────────────────────────────────────┤
746       │                                        │
747number < numberboolean
748       │                                        │
749       │              .PP Less than             │
750       │                                        │
751       │              .PP 5 < 4 → FALSE         │
752       ├────────────────────────────────────────┤
753       │                                        │
754number <= numberboolean
755       │                                        │
756       │              .PP Less than or equal to │
757       │                                        │
758       │              .PP 5 <= 4 → FALSE        │
759       ├────────────────────────────────────────┤
760       │                                        │
761number > numberboolean
762       │                                        │
763       │              .PP Greater than          │
764       │                                        │
765       │              .PP 5 > 4 → TRUE          │
766       ├────────────────────────────────────────┤
767       │                                        │
768number >= numberboolean
769       │                                        │
770       │              .PP Greater than or equal │
771       │       to                               │
772       │                                        │
773       │              .PP 5 >= 4 → TRUE         │
774       ├────────────────────────────────────────┤
775       │                                        │
776integer | integerinteger
777       │                                        │
778       │              .PP Bitwise OR            │
779       │                                        │
780       │              .PP 1 | 2 → 3             │
781       ├────────────────────────────────────────┤
782       │                                        │
783integer # integerinteger
784       │                                        │
785       │              .PP Bitwise XOR           │
786       │                                        │
787       │              .PP 1 # 3 → 2             │
788       ├────────────────────────────────────────┤
789       │                                        │
790integer & integerinteger
791       │                                        │
792       │              .PP Bitwise AND           │
793       │                                        │
794       │              .PP 1 & 3 → 1             │
795       ├────────────────────────────────────────┤
796       │                                        │
797       │       ~ integerinteger
798       │                                        │
799       │              .PP Bitwise NOT           │
800       │                                        │
801       │              .PP ~ 1 → -2              │
802       ├────────────────────────────────────────┤
803       │                                        │
804integer << integerinteger
805       │                                        │
806       │              .PP Bitwise shift left    │
807       │                                        │
808       │              .PP 1 << 2 → 4            │
809       ├────────────────────────────────────────┤
810       │                                        │
811integer >> integerinteger
812       │                                        │
813       │              .PP Bitwise shift right   │
814       │                                        │
815       │              .PP 8 >> 2 → 2            │
816       ├────────────────────────────────────────┤
817       │                                        │
818number + numbernumber
819       │                                        │
820       │              .PP Addition              │
821       │                                        │
822       │              .PP 5 + 4 → 9             │
823       ├────────────────────────────────────────┤
824       │                                        │
825number - numbernumber
826       │                                        │
827       │              .PP Subtraction           │
828       │                                        │
829       │              .PP 3 - 2.0 → 1.0         │
830       ├────────────────────────────────────────┤
831       │                                        │
832number * numbernumber
833       │                                        │
834       │              .PP Multiplication        │
835       │                                        │
836       │              .PP 5 * 4 → 20            │
837       ├────────────────────────────────────────┤
838       │                                        │
839number / numbernumber
840       │                                        │
841       │              .PP Division (truncates   │
842       │       the result towards zero if both  │
843       │       inputs are integers)             │
844       │                                        │
845       │              .PP 5 / 3 → 1             │
846       ├────────────────────────────────────────┤
847       │                                        │
848integer % integerinteger
849       │                                        │
850       │              .PP Modulo (remainder)    │
851       │                                        │
852       │              .PP 3 % 2 → 1             │
853       ├────────────────────────────────────────┤
854       │                                        │
855       │       - numbernumber
856       │                                        │
857       │              .PP Negation              │
858       │                                        │
859       │              .PP - 2.0 → -2.0          │
860       └────────────────────────────────────────┘
861
862   Built-In Functions
863       The functions listed in Table 275 are built into pgbench and may be
864       used in expressions appearing in \set.
865
866       Table 275. pgbench Functions
867       ┌────────────────────────────────────────┐
868       │                                        │
869       │       Function                         │
870       │                                        │
871       │              .PP Description           │
872       │                                        │
873       │              .PP Example(s)            │
874       ├────────────────────────────────────────┤
875       │                                        │
876abs ( number ) → same type as    │
877       │       input                            │
878       │                                        │
879       │              .PP Absolute value        │
880       │                                        │
881       │              .PP abs(-17) → 17         │
882       ├────────────────────────────────────────┤
883       │                                        │
884debug ( number ) → same type as  │
885       │       input                            │
886       │                                        │
887       │              .PP Prints the argument   │
888       │       to stderr, and returns the       │
889       │       argument.                        │
890       │                                        │
891       │              .PP debug(5432.1) →       │
892       │       5432.1                           │
893       ├────────────────────────────────────────┤
894       │                                        │
895double ( number ) → double       │
896       │                                        │
897       │              .PP Casts to double.      │
898       │                                        │
899       │              .PP double(5432) → 5432.0 │
900       ├────────────────────────────────────────┤
901       │                                        │
902exp ( number ) → double          │
903       │                                        │
904       │              .PP Exponential (e raised │
905       │       to the given power)              │
906       │                                        │
907       │              .PP exp(1.0) →            │
908       │       2.718281828459045                │
909       ├────────────────────────────────────────┤
910       │                                        │
911greatest ( number [, ... ] ) →   │
912       │       double if any argument is        │
913       │       double, else integer             │
914       │                                        │
915       │              .PP Selects the largest   │
916       │       value among the arguments.       │
917       │                                        │
918       │              .PP greatest(5, 4, 3, 2)  │
919       │       → 5                              │
920       ├────────────────────────────────────────┤
921       │                                        │
922hash ( value [, seed ] ) →       │
923       │       integer                          │
924       │                                        │
925       │              .PP This is an alias for  │
926hash_murmur2.                    │
927       │                                        │
928       │              .PP hash(10, 5432) →      │
929       │       -5817877081768721676             │
930       ├────────────────────────────────────────┤
931       │                                        │
932hash_fnv1a ( value [, seed ] ) → │
933       │       integer                          │
934       │                                        │
935       │              .PP Computes FNV-1a hash. │
936       │                                        │
937       │              .PP hash_fnv1a(10, 5432)  │
938       │       → -7793829335365542153           │
939       ├────────────────────────────────────────┤
940       │                                        │
941hash_murmur2 ( value [, seed ] ) │
942       │       → integer                        │
943       │                                        │
944       │              .PP Computes MurmurHash2  
945       │       hash.                            │
946       │                                        │
947       │              .PP hash_murmur2(10,      │
948       │       5432) → -5817877081768721676     │
949       ├────────────────────────────────────────┤
950       │                                        │
951int ( number ) → integer         │
952       │                                        │
953       │              .PP Casts to integer.     │
954       │                                        │
955       │              .PP int(5.4 + 3.8) → 9    │
956       ├────────────────────────────────────────┤
957       │                                        │
958least ( number [, ... ] ) →      │
959       │       double if any argument is        │
960       │       double, else integer             │
961       │                                        │
962       │              .PP Selects the smallest  │
963       │       value among the arguments.       │
964       │                                        │
965       │              .PP least(5, 4, 3, 2.1) → │
966       │       2.1                              │
967       ├────────────────────────────────────────┤
968       │                                        │
969ln ( number ) → double           │
970       │                                        │
971       │              .PP Natural logarithm     │
972       │                                        │
973       │              .PP ln(2.718281828459045) │
974       │       → 1.0                            │
975       ├────────────────────────────────────────┤
976       │                                        │
977mod ( integer, integer ) →       │
978       │       integer                          │
979       │                                        │
980       │              .PP Modulo (remainder)    │
981       │                                        │
982       │              .PP mod(54, 32) → 22      │
983       ├────────────────────────────────────────┤
984       │                                        │
985pi () → double                   │
986       │                                        │
987       │              .PP Approximate value of  │
988       │       π                                │
989       │                                        │
990       │              .PP pi() →                │
991       │       3.14159265358979323846           │
992       ├────────────────────────────────────────┤
993       │                                        │
994pow ( x, y ) → double            │
995       │                                        │
996       │              .PP power ( x, y ) →      │
997       │       double                           │
998       │                                        │
999       │              .PP x raised to the power │
1000       │       of y
1001       │                                        │
1002       │              .PP pow(2.0, 10) → 1024.0 │
1003       ├────────────────────────────────────────┤
1004       │                                        │
1005random ( lb, ub ) → integer      │
1006       │                                        │
1007       │              .PP Computes a            │
1008       │       uniformly-distributed random     │
1009       │       integer in [lb, ub].             │
1010       │                                        │
1011       │              .PP random(1, 10) → an    │
1012       │       integer between 1 and 10         │
1013       ├────────────────────────────────────────┤
1014       │                                        │
1015random_exponential ( lb, ub,     │
1016parameter ) → integer            │
1017       │                                        │
1018       │              .PP Computes an           │
1019       │       exponentially-distributed random │
1020       │       integer in [lb, ub], see below.  │
1021       │                                        │
1022       │              .PP random_exponential(1, │
1023       │       10, 3.0) → an integer between 1  │
1024       │       and 10                           │
1025       ├────────────────────────────────────────┤
1026       │                                        │
1027random_gaussian ( lb, ub,        │
1028parameter ) → integer            │
1029       │                                        │
1030       │              .PP Computes a            │
1031       │       Gaussian-distributed random      │
1032       │       integer in [lb, ub], see below.  │
1033       │                                        │
1034       │              .PP random_gaussian(1,    │
1035       │       10, 2.5) → an integer between 1  │
1036       │       and 10                           │
1037       ├────────────────────────────────────────┤
1038       │                                        │
1039random_zipfian ( lb, ub,         │
1040parameter ) → integer            │
1041       │                                        │
1042       │              .PP Computes a            │
1043       │       Zipfian-distributed random       │
1044       │       integer in [lb, ub], see below.  │
1045       │                                        │
1046       │              .PP random_zipfian(1, 10, │
1047       │       1.5) → an integer between 1 and  │
1048       │       10                               │
1049       ├────────────────────────────────────────┤
1050       │                                        │
1051sqrt ( number ) → double         │
1052       │                                        │
1053       │              .PP Square root           │
1054       │                                        │
1055       │              .PP sqrt(2.0) →           │
1056       │       1.414213562                      │
1057       └────────────────────────────────────────┘
1058
1059       The random function generates values using a uniform distribution, that
1060       is all the values are drawn within the specified range with equal
1061       probability. The random_exponential, random_gaussian and random_zipfian
1062       functions require an additional double parameter which determines the
1063       precise shape of the distribution.
1064
1065       •   For an exponential distribution, parameter controls the
1066           distribution by truncating a quickly-decreasing exponential
1067           distribution at parameter, and then projecting onto integers
1068           between the bounds. To be precise, with
1069
1070               f(x) = exp(-parameter * (x - min) / (max - min + 1)) / (1 - exp(-parameter))
1071
1072           Then value i between min and max inclusive is drawn with
1073           probability: f(i) - f(i + 1).
1074
1075           Intuitively, the larger the parameter, the more frequently values
1076           close to min are accessed, and the less frequently values close to
1077           max are accessed. The closer to 0 parameter is, the flatter (more
1078           uniform) the access distribution. A crude approximation of the
1079           distribution is that the most frequent 1% values in the range,
1080           close to min, are drawn parameter% of the time. The parameter value
1081           must be strictly positive.
1082
1083       •   For a Gaussian distribution, the interval is mapped onto a standard
1084           normal distribution (the classical bell-shaped Gaussian curve)
1085           truncated at -parameter on the left and +parameter on the right.
1086           Values in the middle of the interval are more likely to be drawn.
1087           To be precise, if PHI(x) is the cumulative distribution function of
1088           the standard normal distribution, with mean mu defined as (max +
1089           min) / 2.0, with
1090
1091               f(x) = PHI(2.0 * parameter * (x - mu) / (max - min + 1)) /
1092                      (2.0 * PHI(parameter) - 1)
1093
1094           then value i between min and max inclusive is drawn with
1095           probability: f(i + 0.5) - f(i - 0.5). Intuitively, the larger the
1096           parameter, the more frequently values close to the middle of the
1097           interval are drawn, and the less frequently values close to the min
1098           and max bounds. About 67% of values are drawn from the middle 1.0 /
1099           parameter, that is a relative 0.5 / parameter around the mean, and
1100           95% in the middle 2.0 / parameter, that is a relative 1.0 /
1101           parameter around the mean; for instance, if parameter is 4.0, 67%
1102           of values are drawn from the middle quarter (1.0 / 4.0) of the
1103           interval (i.e., from 3.0 / 8.0 to 5.0 / 8.0) and 95% from the
1104           middle half (2.0 / 4.0) of the interval (second and third
1105           quartiles). The minimum allowed parameter value is 2.0.
1106
1107       •   random_zipfian generates a bounded Zipfian distribution.  parameter
1108           defines how skewed the distribution is. The larger the parameter,
1109           the more frequently values closer to the beginning of the interval
1110           are drawn. The distribution is such that, assuming the range starts
1111           from 1, the ratio of the probability of drawing k versus drawing
1112           k+1 is ((k+1)/k)**parameter. For example, random_zipfian(1, ...,
1113           2.5) produces the value 1 about (2/1)**2.5 = 5.66 times more
1114           frequently than 2, which itself is produced (3/2)**2.5 = 2.76 times
1115           more frequently than 3, and so on.
1116
1117           pgbench's implementation is based on "Non-Uniform Random Variate
1118           Generation", Luc Devroye, p. 550-551, Springer 1986. Due to
1119           limitations of that algorithm, the parameter value is restricted to
1120           the range [1.001, 1000].
1121
1122       Hash functions hash, hash_murmur2 and hash_fnv1a accept an input value
1123       and an optional seed parameter. In case the seed isn't provided the
1124       value of :default_seed is used, which is initialized randomly unless
1125       set by the command-line -D option. Hash functions can be used to
1126       scatter the distribution of random functions such as random_zipfian or
1127       random_exponential. For instance, the following pgbench script
1128       simulates possible real world workload typical for social media and
1129       blogging platforms where few accounts generate excessive load:
1130
1131           \set r random_zipfian(0, 100000000, 1.07)
1132           \set k abs(hash(:r)) % 1000000
1133
1134       In some cases several distinct distributions are needed which don't
1135       correlate with each other and this is when implicit seed parameter
1136       comes in handy:
1137
1138           \set k1 abs(hash(:r, :default_seed + 123)) % 1000000
1139           \set k2 abs(hash(:r, :default_seed + 321)) % 1000000
1140
1141       As an example, the full definition of the built-in TPC-B-like
1142       transaction is:
1143
1144           \set aid random(1, 100000 * :scale)
1145           \set bid random(1, 1 * :scale)
1146           \set tid random(1, 10 * :scale)
1147           \set delta random(-5000, 5000)
1148           BEGIN;
1149           UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;
1150           SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
1151           UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;
1152           UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;
1153           INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
1154           END;
1155
1156       This script allows each iteration of the transaction to reference
1157       different, randomly-chosen rows. (This example also shows why it's
1158       important for each client session to have its own variables — otherwise
1159       they'd not be independently touching different rows.)
1160
1161   Per-Transaction Logging
1162       With the -l option (but without the --aggregate-interval option),
1163       pgbench writes information about each transaction to a log file. The
1164       log file will be named prefix.nnn, where prefix defaults to
1165       pgbench_log, and nnn is the PID of the pgbench process. The prefix can
1166       be changed by using the --log-prefix option. If the -j option is 2 or
1167       higher, so that there are multiple worker threads, each will have its
1168       own log file. The first worker will use the same name for its log file
1169       as in the standard single worker case. The additional log files for the
1170       other workers will be named prefix.nnn.mmm, where mmm is a sequential
1171       number for each worker starting with 1.
1172
1173       The format of the log is:
1174
1175           client_id transaction_no time script_no time_epoch time_us [ schedule_lag ]
1176
1177       where client_id indicates which client session ran the transaction,
1178       transaction_no counts how many transactions have been run by that
1179       session, time is the total elapsed transaction time in microseconds,
1180       script_no identifies which script file was used (useful when multiple
1181       scripts were specified with -f or -b), and time_epoch/time_us are a
1182       Unix-epoch time stamp and an offset in microseconds (suitable for
1183       creating an ISO 8601 time stamp with fractional seconds) showing when
1184       the transaction completed. The schedule_lag field is the difference
1185       between the transaction's scheduled start time, and the time it
1186       actually started, in microseconds. It is only present when the --rate
1187       option is used. When both --rate and --latency-limit are used, the time
1188       for a skipped transaction will be reported as skipped.
1189
1190       Here is a snippet of a log file generated in a single-client run:
1191
1192           0 199 2241 0 1175850568 995598
1193           0 200 2465 0 1175850568 998079
1194           0 201 2513 0 1175850569 608
1195           0 202 2038 0 1175850569 2663
1196
1197       Another example with --rate=100 and --latency-limit=5 (note the
1198       additional schedule_lag column):
1199
1200           0 81 4621 0 1412881037 912698 3005
1201           0 82 6173 0 1412881037 914578 4304
1202           0 83 skipped 0 1412881037 914578 5217
1203           0 83 skipped 0 1412881037 914578 5099
1204           0 83 4722 0 1412881037 916203 3108
1205           0 84 4142 0 1412881037 918023 2333
1206           0 85 2465 0 1412881037 919759 740
1207
1208       In this example, transaction 82 was late, because its latency (6.173
1209       ms) was over the 5 ms limit. The next two transactions were skipped,
1210       because they were already late before they were even started.
1211
1212       When running a long test on hardware that can handle a lot of
1213       transactions, the log files can become very large. The --sampling-rate
1214       option can be used to log only a random sample of transactions.
1215
1216   Aggregated Logging
1217       With the --aggregate-interval option, a different format is used for
1218       the log files:
1219
1220           interval_start num_transactions sum_latency sum_latency_2 min_latency max_latency [ sum_lag sum_lag_2 min_lag max_lag [ skipped ] ]
1221
1222       where interval_start is the start of the interval (as a Unix epoch time
1223       stamp), num_transactions is the number of transactions within the
1224       interval, sum_latency is the sum of the transaction latencies within
1225       the interval, sum_latency_2 is the sum of squares of the transaction
1226       latencies within the interval, min_latency is the minimum latency
1227       within the interval, and max_latency is the maximum latency within the
1228       interval. The next fields, sum_lag, sum_lag_2, min_lag, and max_lag,
1229       are only present if the --rate option is used. They provide statistics
1230       about the time each transaction had to wait for the previous one to
1231       finish, i.e., the difference between each transaction's scheduled start
1232       time and the time it actually started. The very last field, skipped, is
1233       only present if the --latency-limit option is used, too. It counts the
1234       number of transactions skipped because they would have started too
1235       late. Each transaction is counted in the interval when it was
1236       committed.
1237
1238       Here is some example output:
1239
1240           1345828501 5601 1542744 483552416 61 2573
1241           1345828503 7884 1979812 565806736 60 1479
1242           1345828505 7208 1979422 567277552 59 1391
1243           1345828507 7685 1980268 569784714 60 1398
1244           1345828509 7073 1979779 573489941 236 1411
1245
1246       Notice that while the plain (unaggregated) log file shows which script
1247       was used for each transaction, the aggregated log does not. Therefore
1248       if you need per-script data, you need to aggregate the data on your
1249       own.
1250
1251   Per-Statement Latencies
1252       With the -r option, pgbench collects the elapsed transaction time of
1253       each statement executed by every client. It then reports an average of
1254       those values, referred to as the latency for each statement, after the
1255       benchmark has finished.
1256
1257       For the default script, the output will look similar to this:
1258
1259           starting vacuum...end.
1260           transaction type: <builtin: TPC-B (sort of)>
1261           scaling factor: 1
1262           query mode: simple
1263           number of clients: 10
1264           number of threads: 1
1265           number of transactions per client: 1000
1266           number of transactions actually processed: 10000/10000
1267           latency average = 15.844 ms
1268           latency stddev = 2.715 ms
1269           tps = 618.764555 (including connections establishing)
1270           tps = 622.977698 (excluding connections establishing)
1271           statement latencies in milliseconds:
1272                   0.002  \set aid random(1, 100000 * :scale)
1273                   0.005  \set bid random(1, 1 * :scale)
1274                   0.002  \set tid random(1, 10 * :scale)
1275                   0.001  \set delta random(-5000, 5000)
1276                   0.326  BEGIN;
1277                   0.603  UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;
1278                   0.454  SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
1279                   5.528  UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;
1280                   7.335  UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;
1281                   0.371  INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
1282                   1.212  END;
1283
1284       If multiple script files are specified, the averages are reported
1285       separately for each script file.
1286
1287       Note that collecting the additional timing information needed for
1288       per-statement latency computation adds some overhead. This will slow
1289       average execution speed and lower the computed TPS. The amount of
1290       slowdown varies significantly depending on platform and hardware.
1291       Comparing average TPS values with and without latency reporting enabled
1292       is a good way to measure if the timing overhead is significant.
1293
1294   Good Practices
1295       It is very easy to use pgbench to produce completely meaningless
1296       numbers. Here are some guidelines to help you get useful results.
1297
1298       In the first place, never believe any test that runs for only a few
1299       seconds. Use the -t or -T option to make the run last at least a few
1300       minutes, so as to average out noise. In some cases you could need hours
1301       to get numbers that are reproducible. It's a good idea to try the test
1302       run a few times, to find out if your numbers are reproducible or not.
1303
1304       For the default TPC-B-like test scenario, the initialization scale
1305       factor (-s) should be at least as large as the largest number of
1306       clients you intend to test (-c); else you'll mostly be measuring update
1307       contention. There are only -s rows in the pgbench_branches table, and
1308       every transaction wants to update one of them, so -c values in excess
1309       of -s will undoubtedly result in lots of transactions blocked waiting
1310       for other transactions.
1311
1312       The default test scenario is also quite sensitive to how long it's been
1313       since the tables were initialized: accumulation of dead rows and dead
1314       space in the tables changes the results. To understand the results you
1315       must keep track of the total number of updates and when vacuuming
1316       happens. If autovacuum is enabled it can result in unpredictable
1317       changes in measured performance.
1318
1319       A limitation of pgbench is that it can itself become the bottleneck
1320       when trying to test a large number of client sessions. This can be
1321       alleviated by running pgbench on a different machine from the database
1322       server, although low network latency will be essential. It might even
1323       be useful to run several pgbench instances concurrently, on several
1324       client machines, against the same database server.
1325
1326   Security
1327       If untrusted users have access to a database that has not adopted a
1328       secure schema usage pattern, do not run pgbench in that database.
1329       pgbench uses unqualified names and does not manipulate the search path.
1330
1331
1332
1333PostgreSQL 13.4                      2021                           PGBENCH(1)
Impressum