2 psql Basics
psql is the official command-line client for PostgreSQL, and it is excellent. Most professionals reach for it before any GUI — it is fast, scriptable, and ships with every PostgreSQL install. You use it two ways: in batch mode (psql -f file.sql) to run a script, or interactively (psql) to type SQL and meta-commands one at a time. This lesson focuses on the basics; a later lesson covers more meta-commands.
What you’ll learn
- The two modes of
psql: file and interactive - How to identify your session (current user, database, schema)
- The difference between SQL statements and
psqlmeta-commands - Where to get help:
\?for meta-commands,\hfor SQL
Example
pg_database is one of many system catalogs — internal tables PostgreSQL exposes for inspection. The datistemplate = false filter hides template0 and template1, which are the templates new databases are cloned from. current_user, current_database(), and current_schema() are session functions; they answer questions you will ask yourself often when debugging connection or permission issues. SHOW displays runtime parameters — these can be changed at the server, database, role, or session level.
When you use psql interactively, you can also type meta-commands (also called backslash commands) that the client interprets locally:
Meta-commands are interpreted by the psql client, both interactively and in files read with psql -f. Commands such as \dt send catalog queries to the server; the backslash syntax itself is not server SQL.
Run the example
To run this file:
Common pitfalls
- Meta-commands require the psql client.
psql -fexecutes\dtin a file; a driver or GUI that sends the file directly as SQL will not interpret it. - Confusing
current_userandsession_user: when aSET ROLEis in effect,current_userreflects the effective role;session_useris the original login. - Encoding mismatches: if your terminal is not UTF-8 and your database is, you may see garbled text — set
client_encodingto match your terminal.
Add \set PROMPT1 '%n@%/%x%R%# ' to ~/.psqlrc so your prompt shows user, database, and transaction state. Use \e to edit the previous query in your $EDITOR. Use \timing on when you are tuning queries.
Start an interactive session with psql postgres, run \l, then \dt, then \d pg_database, then \q to quit. Compare what \dt shows in different schemas using \dt pg_catalog.*.
Downloads
SQL file: psql-basics.sql · All lesson files · Setup guide