Peeping into PostgreSQL

By Sandra Henry-Stocker  Add a new comment

In today's column, we're going to look at some useful scripts for getting information from your PostgreSQL databases. We'll put some SQL queries into use in the form of sql scripts and see how easily we can ask questions about the content of tables, the size of our databases and such.

To begin with, let's create a script that lists all the tables in the database. The PostgreSQL command to list tables is simply "\dt". If we put this command in a file and call it listTables.sql, we can then run the script like this:

% psql -f listTables.sql
                List of relations
 Schema |         Name         | Type  |  Owner
--------+----------------------+-------+----------
 public | alarm_status         | table | postgres
 public | accounts             | table | postgres
 public | filters              | table | postgres
...

You can run this command from the point of view of a particular user by adding "-U username" to the command. For example:

% psql -U privuser -f listTables.sql

If you don't want to go to the trouble of stashing your little "\dt" command in a script (maybe it's not all that hard to remember?), you can offer it as an argument to psql like this:

% psql -c "\dt"
                List of relations
 Schema |         Name         | Type  |  Owner
--------+----------------------+-------+----------
 public | alarm_status         | table | postgres
 public | accounts             | table | postgres
 public | filters              | table | postgres
...

If you're curious about database tables, you might also want to get a description of a particular table using the "\d" (describe) command:

% cat descTable.sql
\d addressbook
% psql -f descTable.sql
             Table "addressbook"
     Column     |         Type          | Modifiers
----------------+-----------------------+-----------
  name          | character varying(32) | not null
  addr          | character varying(48) |

Again, you could also just include your SQL command as an argument to psql:

% psql -c "\d addressbook"
              Table "addressbook"
     Column     |         Type          | Modifiers
----------------+-----------------------+-----------
  name          | character varying(32) | not null
  addr          | character varying(48) |

To determine how many records are in some particular database table, you could create a query that uses COUNT to tally up the records like this:

SELECT COUNT(*) FROM mytable;

You might call the script containing this query "rowcount.sql" and run it like this:

% psql -f rowcount.sql

Of course, it's probably much more useful to be able to ask about the size of any arbitrary table, so it might be more useful to create your sql file on the fly using a simple script like this:

#!/bin/bash

if [ $# == 0 ]; then
    echo -n "table> "
    read T
else
    T=$1
fi

echo "SELECT COUNT(*) FROM $T" > query.sql

psql -f query.sql

The script will create a query.sql file for any table you specify.

% ./getTableSize alarms
 count
-------
    43
(1 row)

If you want to see the size of the entire database, you can put a more complex query together. This one you probably don't want to memorize!

% cat getsize.sql
SELECT datname,pg_size_pretty(pg_database_size(oid)) FROM pg_database ORDER BY pg_database_size(oid) DESC;

When we run this query, we get a listing of the databases and their sizes as shown here:

% psql -f ./getsize.sql
  datname  | pg_size_pretty
-----------+----------------
 A         | 962 MB
 postgres  | 3697 kB
(2 rows)

Any of these commands could also be run by starting psql and issuing them at the prompt as shown below, but then you have to remember the right commands or have them ready to cut and paste into your terminal window. Saving them as scripts makes it easier to ask the questions you might want to ask every now and then.

% psql
Welcome to psql 8.1.4, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit
A=# SELECT datname,pg_size_pretty(pg_database_size(oid)) FROM pg_database ORDER BY 

pg_database_size(oid) DESC;
  datname  | pg_size_pretty
-----------+----------------
 A         | 642 MB
 postgres  | 3697 kB
 template1 | 3697 kB
 template0 | 3697 kB
(4 rows)
A=# \dt
                  List of relations
 Schema  |          Name           | Type  |  Owner
---------+-------------------------+-------+----------
 public  | alarm_status         | table | postgres
 public  | accounts             | table | postgres
 public  | filters              | table | postgres
...

If you run SQL commands all of the time, you might be conversant enough to issue all the commands you need without turning them into scripts. If you're an occassional SQL user, on the other hand, you might find that entrusting the most useful commands to scripts is a good way to go.

ITworld LIVE

IT Management/StrategyWhite Papers & Webcasts

White Paper

The Cloud: Reinventing Enterprise Collaboration

Collaboration and content sharing are not, of course, new concepts. But cloud computing has changed the nature of collaboration, content sharing, document storage and project management to enable more efficient, faster-acting and cost-effective enterprises. According to a new study by IDG Research, the vast majority of knowledge workers (86%) placed a very high level of importance on collaborating with internal coworkers and external stakeholders, and having access to the most up-to-date corporate information. Read how organizations are realizing massive productivity gains by transitioning their content management solutions to cloud-based models.

White Paper

Empowering Your Mobile Worker

Today's most productive employees are mobile, and your company's IT strategy must be ready to support them with 24/7 access to the business information they need across a range of mobile devices.See how corporations are meeting the many needs of their mobile workers with the help of Box.

White Paper

Market Landscape Report: Online File Sharing and Collaboration in the Enterprise

The trend toward "consumerization" marches onward in IT; more and more end-users are choosing their own hardware plaforms and software applications in lieu of the IT-sanctioned business tools provided by their companies. These end-users are looking to tackle issues like data sharing, portability, and access from multiple intelligent endpoint devices, creating a conundrum for IT as it needs to balance business enablement, ease of access, and collaborative capacity with the need to maintain control and security of information assets. This need for balance is one of the drivers of the fast growing online file sharing and collaboration segment of the SaaS market. This paper examines the market drivers, inhibitors, and top vendors in this segment, including Box, Citrix Sharefile, Dropbox, Egnyte, Nomadesk, Sugarsync, Syncplicity and YouSendIt.

White Paper

Sharing Simplified - Consolidating File-sharing Technologies

Employees need to share content with colleagues within their organization and outside. Yet, ECMs make it hard to share content within a business and impossible between organizations. Read how one company consolidated multiple file sharing technologies to increase productivity and reduce complexity.

White Paper

Content Sharing 2.0: The Road Ahead

A growing number of companies are taking advantage of the natural synergies that exist between cloud-based IT services and content access and sharing. Legacy content management and collaboration systems simply weren't designed to meet the evolving requirements of today's IT and business managers, as well as the needs of content users. Box provides cloud-based content storage, access and collaboration services that require virtually no user training and supports file access and delivery on almost all popular PC and mobile devices. Read how Box let companies rapidly implement a cost-effective and secure content storage and sharing system that can easily expand to accommodate any size and number of files.

See more White Papers | Webcasts

Ask a question

Ask a Question