PG_FORMAT(1)
πΈ NAME πΈ
pg_format(1) β User Contributed Perl Documentation π«Ά
pg_format β PostgreSQL SQL syntax beautifier π
β¨ DESCRIPTION β¨
Okay bestie, listen: this is a SQL formatter/beautifier, and it is literally that girl. It supports keywords from SQL-92, SQL-99, SQL-2003, SQL-2008, SQL-2011 and PostgreSQL-specific keywords. It works with any other databases too, no cap. π¦
pgFormatter can work as a console program or as a CGI. It will automatically detect its environment and format output as text or as HTML following the context. It can also return a JSON-formatted response if used as CGI with 'Accept: application/json'. β¨
Keywords highlighting will only be available in CGI context. That's the vibe check. π
π» Terminal/console execution π»
Usage:
pg_format [options] file.sql
PostgreSQL SQL queries and PL/PGSQL code beautifier. π
π«Ά Arguments π«Ά
file.sqlcan be a file, multiple files or use-to read query from stdin.- Returning the SQL formatted to stdout or into a file specified with the
-o|--outputoption.
βοΈ Options βοΈ
-a,--anonymizeβ obscure all literals in queries, useful to hide confidential data before formatting.-b,--comma-startβ in a parameters list, start with the comma (see-e).-B,--comma-breakβ in insert statement, add a newline after each comma.-c,--config FILEβ use a configuration file. Default is to not use configuration file unless files./.pg_formator$HOME/.pg_formator the XDG Base Directory file$XDG_CONFIG_HOME/pg_format/pg_format.confexist.-C,--wrap-commentβ with--wrap-limit, apply reformatting to comments.-d,--debugβ enable debug mode. Disabled by default.-e,--comma-endβ in a parameters list, end with the comma (default).-f,--function-case Nβ Change the case of the PostgreSQL functions. Default is unchanged:0. Values:0=>unchanged,1=>lowercase,2=>uppercase,3=>capitalize.-F,--format STRβ output format:textorhtml. Default:text.-g,--nogroupingβ add a newline between statements in transaction regroupement. Default is to group statements.-h,--helpβ show this message and exit.-i,--inplaceβ override input files with formatted content.-k,--keep-newlineβ preserve empty line in plpgsql code.-L,--no-extra-lineβ do not add an extra empty line at end of the output.-m,--maxlength SIZEβ maximum length of a query, it will be cutted above the given size. Default: no truncate.-M,--multilineβ enable multi-line search for-por--placeholder.-n,--nocommentβ remove any comment from SQL code.-N,--numberingβ statement numbering as a comment before each query.-o,--output fileβ define the filename for the output. Default:stdout.-p,--placeholder REβ set regex to find code that must not be changed.-r,--redshiftβ add RedShift keyworks to the list of SQL keyworks. Obsolete now, use--extra-keyword 'redshift'instead.-s,--spaces sizeβ change space indent, default4spaces.-S,--separator STRβ dynamic code separator, default to single quote.-t,--format-typeβ try another formatting type for some statements.-T,--tabsβ use tabs instead of space characters, when used spaces is set to1whatever is the value set to-s.-u,--keyword-case Nβ Change the case of the reserved keyword. Default is uppercase:2. Values:0=>unchanged,1=>lowercase,2=>uppercase,3=>capitalize.-U,--type-case Nβ Change the case of the data type name. Default is lowercase:1. Values:0=>unchanged,1=>lowercase,2=>uppercase,3=>capitalize.-v,--versionβ showpg_formatversion and exit.-w,--wrap-limit Nβ wrap queries at a certain length.-W,--wrap-after Nβ number of column after which lists must be wrapped. Default: puts every item on its own line.-X,--no-rcfileβ don't read rc files automatically (./.pg_formator$HOME/.pg_formator$XDG_CONFIG_HOME/pg_format). The--config/-coption overrides it.--extra-function FILEβ file containing a list of functions to use the same formatting as PostgreSQL internal function.--extra-keyword FILEβ file containing a list of keywords to use the same formatting as PostgreSQL internal keyword. Use special value'redshift'for support to Redshift keywords defined internaly in pgFormatter.--no-space-functionβ remove space between function call and the open parenthesis.--redundant-parenthesisβ do not remove redundant parenthesis in DML.
β¨ Examples β¨
cat samples/ex1.sql | pg_format -
pg_format -n samples/ex1.sql
pg_format -f 2 -n -o result.sql samples/ex1.sql
π CGI context π
Install pg_format into your cgi-bin folder, grant execution on it as a CGI script (maybe you should add the .cgi extension) and get it from your favorite browser. Copy files logo_pgformatter.png and icon_pgformatter.ico in the CGI directory, pg_format.cgi look for them in the same repository. π
The page says there's a live example "without limitation than ten thousand characters in your SQL query" here:
http://sqlformat.darold.net/
pg_format will automatically detected that it is running in a CGI environment and will output all html code needed to run an online code formatter site. There's nothing more to do. π¦
You need to install the Perl CGI and JSON modules first. If it is not already the case do:
yum install perl-cgi
yum install perl-json
or
apt install libcgi-pm-perl
apt install libjson-perl
following your distribution. πΈ
π¦ INSTALLATION π¦
Following your Linux distribution you might need to install the autodie Perl module:
sudo yum -y install perl-autodie
Download the tarball from github and unpack the archive as follow:
version=5.3 #please use the latest release version from github
wget https://github.com/darold/pgFormatter/archive/refs/tags/v${version}.tar.gz
tar xzf v${version}.tar.gz
cd pgFormatter-${version}/
perl Makefile.PL
make && sudo make install
cd ../ && rm -rf v${version}.tar.gz && rm -rf pgFormatter-${version} #clean up
This will copy the Perl script pg_format in /usr/local/bin/pg_format directory by default and the man page into /usr/local/share/man/man1/pg_format.1. Those are the default installation directory for 'site' install. π
If you want to install all under /usr/ location, use INSTALLDIRS='perl' as argument of Makefile.PL. The script will be installed into /usr/bin/pg_format and the manpage into /usr/share/man/man1/pg_format.1. π
For example, to install everything just like Debian does, proceed as follow:
perl Makefile.PL INSTALLDIRS=vendor
By default INSTALLDIRS is set to site. π«Ά
Regression tests can be executed with the following command:
make test
If you have docker installed you can build a pgFormatter image using:
docker build -t darold.net/pgformatter .
then just use it as
cat file.sql | docker run --rm -a stdin -a stdout -i darold.net/pgformatter -
β¨ SPECIAL FORMATTING β¨
Okay so this is the part where pgFormatter gets β¨opinionatedβ¨ and honestly? Same.
π Option -W, --wrap-after
This one lets you say "wrap my lists after n columns." By default pgFormatter puts every single item on its own line β very one-per-line, very minimalist of it. This format applies to the SELECT and FROM list, iykyk.
So like, this query:
SELECT a, b, c, d FROM t_1, t_2, t3 WHERE a = 10 AND b = 10;
with -W 4 becomes this:
SELECT a, b, c, d
FROM t_1, t_2, t3
WHERE a = 10
AND b = 10;
Heads up bestie: this formatting doesn't fit well with sub queries in a list. Just saying π
πΈ Option -w, --wrap-limit
This one wraps queries at a certain length β and it does not care what part of the query it's at when it hits that limit, unless it's a comment. Fr fr. So if the limit gets reached in the middle of a text constant, the text literally gets wrapped. Indentation is not included in the character count, slay. And this option applies in all cases, even if you've got other options going on.
π¦ Option -C, --wrap-comment
Wraps comments at the length defined by -w, --wrap-limit, whatever part of the comment it happens to be at. Again, indentation is not included in the character count. Periodt.
π
Option -t, --format-type
This activates an alternative formatting that adds:
- newline in procedure/function parameter list
- new line in
PUBLICATIONandPOLICYDDL - keep enumeration in
GROUP BYclause on a single line
Expect this list to grow following alternative thoughts π
π§ Option -g, --nogrouping
By default pgFormatter groups all statements when they're in a transaction:
BEGIN;
INSERT INTO foo VALUES (1, 'text 1');
INSERT INTO foo VALUES (2, 'text 2');
...
COMMIT;
By disabling grouping of statements, pgFormatter will always add an extra newline character between statements, just like outside a transaction:
BEGIN;
INSERT INTO foo VALUES (1, 'text 1');
INSERT INTO foo VALUES (2, 'text 2');
...
COMMIT;
This might add readability to not-DML transactions. Cute!
π Option -L, --no-extra-line
By default pgFormatter always adds an empty line after the end of a statement when it's terminated by a ; β except in a plpgsql code block. If that extra empty line at the end of the output is useless to you, you can remove it by adding this option to the command line. Bye bye blank line π«Ά
β Option --extra-function
pgFormatter applies some formatting to PostgreSQL internal function calls, but it can't detect user defined functions. So you can define a list of functions in a file (one function name per line) and hand it to pgFormatter through the --extra-function option β and those will be formatted as PostgreSQL internal functions. Iconic behavior.
π Option --extra-keyword
pgFormatter applies some formatting to PostgreSQL internal keywords but it can't detect keywords for other databases. So: define a list of keywords in a file (one keyword per line) and give it to pgFormatter through the --extra-keyword option, and it'll be formatted as PostgreSQL internal functions.
You can also pass a special value 'redshift' that'll load the keywords defined internally in pgFormatter for that database. This was historically possible through the -r | --redshift option, which is now obsolete and will be removed in the future. RIP to a real one π
π Option --no-space-function
Use this option to remove the space character between a function call and the open parenthesis that follows it. By default pgFormatter adds a space character, like:
DROP FUNCTION IF EXISTS app_public.hello (a text);
When this option is used, the resulting query is formatted as follows:
DROP FUNCTION IF EXISTS app_public.hello(a text);
No cap, that's the whole vibe shift.
π Option --redundant-parenthesis
By default pgFormatter tries to remove redundant parenthesis in DML, but in some cases they must be preserved. Using this option keeps redundant parenthesis untouched. Leave my parentheses ALONE π
π Option --vertical-align
Use this option to vertically align direct, single-line column definitions inside CREATE TABLE statements. It aligns column names, data types, column constraints such as DEFAULT, and trailing comments. For example:
CREATE TABLE example (
id serial PRIMARY KEY, -- some comment
name varchar(100) NOT NULL, -- another comment
email varchar(100) NOT NULL, -- third comment
created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP -- last comment
);
Look at that alignment. Chef's kiss. π€
Table-level constraints and multiline column definitions are preserved but are not included in the alignment calculation. The option is disabled by default and only applies to text output.
π HINTS π
πΈ Configuration
If the default settings of pg_format don't fit all your needs, you can customize the behavior of pg_format by using a configuration file instead of repeating the command line options over and over (exhausting). By default pgFormatter looks for files ./.pg_format or $HOME/.pg_format or $XDG_CONFIG_HOME/pg_format/pg_format.conf if they exist β but you can choose an alternate configuration file using the command line option -c | --config.
To customize the CGI pg_format.cgi, look for a configuration file named pg_format.conf in the same directory as the CGI script.
For a sample configuration file, see doc/pg_format.conf.sample.
To prevent pg_format from looking at $XDG_CONFIG_HOME/pg_format or $HOME/.pg_format files, you can use the command line option -X | --no-rcfile.
π¦ Formatting from stdin
You can execute pg_format without any argument, or with -, to give the SQL code to format through stdin.
If you use the interactive mode, you have to type ctrl+d after typing your SQL statement to format, to end the typing.
$ pg_format
select * from customers;
< ctrl+d >
You can use stdin in a one-liner as follows:
echo "select * from customers;" | pg_format
π Formatting from VI
With pgFormatter, you can just add the following line to your ~/.vimrc file:
au FileType sql setl formatprg=/usr/local/bin/pg_format\ -
This lets your gq commands use pgFormatter automagically β¨ For example, if you're on the first line, typing:
ESC+gq+G
will format the entire file.
ESC+gq+2j
will format the next two lines.
Thanks to David Fetter for the hint π
There's also the (Neo)vim plugin for formatting code for many file types that supports pg_format to format the SQL file type. Thanks to Anders Riutta for the patch to (Neo)vim.
π§ Formatting from Atom
If you use atom as your favorite editor, you can install the pg-formatter package, which is a Node.js wrapper of pgFormatter.
Features:
- Format selected text or a whole file via keyboard shortcut or command.
- Format SQL files on save.
Installation:
Search for pg-formatter in the Atom UI or get it via command line:
apm install pg-formatter
Usage:
Hit Ctrl-Alt-F to format selected text (or a whole file), or define your shortcut:
'ctrl-alt-p': 'pg-formatter:format'
Also, you can automatically format SQL files on save (disabled by default).
You can download the package from the url:
https://atom.io/packages/pg-formatter
the sources are available at https://github.com/gajus/pg-formatter
Thanks to Alex Fedoseev for the atom package π«Ά
π Formatting from Visual Studio
Thanks to Brady Holt, a Visual Studio Code extension is available to format PostgresSQL SQL using pgFormatter.
https://marketplace.visualstudio.com/items?itemName=bradymholt.pgformatter
For installation and use, have a look at the URL above.
β Prevent replacing code snippets
Using the -p or --placeholder command line option, it's possible to keep code untouched by pgFormatter in your SQL queries. For example, in a query like:
SELECT * FROM projects WHERE projectnumber
IN <<internalprojects>> AND username = <<loginname>>;
you may want pgFormatter to not interpret << and >> as bit-shift keywords and modify your code snippets. You can use a Perl regular expression to instruct pgFormatter to keep some part of the query untouched. For example:
pg_format samples/ex9.sql -p '<<(?:.*)?>>'
will not format the bit-shift like operators. Literally saving your code.
If you'd like to wrap queries after 60 characters (-w 60) and apply that limit to comments as well (-C), then urls in comments may get wrapped. If you'd prefer not to wrap urls, you can use a regular expression to avoid wrapping urls. For example:
pg_format samples/ex62.sql -C -w 60 -p 'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)'
will wrap the queries and the comments, but not the urls. Obsessed with a regex that minds its own business π
π Prevent dynamic code formatting
By default pgFormatter takes all code between single quotes as a string constant and does not perform any formatting on this code. It's common to use a string as a code separator to avoid doubling single quotes in dynamic code generation β in this case pgFormatter can fail to auto-detect the code separator. By default it will search for any string after the EXECUTE keyword starting with a dollar sign. If it can't auto-detect your code separator, you can use the command line option -S or --separator to set the code separator that must be used.
π Node.js thin-wrapper
Gajus Kuizinas has written a Node.js wrapper for executing pgFormatter. You can find it at https://github.com/gajus/pg-formatter
π Customize CSS for the CGI output
You can change the HTML style rendered through the default CSS style by creating a file named custom_css_file.css into the pgFormatter CGI script directory. The default CSS will be fully overridden by this custom file content. You have to look at the generated HTML output to get the default CSS code used.
π Using pgFormatter as an API
You may use pgFormatter as an API by setting the 'Accept' HTTP header to the value 'application/json' when calling it as a CGI app. In case you do not want to enable this feature, set "$self->{ 'enable_api' } = 0" in the "set_config" sub of lib/pgFormatter/CGI.pm.
π USING AS PRE-COMMIT HOOK π
- repo: https://github.com/darold/pgFormatter
rev: "v5.8"
hooks:
- id: pg_format
args: ["--inplace", "--wrap-limit", "120"]
files: '.*\.sql$'
Automate your formatting, bestie. Never hand-format again π
β¨ AUTHORS β¨
pgFormatter is an original work from Gilles Darold, with major code refactoring by Hubert depesz Lubaczewski. Legends, both of them π
πΈ COPYRIGHT πΈ
Copyright 2012-2026 Gilles Darold. All rights reserved.
π¦ LICENSE π¦
pgFormatter is free software distributed under the PostgreSQL Licence.
A modified version of the SQL::Beautify Perl Module is embedded in pgFormatter with copyright (C) 2009 by Jonas Kramer and is published under the terms of the Artistic License 2.0.
okay that's the whole glow-up π« this was perl v5.42.2, dated 2026-09-04, and you just read PG_FORMAT(1) β go forth and format, bestie, mwah π«Άπ
π¦ where this page comes from
- arch rolling: pgformatter 5.11-1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms