Get the current timeline

PostgreSQL 9.6 and later

From PostgreSQL 9.6 the current timeline can be retrieved from the function pg_control_checkpoint():

postgres=# SELECT timeline_id FROM pg_control_checkpoint();
(1 row)

(Note: on a standby, if a timeline switch has just taken place, the value returned by pg_control_checkpoint() may be the previous imeline, which will not be updated until the next restart point.)

Alternatively, on a standby the view pg_stat_wal_receiver also provides the current timeline:

postgres=# SELECT pid, status, received_lsn, received_tli FROM pg_stat_wal_receiver;
  pid  |  status   | received_lsn | received_tli
 11969 | streaming | 0/30015B0    |            1
(1 row)

PostgreSQL 9.5 and earlier

Before 9.6 there was no simple method to explicitly retrieve the current timeline as a standalone value and one of the following workarounds must be used.

At database level it can be retrieved indirectly by executing:

SELECT pg_xlogfile_name(pg_current_xlog_insert_location()); 

This will return the current WAL filename, the first 8 digits of which contains the timeline (this can only be executed on a primary node).

A variant of the above which extracts the timeline as an integer:

SELECT SUBSTR(pg_xlogfile_name(pg_current_xlog_insert_location()), 1, 8)::INT AS timeline;

Using pg_controldata

Current timeline information is returned by pg_controldata:

$ pg_controldata /path/to/postgres/data/ | grep -i timeline
Latest checkpoint's TimeLineID:       1
Latest checkpoint's PrevTimeLineID:   1
Min recovery ending loc's timeline:   0

Using a replication connection

The current timeline can also be obtained by initiating a replication connection to the server and issuing IDENTIFY_SYSTEM:

$ psql "dbname=postgres host=localhost user=repl_user replication=1"
psql (9.5.3)
Type "help" for help.

      systemid       | timeline |  xlogpos  | dbname
 6301592708518993068 |        1 | 0/5002168 | 
(1 row)