Obtain the PostgreSQL version number

The server version can be obtained from the SHOW command:

postgres=# SHOW server_version;
(1 row)

However the value returned cannot be further manipulated at SQL level.

Detailed version information about the server can be obtained from the version() function:

postgres=# SELECT version();
 PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 8.3.1 20191121 (Red Hat 8.3.1-5), 64-bit
(1 row)

However this is tricky and inconvenient to parse if all that's required is the actual version number, particularly in the numbers-only notation (e.g. 110002) which is useful for comparison operations.

The pg_settings view provides the server version information directly:

postgres=# SELECT name, setting FROM pg_settings WHERE name LIKE 'server_version%';
        name        | setting 
 server_version     | 13.1
 server_version_num | 130001
(2 rows)

Alternatively extract individual values with the current_setting() function:

postgres=# SELECT current_setting('server_version');
(1 row)

Applications can use libpq's PQserverVersion() function (documentation) which returns the same integer as server_version_num. Each language's database driver should be able to provide this too.