Sub topic 2
Formatting psql output: expanded mode, timing and pager
This chapter assumes you can connect to a PostgreSQL server, write basic SQL, and read table definitions with keys. It covers output formatting, non-interactive runs, catalog queries, object sizes, privileges, psqlrc, and registering a server in pgAdmin.
Formatting psql output
Wide rows wrap badly in a terminal. Expanded mode prints each row as a list of column name and value pairs. \x auto switches to that layout only when a row is too wide to fit.
\x auto
\timing on
\pset null '(null)'
SELECT * FROM orders LIMIT 3;\timing on prints the elapsed time after each statement. \pset null '(null)' shows NULL values as (null), so they stand apart from empty strings. Long output goes through a pager. Run \pset pager off to disable it, or set the PAGER environment variable to pick another program.
Running commands and script files
-c runs one command, and -f runs a file. -X skips the psqlrc file, so a script behaves the same on every machine.
psql -d mydb -c '\dt public.*'
psql -X -d mydb -f inspect.sqlQuerying information_schema and pg_catalog
information_schema is a set of standard views that works across SQL databases. pg_catalog is PostgreSQL's own system catalog and exposes more detail.
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'orders'
ORDER BY ordinal_position;Finding out how big things are
pg_total_relation_size returns the bytes a table uses, including its indexes and TOAST data. pg_size_pretty formats that number for people.
SELECT n.nspname AS schema_name,
c.relname AS table_name,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 10;Inspecting roles and privileges
\du lists roles and their attributes. \dp orders shows the access privileges on a table. To test one permission directly, call has_table_privilege.
SELECT has_table_privilege('app_reader', 'public.orders', 'SELECT');Customizing psql with a psqlrc file
psql reads ~/.psqlrc at startup. Put your preferred settings there:
\set ON_ERROR_ROLLBACK interactive
\x auto
\timing on
\pset null '(null)'Registering a server in pgAdmin
In pgAdmin 4, right-click Servers in the object browser, choose Register, then Server. On the Connection tab, enter the host, port, maintenance database, and username. pgAdmin then shows the server's databases, schemas and objects in the tree. Open the Query Tool from there to run SQL and view EXPLAIN plans.
Exercise
Exercise
The size query sorts by pgtotalrelationsize. Why not pgrelation_size?
Show answer
pgtotalrelationsize includes indexes and TOAST data. pgrelation_size counts only the table's main data, so it understates the disk space a table uses.