Skip to content

Commit 9e2167d

Browse files
authored
feat: Added documentation for psql meta-commands (#38)
1 parent 3fdbbb2 commit 9e2167d

1 file changed

Lines changed: 180 additions & 0 deletions

File tree

psql/psql-meta-commands.md

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# psql Meta-Commands — Comprehensive Guide
2+
3+
## What are psql meta-commands?
4+
5+
Meta-commands are special commands in the PostgreSQL `psql` shell that begin with a backslash (`\`). They are **not SQL statements** but provide shortcuts for tasks that would otherwise require complex queries or manual steps.
6+
7+
### Key purposes:
8+
9+
- View and explore database objects (tables, columns, indexes, functions)
10+
- Manage database connections and roles
11+
- Import/export data
12+
- Format query results for readability
13+
- Run external shell commands or SQL files
14+
15+
They exist to **simplify common tasks** and make working with PostgreSQL more efficient.
16+
17+
---
18+
19+
## Why are psql meta-commands needed?
20+
21+
- **Time-saving:** No need to write complex SQL to list tables, columns, or users.
22+
- **Convenience:** Quickly connect to databases, run scripts, or inspect schema.
23+
- **Readability:** Easily format and paginate results for wide or large datasets.
24+
- **Integration:** Run shell commands and scripts without leaving the psql shell.
25+
26+
---
27+
28+
## Running meta-commands
29+
30+
1. Open a terminal (not SQL) and run:
31+
32+
```bash
33+
psql -U <username> -d <database>
34+
```
35+
36+
2. You will see a prompt like:
37+
38+
```
39+
yourdb=#:
40+
```
41+
42+
3. All meta-commands are executed from this `psql` prompt.
43+
44+
> **Important:** Meta-commands do **not work in MySQL or other SQL terminals**.
45+
46+
---
47+
48+
## Complete list of commonly used meta-commands
49+
50+
### Database & connection commands
51+
52+
- `\l` — List all databases
53+
- `\c <dbname>` — Connect to a database
54+
- `\conninfo` — Show connection details
55+
56+
### Schema & object commands
57+
58+
- `\dt` — List tables
59+
- `\dv` — List views
60+
- `\di` — List indexes
61+
- `\df` — List functions
62+
- `\d <table>` — Show table structure
63+
- `\d+ <table>` — Verbose table description (includes storage info)
64+
- `\ds` — List sequences
65+
- `\dn` — List schemas
66+
67+
### Roles & user management
68+
69+
- `\du` — List roles and users
70+
- `\dg` — List role memberships
71+
72+
### Running SQL scripts / shell commands
73+
74+
- `\i /path/to/file.sql` — Execute SQL commands from a file
75+
- `\! <shell-command>` — Execute a shell command from within psql
76+
77+
### Data import / export
78+
79+
- `\copy <table> FROM 'file.csv' CSV HEADER` — Import CSV from client
80+
- `\copy <table> TO 'file.csv' CSV HEADER` — Export table to CSV
81+
82+
### Formatting & output control
83+
84+
- `\x` — Toggle expanded output (columns displayed vertically)
85+
- `\a` — Toggle aligned/unaligned output
86+
- `\H` — Output query as HTML table
87+
- `\pset pager on|off` — Enable or disable pager for long outputs
88+
- `\pset format <format>` — Set output format (`aligned`, `unaligned`, `csv`, `html`, etc.)
89+
- `\t` — Toggle row count footer
90+
- `\o filename` — Send output to a file
91+
92+
### Variables & scripting
93+
94+
- `\set name 'value'` — Set a variable in psql
95+
- Use variables in SQL as `:name` or `:'name'`
96+
- `:\g` — Send the current query buffer to the server
97+
98+
### Help commands
99+
100+
- `\?` — List all psql meta-commands
101+
- `\h` — Show SQL syntax help (`\h SELECT` for SELECT)
102+
103+
---
104+
105+
## Using SQL commands directly in psql
106+
107+
Meta-commands are shortcuts, but anything they do can also be done using standard SQL queries. For example:
108+
109+
| Task | Meta-command | SQL alternative |
110+
| ------------------ | -------------- | ---------------------------------------------------------------------------------------------------------- |
111+
| List tables | `\dt` | `SELECT table_name FROM information_schema.tables WHERE table_schema='public';` |
112+
| Show table columns | `\d employees` | `SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_name='employees';` |
113+
| List roles | `\du` | `SELECT rolname, rolsuper, rolcreaterole, rolcreatedb FROM pg_roles;` |
114+
115+
**Takeaway:** Meta-commands are faster and easier, but SQL gives full control and flexibility. You can mix both depending on your task.
116+
117+
---
118+
119+
## Example session
120+
121+
```
122+
psql -U postgres -d mydb
123+
\l -- list databases
124+
\c mydb -- switch to mydb
125+
\dt -- list tables
126+
\d employees -- table structure
127+
\x -- toggle expanded output
128+
SELECT * FROM employees WHERE id = 1;
129+
\x -- toggle expanded off
130+
\i scripts/setup.sql -- run SQL script
131+
\copy employees FROM 'data/employees.csv' CSV HEADER -- import CSV
132+
\! ls -la -- run shell command
133+
\q -- quit psql
134+
```
135+
136+
---
137+
138+
## Example Questions with Solutions
139+
140+
### Question 1: Show all tables and columns in the `sales` database
141+
142+
**Task:** You want to quickly inspect all tables and their columns in `sales`.
143+
144+
**Solution:**
145+
146+
```sql
147+
\c sales -- connect to sales database
148+
\dt -- list all tables
149+
\d orders -- show structure of orders table
150+
\d customers -- show structure of customers table
151+
```
152+
153+
### Question 2: Check all user roles and their privileges
154+
155+
**Task:** List all roles, see which users have superuser privileges, and check memberships.
156+
157+
**Solution:**
158+
159+
```sql
160+
\du -- list all roles and their attributes
161+
\dg -- show role memberships
162+
```
163+
164+
- Look for `Superuser` column to identify admin users.
165+
- Memberships indicate which roles/users belong to groups.
166+
167+
---
168+
169+
## Notes
170+
171+
- `\copy` vs `COPY`: `\copy` runs on the client machine, `COPY` runs on the server.
172+
- These commands are PostgreSQL-specific; equivalent MySQL commands differ (e.g., `SHOW TABLES;`, `DESCRIBE table;`, `SOURCE file.sql;`).
173+
- Expanded output (`\x`) and formatting commands make reading wide or complex tables easier.
174+
- Both meta-commands and SQL queries can be used in psql. Meta-commands are shortcuts, while SQL provides full control for querying, filtering, and manipulating data.
175+
176+
---
177+
178+
## Summary
179+
180+
psql meta-commands are **essential tools** for efficient database interaction. They simplify inspection, formatting, data import/export, role management, scripting, and executing shell commands, all within the interactive PostgreSQL shell.

0 commit comments

Comments
 (0)