How to Get the Server Uptime in a PostgreSQL Database Server

In this article, we show how to get the server uptime in a postgresql database server.
The server uptime is the period of time since the server was last started.
Knowing the server uptime is very valuable to know things such as to verify that there was no recent server crash if your server is not monitored.
It's also useful just to know when the server was last restarted, such as when configuration settings change for the server.
So how do we find this out about the database server?
And we can do this with the following code below.
If using pgadmin, you can go to the psql tool and type in the following code shown below.
When running this code on a recently started server, I received the following code below.
If you want to apply some formatting to this so that only 2-digit seconds appear,
then we use the following code shown below.
This will produce an uptime with only seconds specified to 2 digits, such as that shown below.
How this code works is, pg_postmaster_start_time();, gets the server start time.
current_timestamp is the current time.
Therefore, we can get the server uptime by subtracting pg_postmaster_start_time(); from current_timestamp
If we add in a little formatting, such as we did above, we can get the server uptime to a second specified in 2 digits.
And this is how we can obtain the server uptime in a postgresql database server.
Related Resources
How to Create Your Own PostgreSQL Server on Your Own Computer in Windows