[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6PBVBC89T809AEAFEF27TQR":3,"skill-same:01M6PBVBC89T809AEAFEF27TQR":91},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":13,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":50,"install":51,"resources":64},"01M6PBVBC89T809AEAFEF27TQR","postgresql-cli",null,"PostgreSQL interactive terminal (psql) reference and usage guide.","duc-duy-1612\u002FOnline-Delivery-Systems-Web","duc-duy-1612","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F192231384?v=4","01M6NSDKQQDKVTHZ8DZMZ1VYY6","01M6NSDKW8DDVTQHBT1HBDDJPT",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35],"postgresql","postgresql cli","cli","reference","tree","usage","psql","critical","wed","community","master","agent-skills","guide","interactive","https","license","github","terminal","2026-11-10 10:12:30",false,"---\nname: postgresql-cli\ndescription: \"PostgreSQL interactive terminal (psql) reference and usage guide.\"\nrisk: critical\nsource: https:\u002F\u002Fgithub.com\u002Fchaunsin\u002Fagent-skills\u002Ftree\u002Fmaster\u002Fskills\u002Fpostgresql-cli\nsource_repo: chaunsin\u002Fagent-skills\nsource_type: community\ndate_added: 2026-07-01\nlicense: Apache-2.0\nlicense_source: https:\u002F\u002Fgithub.com\u002Fchaunsin\u002Fagent-skills\u002Fblob\u002Fmaster\u002FLICENSE\n---\n\n# psql — PostgreSQL Interactive Terminal\n\npsql is PostgreSQL's feature-rich interactive terminal. It lets you write and execute queries, inspect database objects, import\u002Fexport data, script batch operations, and customize output formatting — all from the command line.\n\n## Prerequisites\n\nBefore using psql, verify it is installed and available:\n\n```bash\n# Check if psql is installed\npsql --version\n\n# If not found, install PostgreSQL client tools:\n\n# macOS (Homebrew)\nbrew install libpq\nbrew link --force libpq\n\n# Ubuntu \u002F Debian\nsudo apt install postgresql-client\n\n# CentOS \u002F RHEL\nsudo yum install postgresql\n\n# Alpine\napk add postgresql-client\n\n# Windows — install PostgreSQL via the official installer or use WSL\n```\n\npsql ships as part of the `postgresql-client` package. The server (`postgresql`) is not required — you only need the client to connect to a remote PostgreSQL instance.\n\n## Quick Reference\n\n### Connecting\n\n```\n# 1. CLI flags\npsql -h host -p port -U user -d dbname\n\n# 2. Connection URI\n# WARNING: Password in URI is visible in shell history and process listings.\n#          Prefer ~\u002F.pgpass for production use (see method 4 below).\npsql \"postgresql:\u002F\u002Fuser:YOUR_PASSWORD@host:port\u002Fdbname\"\n\n# 3. Environment variables (no flags needed)\nexport PGHOST=localhost\nexport PGPORT=5432\nexport PGDATABASE=mydb\nexport PGUSER=postgres\n# WARNING: PGPASSWORD is visible in process listings (e.g. `ps aux`).\n#          Use ~\u002F.pgpass in production instead.\nexport PGPASSWORD=YOUR_PASSWORD\npsql                       # picks up all params from env\n\n# 4. ~\u002F.pgpass file (RECOMMENDED for passwords)\n#    Format: hostname:port:database:username:password\ntouch ~\u002F.pgpass && chmod 600 ~\u002F.pgpass\n# Then manually edit ~\u002F.pgpass and add entries (avoids password in shell history):\n# hostname:port:database:username:password\n# Example: localhost:5432:mydb:postgres:YOUR_PASSWORD\npsql -h localhost -U postgres -d mydb   # no password prompt\n\n# 5. Execute and exit\npsql -f script.sql dbname                        # execute file then exit\npsql -c \"SELECT 1\" dbname                        # run single command then exit\npsql -1 -f migration.sql dbname                  # run in single transaction\n\n# 6. Service connection (reads from pg_service.conf)\npsql service=mydb_prod\n\n# 7. Reconnect within a session\n\\c dbname                                       # reconnect to different db\n\\c -reuse-previous=on sslmode=require           # change only sslmode\n\\c \"host=newhost port=5432 dbname=mydb\"         # conninfo string\n```\n\nOn connection failure: interactive mode keeps the previous connection; script mode closes it and all subsequent database commands fail until the next successful `\\c`.\n\nKey flags: `-h` host, `-p` port, `-U` user, `-d` database, `-w` no password prompt, `-W` force password prompt, `-1` single transaction, `-f` execute file, `-c` execute command, `-t` tuples only, `-x` expanded, `-A` unaligned, `-E` echo hidden queries (`\\d` internals), `-L` log file, `-X` skip `~\u002F.psqlrc`.\n\n**Connection precedence**: CLI flags > environment variables > `pg_service.conf` > defaults. **Password precedence**: connection string\u002Fpassword flag > `PGPASSWORD` env > `~\u002F.pgpass`. Use `~\u002F.pgpass` instead of `PGPASSWORD` in production — `PGPASSWORD` is visible in process listings (`ps aux`).\n\n### Object Inspection (\\d family)\n\n| Command           | Shows                                                                                                 |\n| ----------------- | ----------------------------------------------------------------------------------------------------- |\n| `\\d`            | All tables, views, materialized views, sequences, foreign tables (equiv.`\\dtvmsE`)                  |\n| `\\dP`           | Partitioned tables                                                                                    |\n| `\\dt`           | Tables only                                                                                           |\n| `\\dv`           | Views only                                                                                            |\n| `\\di`           | Indexes only                                                                                          |\n| `\\ds`           | Sequences only                                                                                        |\n| `\\dm`           | Materialized views only                                                                               |\n| `\\det`          | Foreign tables (mnemonic: \"external tables\")                                                          |\n| `\\dT`           | Data types                                                                                            |\n| `\\df`           | Functions (use modifiers:`a`=aggregate, `n`=normal, `p`=procedure, `t`=trigger, `w`=window) |\n| `\\da`           | Aggregate functions                                                                                   |\n| `\\dn`           | Schemas                                                                                               |\n| `\\du` \u002F `\\dg` | Roles                                                                                                 |\n| `\\db`           | Tablespaces                                                                                           |\n| `\\dc`           | Conversions                                                                                           |\n| `\\dD`           | Domains                                                                                               |\n| `\\dl`           | Large objects (alias for `\\lo_list`)                                                                |\n| `\\dF`           | Text search configurations                                                                            |\n| `\\dFd`          | Text search dictionaries                                                                              |\n| `\\dFp`          | Text search parsers                                                                                   |\n| `\\dFt`          | Text search templates                                                                                 |\n| `\\des`          | Foreign servers                                                                                       |\n| `\\deu`          | User mappings                                                                                         |\n| `\\dew`          | Foreign-data wrappers                                                                                 |\n| `\\dp`           | Privileges (GRANT\u002FREVOKE)                                                                             |\n| `\\drds`         | Per-role and per-database configuration settings                                                      |\n| `\\l`            | List databases (accepts pattern:`\\l test*`)                                                         |\n\n| `\\dA`           | Access methods                                           |\n| `\\dAc` \u002F `\\dAf` \u002F `\\dAo` \u002F `\\dAp` | Operator classes, families, operators, support functions |\n| `\\dC`           | Type casts                                               |\n| `\\dconfig`      | Server configuration parameters (`\\dconfig *` for all, PostgreSQL 16+)  |\n| `\\dd`           | Object descriptions (comments)                           |\n| `\\ddp`          | Default privileges                                       |\n| `\\dL`           | Procedural languages                                     |\n| `\\do`           | Operators (accepts arg type patterns)                    |\n| `\\dO`           | Collations                                               |\n| `\\dP[itn]`      | Partitioned tables (`t`=tables, `i`=indexes, `n`=nested) |\n| `\\drg`          | Granted role memberships                                 |\n| `\\dRp` \u002F `\\dRs` | Replication publications \u002F subscriptions                 |\n| `\\dX`           | Extended statistics                                      |\n| `\\dx`           | Installed extensions                                     |\n| `\\dy`           | Event triggers                                           |\n| `\\sf[+]`        | Show function definition                                 |\n| `\\sv[+]`        | Show view definition                                     |\n| `\\z`            | Privileges (alias for `\\dp`)                             |\n\n**Modifiers** (append to most `\\d` commands):\n\n- `+` — extra info (size, description): `\\dt+`, `\\l+`, `\\du+`\n- `S` — include system objects: `\\dtS`, `\\dfS+`\n- `x` — expanded display mode: `\\dt+x` (note: `\\dx` is a different command; `x` must follow `S` or `+`)\n\nProvide a name for details: `\\d table_name` shows columns, types, indexes, constraints, foreign keys.\n\n**Pattern matching** in \\d commands:\n\n- `*` = any sequence of characters, `?` = single character\n- `.` separates schema from object: `\\dt public.*` or `\\dt my_schema.users`\n- `..` separates database.schema.object: `\\dt mydb.public.*` (db must match current db)\n- Double quotes stop case folding and wildcard expansion: `\\dt \"FOO\"` matches `FOO` not `foo`\n- `$` is matched literally (not regex anchor)\n- Regex chars like `[0-9]` work: `\\dt user[0-9]*` matches `user1`, `user2`\n- No pattern: shows all objects visible in current `search_path` (not all objects in DB)\n- Use `*.*` to see all objects in all schemas regardless of visibility\n\n### Query Execution\n\n| Command                               | Action                                                                                 |\n| ------------------------------------- | -------------------------------------------------------------------------------------- |\n| `;`                                 | Execute the current query buffer                                                       |\n| `\\g`                                | Execute (like `;`, but can add options)                                              |\n| `\\gx`                               | Execute with expanded output (like `\\g`, forces `\\x on`)                           |\n| `\\g filename`                       | Execute and send output to file                                                        |\n| `\\g \\| command`                      | Execute and pipe output to shell command                                               |\n| `\\g (format=csv footer=off) file`   | Execute with one-shot formatting options                                               |\n| `\\gdesc`                            | Describe result columns without executing                                              |\n| `\\gset [prefix]`                    | Execute and store results in psql variables                                            |\n| `\\gexec`                            | Execute each cell of result as a SQL command                                           |\n| `\\crosstabview`                     | Display result as crosstab (pivot table)                                               |\n| `\\watch`                            | Re-execute query periodically (see below)                                              |\n| `\\bind [params...]`                 | Use extended query protocol with parameters. Works with `\\g`, `\\gx`, and `\\gset` |\n| `\\bind_named stmt_name [params...]` | Bind named prepared statement                                                          |\n| `\\parse stmt_name`                  | Create prepared statement from current query buffer                                    |\n| `\\close_prepared stmt_name`         | Close a prepared statement                                                             |\n| `\\;`                                | Append semicolon to buffer without executing                                           |\n\n### Data Import\u002FExport\n\n```sql\n-- Server-side (requires superuser for file access, uses server filesystem)\nCOPY table TO '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true);\nCOPY table FROM '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true);\n\n-- Client-side (runs with client permissions, no superuser needed) — preferred\n\\copy table TO '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true)\n\\copy table FROM '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true)\n\\copy (SELECT ...) TO '\u002Fpath\u002Foutput.csv' WITH (FORMAT csv, HEADER true)\n\n-- Advanced: specific columns, NULL handling, custom delimiter\n\\copy table (col1, col2) FROM 'data.csv' WITH (FORMAT csv, HEADER true, NULL 'N\u002FA')\n```\n\n`\\copy` is the go-to for day-to-day work — it uses the client's filesystem and permissions, not the server's.\n\n**\\copy syntax detail:**\n\n```\n-- FROM (import): sources are 'filename', program 'command', stdin, pstdin\n\\copy table FROM 'file.csv' WITH (FORMAT csv, HEADER true) [ WHERE condition ]\n\n-- TO (export): destinations are 'filename', program 'command', stdout, pstdout\n\\copy table TO 'file.csv' WITH (FORMAT csv, HEADER true)\n```\n\nFor `\\copy ... FROM stdin`, data rows continue until a line containing only `\\.` is read or EOF is reached. Use `pstdin`\u002F`pstdout` to always read\u002Fwrite psql's actual stdin\u002Fstdout regardless of `\\o` setting.\n\nWARNING: The `program` option executes a shell command. If constructed from user input, it can lead to command injection. Avoid string concatenation with untrusted data.\n\n**Tip**: `\\copy` takes the entire rest of the line as arguments (no variable interpolation). When you need variable interpolation or multi-line queries, use SQL `COPY ... TO STDOUT` with `\\g` instead:\n\n```sql\n-- This allows variable interpolation and multi-line queries\nCOPY (SELECT * FROM :table WHERE id > :min_id) TO STDOUT WITH (FORMAT csv, HEADER true) \\g \u002Ftmp\u002Foutput.csv\n```\n\n### Output Formatting\n\n```\n\\a                  Toggle aligned\u002Funaligned output\n\\x                  Toggle expanded display (vertical vs table)\n\\t                  Toggle tuples only (no headers\u002Ffooters)\n\\pset format FORMAT  Set output format: aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped\n\\pset border N       Set border style (0-2; 3 for latex data-row lines)\n\\pset null STRING    Display NULL as STRING\n\\pset pager [off]    Control pager usage\n\\pset title 'TEXT'   Set table title\n\\pset recordsep SEP  Set record separator for unaligned mode\n\\pset fieldsep SEP   Set field separator for unaligned mode (default: |)\n\\pset footer [on|off] Toggle row count footer\n\\pset columns N      Set target width for wrapped format\n\\pset csv_fieldsep C  Set CSV field separator (default: comma)\n\\pset numericlocale [on|off]  Toggle locale-specific number formatting\n\\pset linestyle STYLE Set border style: ascii, old-ascii, unicode\n\\pset pager_min_lines N  Minimum lines before pager activates\n\\pset xheader_width MODE  Expanded header width: full, column, page, or N (PostgreSQL 17+)\n\\H                   Toggle HTML output (shortcut)\n\\C [title]           Set table title (shortcut for \\pset title)\n\\f [string]          Set field separator (shortcut for \\pset fieldsep)\n\\T table_options     Set HTML table attributes (shortcut for \\pset tableattr)\n```\n\n### Large Objects\n\n```\n\\lo_import filename [comment]   Import file as large object, returns OID\n\\lo_export loid filename        Export large object to file\n\\lo_list[x+]                    List all large objects\n\\lo_unlink loid                 Delete large object\n```\n\nLarge object OIDs are persistent references. Always associate a human-readable comment on import. Use `\\lo_list` to find OIDs.\n\n### Scripting & Control Flow\n\n```\n\\i filename         Execute file (relative to current working directory)\n\\ir filename        Execute file (relative to the script being processed)\n\\o [filename]       Redirect query output to file (or pipe with |cmd)\n\\o                   Stop output redirection\n\\qecho TEXT          Output text to redirected output\n\\echo TEXT           Output text to stdout (-n suppresses trailing newline)\n\\warn TEXT           Output text to stderr\n\\! command           Execute shell command\n\\cd [dir]            Change working directory\n\\set NAME VALUE      Set psql variable\n\\unset NAME          Unset psql variable\n\\prompt [TEXT] NAME  Prompt user for variable value\n\\getenv psql_var env_var   Copy environment variable into psql variable\n\\setenv name [value]       Set or unset environment variable\n\\p                  Print current query buffer\n\\w filename         Write query buffer to file (or pipe with |cmd)\n\n-- Conditional execution (useful in scripts)\n\\if EXPR\n  \\echo 'true branch'\n\\else\n  \\echo 'false branch'\n\\endif\n\n\\elif EXPR           Else-if inside \\if block\n```\n\n`\\if` and `\\elif` evaluate their argument as a boolean. Valid values (case-insensitive, unambiguous prefix matching): `true`, `false`, `1`, `0`, `on`, `off`, `yes`, `no`. Expressions that don't evaluate to true\u002Ffalse generate a warning and are treated as false. Variable references in skipped lines are NOT expanded.\n\nVariables in SQL: `:'varname'` (quoted string value, escapes embedded quotes), `:\"varname\"` (double-quoted identifier), `:'varname'::type` (with cast), `:varname` (unquoted — can break SQL), `:{?varname}` (tests existence, expands to TRUE\u002FFALSE).\n\n### Session Management\n\n```\n\\c [dbname [user]]  Connect to database (or reconnect)\n\\conninfo           Display connection info (includes SSL info)\n\\encoding [ENC]     Set or show client encoding\n\\password [USER]    Change password (does NOT appear in command history or server log)\n\\q                   Quit psql. In a script file, only that script is terminated. In interactive mode, the entire program exits.\n\\r                   Reset (clear) the query buffer\n\\e                   Edit query buffer in external editor\n\\ef [FUNCNAME]       Edit function definition\n\\ev [VIEWNAME]       Edit view definition\n\\sf[+] FUNCNAME      Show function definition (read-only)\n\\sv[+] VIEWNAME      Show view definition (read-only)\n\\s [FILE]            Print command history (or save to file)\n\\restrict KEY        Enter restricted mode (only \\unrestrict allowed)\n\\unrestrict KEY      Exit restricted mode\n\\timing [on\\|off]    Toggle query execution time display (milliseconds)\n\\errverbose          Repeat last error at maximum verbosity\n\\? [topic]           Help: commands, options, or variables\n\\h [command]         SQL syntax help (use * for all: \\h *)\n\\copyright           Show PostgreSQL copyright\n```\n\n### Pipeline Mode (PostgreSQL 14+)\n\n```\n\\startpipeline\n  SELECT $1 \\bind 42 \\sendpipeline\n  SELECT $1 \\bind 100 \\sendpipeline\n  \\getresults\n\\endpipeline\n```\n\nPipeline mode sends multiple queries without waiting for each result, reducing round-trip latency. All queries use the extended query protocol.\n\n**Pipeline commands:**\n\n- `\\startpipeline` — begin pipeline block\n- `\\endpipeline` — end pipeline block and process remaining results\n- `\\sendpipeline` — append current query buffer to pipeline without waiting\n- `\\syncpipeline` — send sync message without ending pipeline\n- `\\flushrequest` — request server flush without sync\n- `\\flush` — manually push unsent data to server\n- `\\getresults [N]` — read pending results (N=0 or omitted means all)\n\n**Pipeline limitations:**\n\n- `COPY` is not supported in pipeline mode\n- Meta-commands like `\\g`, `\\gx`, `\\gdesc` are not allowed inside a pipeline\n- All queries use the extended query protocol\n- Use `\\bind`, `\\bind_named`, `\\parse`, `\\close_prepared`, or `\\sendpipeline` within pipelines\n- A `%P` prompt variable shows pipeline status (`on`, `off`, or `abort`)\n\n### \\watch Syntax\n\n```\n\\watch [i[nterval]=SECONDS] [c[ount]=TIMES] [m[in_rows]=ROWS] [SECONDS]\n```\n\n`count` and `min_rows` require PostgreSQL 17+.\n\n- `interval` — seconds between executions (default: 2, overridable via `WATCH_INTERVAL` variable)\n- `count` — stop after N executions\n- `min_rows` — stop if query returns fewer than N rows\n\nIf the query buffer is empty, `\\watch` re-executes the most recently sent query.\n\nExamples:\n\n```sql\nSELECT * FROM pg_stat_activity WHERE state = 'active';\n\\watch interval=5 count=10      -- every 5s, stop after 10 runs\n\nSELECT count(*) FROM queue WHERE status = 'pending';\n\\watch i=1 min_rows=1            -- every 1s, stop when queue is empty\n```\n\n### Exit Codes\n\n| Code | Meaning                                                         |\n| ---- | --------------------------------------------------------------- |\n| 0    | Successful completion                                           |\n| 1    | A fatal error occurred (server error, connection failure, etc.) |\n| 2    | Connection failed (could not connect to the server)             |\n| 3    | Script execution ended due to ON_ERROR_STOP                     |\n\n## Security Considerations\n\n### Destructive Operations Checklist\n\nBefore running any destructive SQL, verify impact first:\n\n```sql\n-- BEFORE DELETE: check how many rows are affected\nSELECT count(*) FROM users WHERE condition;  -- verify scope\nBEGIN;\nDELETE FROM users WHERE condition RETURNING *;  -- see what was deleted\n-- ROLLBACK if wrong; COMMIT only after verification\n\n-- BEFORE DROP TABLE: verify no foreign keys depend on it\n\\d table_name  -- check \"Referenced by\" section\n-- Consider renaming first: ALTER TABLE old RENAME TO old_backup;\n```\n\n### Dangerous Commands Requiring Extra Caution\n\n| Command\u002FPattern                         | Risk                                                      | Mitigation                                                                                           |\n| --------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |\n| `\\gexec`                              | Executes generated SQL without confirmation               | Always inspect the generating query first by running it without `\\gexec`; set `ON_ERROR_STOP on` |\n| `\\! command`                          | Arbitrary shell execution                                 | No sandboxing; commands run with psql user's full privileges                                         |\n| `\\copy ... program 'cmd'`             | Shell command injection if filename comes from user input | Never concatenate untrusted input into the `program` string                                        |\n| `\\deu+`                               | May display remote user passwords                         | Avoid using `\\deu+` in shared\u002Fpiped output; use `\\deu` without `+`                             |\n| `DELETE`\u002F`UPDATE` without `WHERE` | Affects every row in the table                            | Always use `WHERE`; wrap in `BEGIN`\u002F`ROLLBACK` to preview                                      |\n| `DROP DATABASE\u002FTABLE`                 | Irreversible data loss                                    | Verify you're on the correct database with `\\conninfo` first                                       |\n\n### Variable Interpolation Safety\n\npsql variables are **plain text substitution**, not parameterized queries. This means:\n\n```sql\n-- UNSAFE: if :name contains \"Robert'); DROP TABLE users;--\" it will execute the injection\nSELECT * FROM users WHERE name = :'name';\n\n-- SAFER: use \\prompt for interactive input (user sees what they typed)\n\\prompt 'Enter name: ' search_name\nSELECT * FROM users WHERE name = :'search_name';\n\n-- SAFEST: use \\bind for programmatic parameter passing (truly parameterized)\nSELECT * FROM users WHERE name = $1;\n\\bind 'Robert' \\g\n```\n\nThe `:'varname'` form (quoted) is always safer than `:varname` (unquoted), because unquoted substitution can break SQL syntax or enable injection. Use `:\"varname\"` for identifiers (table\u002Fcolumn names) — it properly escapes embedded double quotes.\n\n## When to Use What\n\n| Scenario                      | Recommended Command                                            |\n| ----------------------------- | -------------------------------------------------------------- |\n| Quick table inspection        | `\\d table_name`                                              |\n| List all tables in schema     | `\\dt schema.*`                                               |\n| Check indexes on a table      | `\\di+ table_name*` or `\\d table_name`                      |\n| Export query to CSV           | `\\copy (SELECT ...) TO 'file.csv' WITH (FORMAT csv, HEADER)` |\n| Import CSV into table         | `\\copy table FROM 'file.csv' WITH (FORMAT csv, HEADER)`      |\n| Run migration script          | `psql -1 -f migration.sql dbname`                            |\n| Watch a live query            | `SELECT ... \\watch 5`                                        |\n| Pivot query results           | `SELECT ... \\crosstabview`                                   |\n| Script with conditional logic | `\\if :var ... \\endif`                                        |\n| Batch-insert many rows        | Use `\\startpipeline` \u002F `\\endpipeline`                      |\n| SQL syntax help               | `\\h CREATE TABLE`                                            |\n| psql command help             | `\\? commands`                                                |\n| Check query execution time    | `\\timing on` then run query                                  |\n| Debug error details           | `\\errverbose`                                                |\n| Handle large result sets      | `\\set FETCH_COUNT 1000` then run query                       |\n| Auto-savepoint on errors      | `\\set ON_ERROR_ROLLBACK on` then use transactions            |\n\n- **`references\u002Fmeta-commands-core.md`** — Core meta-commands: query buffer behavior, argument parsing rules, connection management, query execution, `\\copy` syntax, and scripting commands (`\\if`, `\\i`, `\\o`, backquote expansion). Read this when you need exact syntax or behavioral details for any backslash command.\n- **`references\u002Fmeta-commands-inspection.md`** — Full `\\d` command reference: all object inspection commands, modifiers (`S`, `+`, `x`), and pattern matching rules. Read this when exploring database schema or when the user needs to inspect tables, indexes, views, functions, privileges, etc.\n- **`references\u002Fmeta-commands-formatting.md`** — Output formatting (`\\pset` options and all format descriptions), pipeline mode, `\\watch`, `\\crosstabview`, and session management (`\\e`, `\\ef`, `\\ev`, `\\timing`, etc.). Read this when the user needs to control output format or use pipeline mode.\n- **`references\u002Fcli-options-and-variables.md`** — All CLI flags, environment variables, psql internal variables (AUTOCOMMIT, ON_ERROR_STOP, ECHO, FETCH_COUNT, etc.), prompt customization, `~\u002F.psqlrc` configuration, and SQL interpolation syntax. Read this when configuring psql startup behavior, writing scripts that depend on variable state, or customizing prompts.\n- **`references\u002Ftips-workflows.md`** — Practical workflows (exploring a new database, understanding table structure), scripting patterns (safe scripts, conditional execution, `\\gexec`), output control for automation, and data import\u002Fexport patterns. Read this when the user asks how to accomplish a specific task with psql.\n- **`references\u002Ftips-advanced.md`** — Performance tips, debugging\u002Fintrospection (`EXPLAIN`, lock analysis, `ECHO_HIDDEN`), safety best practices (ON_ERROR_STOP, transaction patterns, search_path safety), and common gotchas. Read this for lock analysis, query plan inspection, and troubleshooting.\n\n## Important Notes\n\npsql handles two comment styles differently:\n\n- **C-style block comments** (`\u002F* ... *\u002F`): Passed to the server for processing and removal.\n- **SQL-standard comments** (`--`): Removed by psql itself, before sending to the server.\n\nThis distinction matters when writing scripts that rely on comment behavior — only SQL-standard comments are stripped client-side.\n\n### Variable Variables (Soft References)\n\npsql allows indirect variable references through `\\set`:\n\n```sql\n\\set foo 'my_table'\n\\set bar :foo         -- copies the value of foo into bar\n\\echo :bar            -- outputs: my_table\n```\n\nWhile constructs like `\\set :foo 'something'` are syntactically valid, they produce \"soft links\" that have limited practical use. For straightforward variable copying, use `\\set new_var :old_var`.\n\n### Version Compatibility\n\npsql works best with servers of the same or an older major version. Backslash commands (especially `\\d` family) may fail with newer server versions. When connecting to multiple server versions, use the newest available psql client. The `\\d` commands generally work with servers back to version 9.2.\n\n## External References\n\n- [PostgreSQL Client Applications](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fapp-psql.html)\n- [Official PostgreSQL Documentation](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Findex.html)\n- [The SQL Language](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql.html)\n- [SQL Syntax - The SQL Language](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-syntax.html)\n- [SQL Command](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-commands.html)\n- [PostgreSQL Wiki](https:\u002F\u002Fwiki.postgresql.org\u002F)\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n","# psql — PostgreSQL Interactive Terminal\n\npsql is PostgreSQL's feature-rich interactive terminal. It lets you write and execute queries, inspect database objects, import\u002Fexport data, script batch operations, and customize output formatting — all from the command line.\n\n## Prerequisites\n\nBefore using psql, verify it is installed and available:\n\n```bash\n# Check if psql is installed\npsql --version\n\n# If not found, install PostgreSQL client tools:\n\n# macOS (Homebrew)\nbrew install libpq\nbrew link --force libpq\n\n# Ubuntu \u002F Debian\nsudo apt install postgresql-client\n\n# CentOS \u002F RHEL\nsudo yum install postgresql\n\n# Alpine\napk add postgresql-client\n\n# Windows — install PostgreSQL via the official installer or use WSL\n```\n\npsql ships as part of the `postgresql-client` package. The server (`postgresql`) is not required — you only need the client to connect to a remote PostgreSQL instance.\n\n## Quick Reference\n\n### Connecting\n\n```\n# 1. CLI flags\npsql -h host -p port -U user -d dbname\n\n# 2. Connection URI\n# WARNING: Password in URI is visible in shell history and process listings.\n#          Prefer ~\u002F.pgpass for production use (see method 4 below).\npsql \"postgresql:\u002F\u002Fuser:YOUR_PASSWORD@host:port\u002Fdbname\"\n\n# 3. Environment variables (no flags needed)\nexport PGHOST=localhost\nexport PGPORT=5432\nexport PGDATABASE=mydb\nexport PGUSER=postgres\n# WARNING: PGPASSWORD is visible in process listings (e.g. `ps aux`).\n#          Use ~\u002F.pgpass in production instead.\nexport PGPASSWORD=YOUR_PASSWORD\npsql                       # picks up all params from env\n\n# 4. ~\u002F.pgpass file (RECOMMENDED for passwords)\n#    Format: hostname:port:database:username:password\ntouch ~\u002F.pgpass && chmod 600 ~\u002F.pgpass\n# Then manually edit ~\u002F.pgpass and add entries (avoids password in shell history):\n# hostname:port:database:username:password\n# Example: localhost:5432:mydb:postgres:YOUR_PASSWORD\npsql -h localhost -U postgres -d mydb   # no password prompt\n\n# 5. Execute and exit\npsql -f script.sql dbname                        # execute file then exit\npsql -c \"SELECT 1\" dbname                        # run single command then exit\npsql -1 -f migration.sql dbname                  # run in single transaction\n\n# 6. Service connection (reads from pg_service.conf)\npsql service=mydb_prod\n\n# 7. Reconnect within a session\n\\c dbname                                       # reconnect to different db\n\\c -reuse-previous=on sslmode=require           # change only sslmode\n\\c \"host=newhost port=5432 dbname=mydb\"         # conninfo string\n```\n\nOn connection failure: interactive mode keeps the previous connection; script mode closes it and all subsequent database commands fail until the next successful `\\c`.\n\nKey flags: `-h` host, `-p` port, `-U` user, `-d` database, `-w` no password prompt, `-W` force password prompt, `-1` single transaction, `-f` execute file, `-c` execute command, `-t` tuples only, `-x` expanded, `-A` unaligned, `-E` echo hidden queries (`\\d` internals), `-L` log file, `-X` skip `~\u002F.psqlrc`.\n\n**Connection precedence**: CLI flags > environment variables > `pg_service.conf` > defaults. **Password precedence**: connection string\u002Fpassword flag > `PGPASSWORD` env > `~\u002F.pgpass`. Use `~\u002F.pgpass` instead of `PGPASSWORD` in production — `PGPASSWORD` is visible in process listings (`ps aux`).\n\n### Object Inspection (\\d family)\n\n| Command           | Shows                                                                                                 |\n| ----------------- | ----------------------------------------------------------------------------------------------------- |\n| `\\d`            | All tables, views, materialized views, sequences, foreign tables (equiv.`\\dtvmsE`)                  |\n| `\\dP`           | Partitioned tables                                                                                    |\n| `\\dt`           | Tables only                                                                                           |\n| `\\dv`           | Views only                                                                                            |\n| `\\di`           | Indexes only                                                                                          |\n| `\\ds`           | Sequences only                                                                                        |\n| `\\dm`           | Materialized views only                                                                               |\n| `\\det`          | Foreign tables (mnemonic: \"external tables\")                                                          |\n| `\\dT`           | Data types                                                                                            |\n| `\\df`           | Functions (use modifiers:`a`=aggregate, `n`=normal, `p`=procedure, `t`=trigger, `w`=window) |\n| `\\da`           | Aggregate functions                                                                                   |\n| `\\dn`           | Schemas                                                                                               |\n| `\\du` \u002F `\\dg` | Roles                                                                                                 |\n| `\\db`           | Tablespaces                                                                                           |\n| `\\dc`           | Conversions                                                                                           |\n| `\\dD`           | Domains                                                                                               |\n| `\\dl`           | Large objects (alias for `\\lo_list`)                                                                |\n| `\\dF`           | Text search configurations                                                                            |\n| `\\dFd`          | Text search dictionaries                                                                              |\n| `\\dFp`          | Text search parsers                                                                                   |\n| `\\dFt`          | Text search templates                                                                                 |\n| `\\des`          | Foreign servers                                                                                       |\n| `\\deu`          | User mappings                                                                                         |\n| `\\dew`          | Foreign-data wrappers                                                                                 |\n| `\\dp`           | Privileges (GRANT\u002FREVOKE)                                                                             |\n| `\\drds`         | Per-role and per-database configuration settings                                                      |\n| `\\l`            | List databases (accepts pattern:`\\l test*`)                                                         |\n\n| `\\dA`           | Access methods                                           |\n| `\\dAc` \u002F `\\dAf` \u002F `\\dAo` \u002F `\\dAp` | Operator classes, families, operators, support functions |\n| `\\dC`           | Type casts                                               |\n| `\\dconfig`      | Server configuration parameters (`\\dconfig *` for all, PostgreSQL 16+)  |\n| `\\dd`           | Object descriptions (comments)                           |\n| `\\ddp`          | Default privileges                                       |\n| `\\dL`           | Procedural languages                                     |\n| `\\do`           | Operators (accepts arg type patterns)                    |\n| `\\dO`           | Collations                                               |\n| `\\dP[itn]`      | Partitioned tables (`t`=tables, `i`=indexes, `n`=nested) |\n| `\\drg`          | Granted role memberships                                 |\n| `\\dRp` \u002F `\\dRs` | Replication publications \u002F subscriptions                 |\n| `\\dX`           | Extended statistics                                      |\n| `\\dx`           | Installed extensions                                     |\n| `\\dy`           | Event triggers                                           |\n| `\\sf[+]`        | Show function definition                                 |\n| `\\sv[+]`        | Show view definition                                     |\n| `\\z`            | Privileges (alias for `\\dp`)                             |\n\n**Modifiers** (append to most `\\d` commands):\n\n- `+` — extra info (size, description): `\\dt+`, `\\l+`, `\\du+`\n- `S` — include system objects: `\\dtS`, `\\dfS+`\n- `x` — expanded display mode: `\\dt+x` (note: `\\dx` is a different command; `x` must follow `S` or `+`)\n\nProvide a name for details: `\\d table_name` shows columns, types, indexes, constraints, foreign keys.\n\n**Pattern matching** in \\d commands:\n\n- `*` = any sequence of characters, `?` = single character\n- `.` separates schema from object: `\\dt public.*` or `\\dt my_schema.users`\n- `..` separates database.schema.object: `\\dt mydb.public.*` (db must match current db)\n- Double quotes stop case folding and wildcard expansion: `\\dt \"FOO\"` matches `FOO` not `foo`\n- `$` is matched literally (not regex anchor)\n- Regex chars like `[0-9]` work: `\\dt user[0-9]*` matches `user1`, `user2`\n- No pattern: shows all objects visible in current `search_path` (not all objects in DB)\n- Use `*.*` to see all objects in all schemas regardless of visibility\n\n### Query Execution\n\n| Command                               | Action                                                                                 |\n| ------------------------------------- | -------------------------------------------------------------------------------------- |\n| `;`                                 | Execute the current query buffer                                                       |\n| `\\g`                                | Execute (like `;`, but can add options)                                              |\n| `\\gx`                               | Execute with expanded output (like `\\g`, forces `\\x on`)                           |\n| `\\g filename`                       | Execute and send output to file                                                        |\n| `\\g \\| command`                      | Execute and pipe output to shell command                                               |\n| `\\g (format=csv footer=off) file`   | Execute with one-shot formatting options                                               |\n| `\\gdesc`                            | Describe result columns without executing                                              |\n| `\\gset [prefix]`                    | Execute and store results in psql variables                                            |\n| `\\gexec`                            | Execute each cell of result as a SQL command                                           |\n| `\\crosstabview`                     | Display result as crosstab (pivot table)                                               |\n| `\\watch`                            | Re-execute query periodically (see below)                                              |\n| `\\bind [params...]`                 | Use extended query protocol with parameters. Works with `\\g`, `\\gx`, and `\\gset` |\n| `\\bind_named stmt_name [params...]` | Bind named prepared statement                                                          |\n| `\\parse stmt_name`                  | Create prepared statement from current query buffer                                    |\n| `\\close_prepared stmt_name`         | Close a prepared statement                                                             |\n| `\\;`                                | Append semicolon to buffer without executing                                           |\n\n### Data Import\u002FExport\n\n```sql\n-- Server-side (requires superuser for file access, uses server filesystem)\nCOPY table TO '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true);\nCOPY table FROM '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true);\n\n-- Client-side (runs with client permissions, no superuser needed) — preferred\n\\copy table TO '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true)\n\\copy table FROM '\u002Fpath\u002Ffile.csv' WITH (FORMAT csv, HEADER true)\n\\copy (SELECT ...) TO '\u002Fpath\u002Foutput.csv' WITH (FORMAT csv, HEADER true)\n\n-- Advanced: specific columns, NULL handling, custom delimiter\n\\copy table (col1, col2) FROM 'data.csv' WITH (FORMAT csv, HEADER true, NULL 'N\u002FA')\n```\n\n`\\copy` is the go-to for day-to-day work — it uses the client's filesystem and permissions, not the server's.\n\n**\\copy syntax detail:**\n\n```\n-- FROM (import): sources are 'filename', program 'command', stdin, pstdin\n\\copy table FROM 'file.csv' WITH (FORMAT csv, HEADER true) [ WHERE condition ]\n\n-- TO (export): destinations are 'filename', program 'command', stdout, pstdout\n\\copy table TO 'file.csv' WITH (FORMAT csv, HEADER true)\n```\n\nFor `\\copy ... FROM stdin`, data rows continue until a line containing only `\\.` is read or EOF is reached. Use `pstdin`\u002F`pstdout` to always read\u002Fwrite psql's actual stdin\u002Fstdout regardless of `\\o` setting.\n\nWARNING: The `program` option executes a shell command. If constructed from user input, it can lead to command injection. Avoid string concatenation with untrusted data.\n\n**Tip**: `\\copy` takes the entire rest of the line as arguments (no variable interpolation). When you need variable interpolation or multi-line queries, use SQL `COPY ... TO STDOUT` with `\\g` instead:\n\n```sql\n-- This allows variable interpolation and multi-line queries\nCOPY (SELECT * FROM :table WHERE id > :min_id) TO STDOUT WITH (FORMAT csv, HEADER true) \\g \u002Ftmp\u002Foutput.csv\n```\n\n### Output Formatting\n\n```\n\\a                  Toggle aligned\u002Funaligned output\n\\x                  Toggle expanded display (vertical vs table)\n\\t                  Toggle tuples only (no headers\u002Ffooters)\n\\pset format FORMAT  Set output format: aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped\n\\pset border N       Set border style (0-2; 3 for latex data-row lines)\n\\pset null STRING    Display NULL as STRING\n\\pset pager [off]    Control pager usage\n\\pset title 'TEXT'   Set table title\n\\pset recordsep SEP  Set record separator for unaligned mode\n\\pset fieldsep SEP   Set field separator for unaligned mode (default: |)\n\\pset footer [on|off] Toggle row count footer\n\\pset columns N      Set target width for wrapped format\n\\pset csv_fieldsep C  Set CSV field separator (default: comma)\n\\pset numericlocale [on|off]  Toggle locale-specific number formatting\n\\pset linestyle STYLE Set border style: ascii, old-ascii, unicode\n\\pset pager_min_lines N  Minimum lines before pager activates\n\\pset xheader_width MODE  Expanded header width: full, column, page, or N (PostgreSQL 17+)\n\\H                   Toggle HTML output (shortcut)\n\\C [title]           Set table title (shortcut for \\pset title)\n\\f [string]          Set field separator (shortcut for \\pset fieldsep)\n\\T table_options     Set HTML table attributes (shortcut for \\pset tableattr)\n```\n\n### Large Objects\n\n```\n\\lo_import filename [comment]   Import file as large object, returns OID\n\\lo_export loid filename        Export large object to file\n\\lo_list[x+]                    List all large objects\n\\lo_unlink loid                 Delete large object\n```\n\nLarge object OIDs are persistent references. Always associate a human-readable comment on import. Use `\\lo_list` to find OIDs.\n\n### Scripting & Control Flow\n\n```\n\\i filename         Execute file (relative to current working directory)\n\\ir filename        Execute file (relative to the script being processed)\n\\o [filename]       Redirect query output to file (or pipe with |cmd)\n\\o                   Stop output redirection\n\\qecho TEXT          Output text to redirected output\n\\echo TEXT           Output text to stdout (-n suppresses trailing newline)\n\\warn TEXT           Output text to stderr\n\\! command           Execute shell command\n\\cd [dir]            Change working directory\n\\set NAME VALUE      Set psql variable\n\\unset NAME          Unset psql variable\n\\prompt [TEXT] NAME  Prompt user for variable value\n\\getenv psql_var env_var   Copy environment variable into psql variable\n\\setenv name [value]       Set or unset environment variable\n\\p                  Print current query buffer\n\\w filename         Write query buffer to file (or pipe with |cmd)\n\n-- Conditional execution (useful in scripts)\n\\if EXPR\n  \\echo 'true branch'\n\\else\n  \\echo 'false branch'\n\\endif\n\n\\elif EXPR           Else-if inside \\if block\n```\n\n`\\if` and `\\elif` evaluate their argument as a boolean. Valid values (case-insensitive, unambiguous prefix matching): `true`, `false`, `1`, `0`, `on`, `off`, `yes`, `no`. Expressions that don't evaluate to true\u002Ffalse generate a warning and are treated as false. Variable references in skipped lines are NOT expanded.\n\nVariables in SQL: `:'varname'` (quoted string value, escapes embedded quotes), `:\"varname\"` (double-quoted identifier), `:'varname'::type` (with cast), `:varname` (unquoted — can break SQL), `:{?varname}` (tests existence, expands to TRUE\u002FFALSE).\n\n### Session Management\n\n```\n\\c [dbname [user]]  Connect to database (or reconnect)\n\\conninfo           Display connection info (includes SSL info)\n\\encoding [ENC]     Set or show client encoding\n\\password [USER]    Change password (does NOT appear in command history or server log)\n\\q                   Quit psql. In a script file, only that script is terminated. In interactive mode, the entire program exits.\n\\r                   Reset (clear) the query buffer\n\\e                   Edit query buffer in external editor\n\\ef [FUNCNAME]       Edit function definition\n\\ev [VIEWNAME]       Edit view definition\n\\sf[+] FUNCNAME      Show function definition (read-only)\n\\sv[+] VIEWNAME      Show view definition (read-only)\n\\s [FILE]            Print command history (or save to file)\n\\restrict KEY        Enter restricted mode (only \\unrestrict allowed)\n\\unrestrict KEY      Exit restricted mode\n\\timing [on\\|off]    Toggle query execution time display (milliseconds)\n\\errverbose          Repeat last error at maximum verbosity\n\\? [topic]           Help: commands, options, or variables\n\\h [command]         SQL syntax help (use * for all: \\h *)\n\\copyright           Show PostgreSQL copyright\n```\n\n### Pipeline Mode (PostgreSQL 14+)\n\n```\n\\startpipeline\n  SELECT $1 \\bind 42 \\sendpipeline\n  SELECT $1 \\bind 100 \\sendpipeline\n  \\getresults\n\\endpipeline\n```\n\nPipeline mode sends multiple queries without waiting for each result, reducing round-trip latency. All queries use the extended query protocol.\n\n**Pipeline commands:**\n\n- `\\startpipeline` — begin pipeline block\n- `\\endpipeline` — end pipeline block and process remaining results\n- `\\sendpipeline` — append current query buffer to pipeline without waiting\n- `\\syncpipeline` — send sync message without ending pipeline\n- `\\flushrequest` — request server flush without sync\n- `\\flush` — manually push unsent data to server\n- `\\getresults [N]` — read pending results (N=0 or omitted means all)\n\n**Pipeline limitations:**\n\n- `COPY` is not supported in pipeline mode\n- Meta-commands like `\\g`, `\\gx`, `\\gdesc` are not allowed inside a pipeline\n- All queries use the extended query protocol\n- Use `\\bind`, `\\bind_named`, `\\parse`, `\\close_prepared`, or `\\sendpipeline` within pipelines\n- A `%P` prompt variable shows pipeline status (`on`, `off`, or `abort`)\n\n### \\watch Syntax\n\n```\n\\watch [i[nterval]=SECONDS] [c[ount]=TIMES] [m[in_rows]=ROWS] [SECONDS]\n```\n\n`count` and `min_rows` require PostgreSQL 17+.\n\n- `interval` — seconds between executions (default: 2, overridable via `WATCH_INTERVAL` variable)\n- `count` — stop after N executions\n- `min_rows` — stop if query returns fewer than N rows\n\nIf the query buffer is empty, `\\watch` re-executes the most recently sent query.\n\nExamples:\n\n```sql\nSELECT * FROM pg_stat_activity WHERE state = 'active';\n\\watch interval=5 count=10      -- every 5s, stop after 10 runs\n\nSELECT count(*) FROM queue WHERE status = 'pending';\n\\watch i=1 min_rows=1            -- every 1s, stop when queue is empty\n```\n\n### Exit Codes\n\n| Code | Meaning                                                         |\n| ---- | --------------------------------------------------------------- |\n| 0    | Successful completion                                           |\n| 1    | A fatal error occurred (server error, connection failure, etc.) |\n| 2    | Connection failed (could not connect to the server)             |\n| 3    | Script execution ended due to ON_ERROR_STOP                     |\n\n## Security Considerations\n\n### Destructive Operations Checklist\n\nBefore running any destructive SQL, verify impact first:\n\n```sql\n-- BEFORE DELETE: check how many rows are affected\nSELECT count(*) FROM users WHERE condition;  -- verify scope\nBEGIN;\nDELETE FROM users WHERE condition RETURNING *;  -- see what was deleted\n-- ROLLBACK if wrong; COMMIT only after verification\n\n-- BEFORE DROP TABLE: verify no foreign keys depend on it\n\\d table_name  -- check \"Referenced by\" section\n-- Consider renaming first: ALTER TABLE old RENAME TO old_backup;\n```\n\n### Dangerous Commands Requiring Extra Caution\n\n| Command\u002FPattern                         | Risk                                                      | Mitigation                                                                                           |\n| --------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |\n| `\\gexec`                              | Executes generated SQL without confirmation               | Always inspect the generating query first by running it without `\\gexec`; set `ON_ERROR_STOP on` |\n| `\\! command`                          | Arbitrary shell execution                                 | No sandboxing; commands run with psql user's full privileges                                         |\n| `\\copy ... program 'cmd'`             | Shell command injection if filename comes from user input | Never concatenate untrusted input into the `program` string                                        |\n| `\\deu+`                               | May display remote user passwords                         | Avoid using `\\deu+` in shared\u002Fpiped output; use `\\deu` without `+`                             |\n| `DELETE`\u002F`UPDATE` without `WHERE` | Affects every row in the table                            | Always use `WHERE`; wrap in `BEGIN`\u002F`ROLLBACK` to preview                                      |\n| `DROP DATABASE\u002FTABLE`                 | Irreversible data loss                                    | Verify you're on the correct database with `\\conninfo` first                                       |\n\n### Variable Interpolation Safety\n\npsql variables are **plain text substitution**, not parameterized queries. This means:\n\n```sql\n-- UNSAFE: if :name contains \"Robert'); DROP TABLE users;--\" it will execute the injection\nSELECT * FROM users WHERE name = :'name';\n\n-- SAFER: use \\prompt for interactive input (user sees what they typed)\n\\prompt 'Enter name: ' search_name\nSELECT * FROM users WHERE name = :'search_name';\n\n-- SAFEST: use \\bind for programmatic parameter passing (truly parameterized)\nSELECT * FROM users WHERE name = $1;\n\\bind 'Robert' \\g\n```\n\nThe `:'varname'` form (quoted) is always safer than `:varname` (unquoted), because unquoted substitution can break SQL syntax or enable injection. Use `:\"varname\"` for identifiers (table\u002Fcolumn names) — it properly escapes embedded double quotes.\n\n## When to Use What\n\n| Scenario                      | Recommended Command                                            |\n| ----------------------------- | -------------------------------------------------------------- |\n| Quick table inspection        | `\\d table_name`                                              |\n| List all tables in schema     | `\\dt schema.*`                                               |\n| Check indexes on a table      | `\\di+ table_name*` or `\\d table_name`                      |\n| Export query to CSV           | `\\copy (SELECT ...) TO 'file.csv' WITH (FORMAT csv, HEADER)` |\n| Import CSV into table         | `\\copy table FROM 'file.csv' WITH (FORMAT csv, HEADER)`      |\n| Run migration script          | `psql -1 -f migration.sql dbname`                            |\n| Watch a live query            | `SELECT ... \\watch 5`                                        |\n| Pivot query results           | `SELECT ... \\crosstabview`                                   |\n| Script with conditional logic | `\\if :var ... \\endif`                                        |\n| Batch-insert many rows        | Use `\\startpipeline` \u002F `\\endpipeline`                      |\n| SQL syntax help               | `\\h CREATE TABLE`                                            |\n| psql command help             | `\\? commands`                                                |\n| Check query execution time    | `\\timing on` then run query                                  |\n| Debug error details           | `\\errverbose`                                                |\n| Handle large result sets      | `\\set FETCH_COUNT 1000` then run query                       |\n| Auto-savepoint on errors      | `\\set ON_ERROR_ROLLBACK on` then use transactions            |\n\n- **`references\u002Fmeta-commands-core.md`** — Core meta-commands: query buffer behavior, argument parsing rules, connection management, query execution, `\\copy` syntax, and scripting commands (`\\if`, `\\i`, `\\o`, backquote expansion). Read this when you need exact syntax or behavioral details for any backslash command.\n- **`references\u002Fmeta-commands-inspection.md`** — Full `\\d` command reference: all object inspection commands, modifiers (`S`, `+`, `x`), and pattern matching rules. Read this when exploring database schema or when the user needs to inspect tables, indexes, views, functions, privileges, etc.\n- **`references\u002Fmeta-commands-formatting.md`** — Output formatting (`\\pset` options and all format descriptions), pipeline mode, `\\watch`, `\\crosstabview`, and session management (`\\e`, `\\ef`, `\\ev`, `\\timing`, etc.). Read this when the user needs to control output format or use pipeline mode.\n- **`references\u002Fcli-options-and-variables.md`** — All CLI flags, environment variables, psql internal variables (AUTOCOMMIT, ON_ERROR_STOP, ECHO, FETCH_COUNT, etc.), prompt customization, `~\u002F.psqlrc` configuration, and SQL interpolation syntax. Read this when configuring psql startup behavior, writing scripts that depend on variable state, or customizing prompts.\n- **`references\u002Ftips-workflows.md`** — Practical workflows (exploring a new database, understanding table structure), scripting patterns (safe scripts, conditional execution, `\\gexec`), output control for automation, and data import\u002Fexport patterns. Read this when the user asks how to accomplish a specific task with psql.\n- **`references\u002Ftips-advanced.md`** — Performance tips, debugging\u002Fintrospection (`EXPLAIN`, lock analysis, `ECHO_HIDDEN`), safety best practices (ON_ERROR_STOP, transaction patterns, search_path safety), and common gotchas. Read this for lock analysis, query plan inspection, and troubleshooting.\n\n## Important Notes\n\npsql handles two comment styles differently:\n\n- **C-style block comments** (`\u002F* ... *\u002F`): Passed to the server for processing and removal.\n- **SQL-standard comments** (`--`): Removed by psql itself, before sending to the server.\n\nThis distinction matters when writing scripts that rely on comment behavior — only SQL-standard comments are stripped client-side.\n\n### Variable Variables (Soft References)\n\npsql allows indirect variable references through `\\set`:\n\n```sql\n\\set foo 'my_table'\n\\set bar :foo         -- copies the value of foo into bar\n\\echo :bar            -- outputs: my_table\n```\n\nWhile constructs like `\\set :foo 'something'` are syntactically valid, they produce \"soft links\" that have limited practical use. For straightforward variable copying, use `\\set new_var :old_var`.\n\n### Version Compatibility\n\npsql works best with servers of the same or an older major version. Backslash commands (especially `\\d` family) may fail with newer server versions. When connecting to multiple server versions, use the newest available psql client. The `\\d` commands generally work with servers back to version 9.2.\n\n## External References\n\n- [PostgreSQL Client Applications](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fapp-psql.html)\n- [Official PostgreSQL Documentation](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Findex.html)\n- [The SQL Language](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql.html)\n- [SQL Syntax - The SQL Language](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-syntax.html)\n- [SQL Command](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-commands.html)\n- [PostgreSQL Wiki](https:\u002F\u002Fwiki.postgresql.org\u002F)\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n",{"name":5,"risk":25,"source":41,"license":14,"date_added":42,"description":7,"source_repo":43,"source_type":27,"license_source":44},"https:\u002F\u002Fgithub.com\u002Fchaunsin\u002Fagent-skills\u002Ftree\u002Fmaster\u002Fskills\u002Fpostgresql-cli",1782864000000,"chaunsin\u002Fagent-skills","https:\u002F\u002Fgithub.com\u002Fchaunsin\u002Fagent-skills\u002Fblob\u002Fmaster\u002FLICENSE","main","f3312ba749561b6159f477dbfc9313c875d40a56",".agents\u002Fskills_archive\u002Fpostgresql-cli","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612","2026-10-25 23:50:58",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill postgresql-cli",{"tool":57,"command":58},"bunx","bunx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill postgresql-cli",{"tool":60,"command":61},"pnpm","pnpm dlx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill postgresql-cli","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002FSKILL.md",true,[65,71,75,79,83,87],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fcli-options-and-variables.md","REFERENCE","参考文档",21658,"https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002Freferences\u002Fcli-options-and-variables.md",{"path":72,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fmeta-commands-core.md",18284,"https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002Freferences\u002Fmeta-commands-core.md",{"path":76,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Fmeta-commands-formatting.md",6940,"https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002Freferences\u002Fmeta-commands-formatting.md",{"path":80,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Fmeta-commands-inspection.md",7287,"https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002Freferences\u002Fmeta-commands-inspection.md",{"path":84,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Ftips-advanced.md",8153,"https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002Freferences\u002Ftips-advanced.md",{"path":88,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Ftips-workflows.md",10484,"https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fpostgresql-cli\u002Freferences\u002Ftips-workflows.md",[92,121,144,166,194,218],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":96,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":104,"publishedAt":36},"01M6Q0FA5FZ410Z33Z3TFQ4DBA","zero-trust","Implement zero-trust network architecture. Configure identity-based access, micro-segmentation, and continuous verification. Use when implementing modern security architectures.","MIT","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzero-trust\u002FSKILL.md",[99],{"categoryNo":100,"categoryName":101,"taxonomyType":102,"taxonomyTypeDesc":103},"01JBSEEDCAT000000000000011","运维与部署","SCENARIO","使用场景",[105,106,107,108,109,110,94,111,112,113,114,115,27,45,116,25,117,118,119,120],"ZeRO","trust","zero trust","architecture","assessment","verification","segmentation","devops-security","access","configure","only","active","scope","scripts","relevant","implementing",{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":96,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":36},"01M6Q0F1YZJW3KX5FBKEVZ8CV4","zcode-delegate","Delegate coding tasks to the Z.AI ZCode CLI only when the user explicitly requests it, while the orchestrator retains review and landing responsibility.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzcode-delegate\u002FSKILL.md",[],[128,129,130,131,20,132,133,134,135,136,137,138,139,115,140,27,141,142,25,143],"delegate","zcode","zcode delegate","review","orchestration","tasks","run","Bash","model","node","read","orchestrator","files","desktop app","app","agent-orchestration",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":96,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":36},"01M6Q0ETK41VGNMYEXW0T00AJN","youtube-transcript","Fetch YouTube transcripts through DeepAPI or local fallback tooling and save clean text output.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript\u002FSKILL.md",[],[151,152,153,154,34,155,156,33,32,157,158,159,160,27,45,161,162,163,164,165],"transcript","youtube transcript","youtube","safe","codex","research","text","fetch","tooling","clean","local","output","deepapi","youtube transcripts","blob",{"skillNo":167,"name":168,"nameZh":6,"description":169,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":96,"licenseFileUrl":6,"sourceHtmlUrl":170,"categories":171,"keywords":183,"publishedAt":36},"01M6Q0EPPH2PVMDW40017F8WX0","youtube-transcript-skills","Fetch YouTube video transcripts, search videos\u002Fchannels, browse channels, and extract playlists via the getyoutubetranscript.com API - free tier, no card required.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript-skills\u002FSKILL.md",[172,175,178],{"categoryNo":173,"categoryName":174,"taxonomyType":102,"taxonomyTypeDesc":103},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":176,"categoryName":177,"taxonomyType":102,"taxonomyTypeDesc":103},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":179,"categoryName":180,"taxonomyType":181,"taxonomyTypeDesc":182},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[151,152,153,184,154,185,34,155,33,186,187,188,189,158,190,27,45,191,192,193],"youtube transcript skills","gemini","search","api","Video","browse","api-integration","free","card","channels",{"skillNo":195,"name":196,"nameZh":6,"description":197,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":96,"licenseFileUrl":6,"sourceHtmlUrl":198,"categories":199,"keywords":204,"publishedAt":36},"01M6Q0EAB96PX83W5PTE8A0R8D","youtube-notetaker","Turn YouTube talks into local study notes with slides, transcripts, editable annotations, and a markdown-backed viewer.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-notetaker\u002FSKILL.md",[200,203],{"categoryNo":201,"categoryName":202,"taxonomyType":102,"taxonomyTypeDesc":103},"01JBSEEDCAT000000000000003","演示文稿",{"categoryNo":176,"categoryName":177,"taxonomyType":102,"taxonomyTypeDesc":103},[153,205,206,20,154,207,208,209,210,33,188,211,212,213,214,45,215,161,216,217],"youtube notetaker","notetaker","workflow","official","notes","code","markdown","slides","annotations","README","study","dair-academy","viewer",{"skillNo":219,"name":220,"nameZh":6,"description":221,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":96,"licenseFileUrl":6,"sourceHtmlUrl":222,"categories":223,"keywords":225,"publishedAt":36},"01M6Q0E55F0GW5MX48V8HXS8B5","youtube-full","Fetch YouTube transcripts, search videos, browse channels, and extract playlists via TranscriptAPI — no yt-dlp, no Google API key, works from any cloud server.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-full\u002FSKILL.md",[224],{"categoryNo":173,"categoryName":174,"taxonomyType":102,"taxonomyTypeDesc":103},[226,153,227,228,154,185,186,229,230,187,188,189,158,231,190,27,45,191,232,164],"youtube full","full","google","server","dlp","credits","automatic"]