Start with the mental model: SQL is the language, PostgreSQL is the database system, and psql is one client used to talk to PostgreSQL.
SQL / CONCEPT
POSTGRESQL
psql / CLIENT
01 — What SQL, PostgreSQL & psql Are
Core Difference
SQLA language for defining, querying, changing, and controlling relational data.
Used inside psql, applications, GUI clients, migrations, and other database tools.
PostgreSQLA relational database management system that implements SQL plus PostgreSQL-specific features.
psql connects to a running PostgreSQL server and sends work to it.
psqlA command-line client for PostgreSQL, not a database and not a replacement for SQL.
Accepts SQL plus psql-only backslash meta-commands such as \dt and \d.
Where Code Executes
SELECT * FROM users;SQL statement interpreted and executed by the PostgreSQL server.
Type it at the psql prompt; psql sends it to PostgreSQL.
CREATE TABLE ...;SQL data-definition statement executed by PostgreSQL.
psql is only the interactive client carrying the statement.
\dtNot SQL.
psql meta-command; psql itself uses PostgreSQL metadata to list tables.
\d usersNot SQL.
psql meta-command that describes a relation.
pg_dumpNot SQL.
Separate PostgreSQL client utility for backups; it is not a psql command.
Portable vs PostgreSQL-Specific
Portable SQLSELECT, INSERT, UPDATE, DELETE, JOIN, GROUP BY, CREATE TABLE, constraints, and transactions are broadly shared across relational databases.
PostgreSQL dialectAdds PostgreSQL syntax, operators, data types, functions, extensions, and implementation details.
psql layerAdds interactive conveniences: slash commands, variables, query buffer tools, formatting, scripting, timing, and file execution.
Rule of thumbIf it begins with an unquoted backslash at the psql prompt, it is normally a psql meta-command rather than SQL.
Typical Workflow
1. ConnectUse psql or another client to open a PostgreSQL connection.
2. InspectUse psql meta-commands such as \l, \dn, \dt, and \d.
3. QueryWrite SQL such as SELECT, JOIN, GROUP BY, INSERT, and UPDATE.
4. Use PostgreSQL featuresApply PostgreSQL types/operators such as JSONB, arrays, RETURNING, ILIKE, or ON CONFLICT when useful.
5. DiagnoseUse EXPLAIN / EXPLAIN ANALYZE and psql timing/output tools.
6. AutomateMove repeatable SQL into migration/query files and run with application tooling or psql -f.
SELECT Anatomy
SELECT columnsChoose result expressions or columns.
Enter normally at the psql prompt.
FROM tableChoose source relations.
Use \dt first when you need to discover tables.
JOIN ... ON ...Combine related rows.
Use \d table to inspect keys and columns.
WHERE conditionFilter individual rows before grouping.
\p shows the current query buffer before execution.
GROUP BY columnsGroup rows for aggregate calculations.
\g sends the current query buffer to the server.
HAVING conditionFilter aggregate groups.
A semicolon normally terminates and sends a complete SQL statement.
ORDER BY expressionSort result rows.
\pset controls how psql formats returned rows.
LIMIT n OFFSET nPostgreSQL row-limiting syntax commonly used for pagination.
\timing can show execution duration.
Joins
INNER JOINReturn matching rows from both sides.
LEFT JOINKeep every left row and matching right rows.
RIGHT JOINKeep every right row and matching left rows.
FULL OUTER JOINKeep matched rows plus unmatched rows from both sides.
CROSS JOINProduce the Cartesian product.
SELF JOINJoin a relation to itself using aliases.
USING (column)Concise PostgreSQL/SQL join syntax when join-column names match.
Qualified namesUse aliases such as u.id and o.id to avoid ambiguity.
Aggregates & Windows
COUNT(*)Count rows.
COUNT(DISTINCT id)Count distinct non-NULL values.
SUM(amount)Total numeric values.
AVG(amount)Average non-NULL values.
MIN / MAXSmallest or largest value.
ROW_NUMBER() OVER (...)Number rows without collapsing them.
RANK() / DENSE_RANK()Ranking window functions.
LAG() / LEAD()Read previous or following row values.
PARTITION BYRestart a window calculation per group.
Subqueries, CTEs & Sets
WHERE EXISTS (...)Test whether a subquery returns a row.
WHERE id IN (SELECT ...)Filter against a subquery result set.
WITH name AS (...)Create a common table expression for one statement.
WITH RECURSIVEExpress recursive hierarchies and graph/tree traversal.
UNIONCombine compatible result sets and remove duplicates.
UNION ALLCombine compatible result sets without duplicate removal.
INTERSECTRows common to both result sets.
EXCEPTRows in the first result but not the second.
NULL & Expressions
IS NULL / IS NOT NULLCorrectly test for NULL.
COALESCE(a,b)Return the first non-NULL expression.
NULLIF(a,b)Return NULL when two expressions compare equal.
CASE WHEN ... THEN ... ENDConditional SQL expression.
CAST(value AS type)Standard-style explicit type conversion.
value::typePostgreSQL shorthand cast syntax.
CURRENT_DATECurrent SQL date.
CURRENT_TIMESTAMPCurrent date and time.
psql Query Buffer
\pDisplay the current query buffer.
\gSend the current query buffer to PostgreSQL.
\gxSend the query and show expanded output where supported.
\rReset/clear the query buffer.
\eOpen the current query buffer in an editor.
\ef functionEdit a function definition.
\ev viewEdit a view definition.
\w file.sqlWrite the current query buffer to a file.
PostgreSQL speaks SQL, but its dialect includes powerful types, operators, expressions, and data-changing features that are not universally portable.
SQL / CONCEPT
POSTGRESQL
psql / CLIENT
03 — PostgreSQL Extensions to Everyday SQL
PostgreSQL Data Types
BOOLEANNative true/false type.
SMALLINT / INTEGER / BIGINTSigned integer types.
NUMERIC(p,s)Exact arbitrary-precision numeric values.
TEXT / VARCHAR / CHARCharacter types.
BYTEABinary string data.
UUIDNative universally unique identifier type.
JSON / JSONBJSON text and binary-decomposed JSON storage; JSONB supports indexing and rich operators.
ARRAYNative arrays of supported element types.
ENUMUser-defined enumerated type.
RANGE / MULTIRANGENative range types for values such as numbers and timestamps.
INET / CIDR / MACADDRNetwork-address data types.
TIMESTAMP / TIMESTAMPTZTimestamp without and with time-zone semantics.
Identity & Generated Values
SQL standard identityGENERATED ... AS IDENTITY is the modern identity-column concept.
PostgreSQL supports identity columns directly.
SERIALNot standard SQL; historical PostgreSQL shorthand backed by a sequence.
Still encountered in existing schemas.
nextval(sequence)PostgreSQL sequence function.
psql \d table exposes default/identity information.
GENERATED ALWAYS AS (...) STORED/VIRTUALGenerated-column syntax/features are PostgreSQL-version dependent.
Inspect current definition with \d+ table.
PostgreSQL Operators
ILIKECase-insensitive pattern matching.
~ / ~*Regular-expression match, case-sensitive / insensitive.
!~ / !~*Regular-expression non-match.
-> / ->>Extract JSON/JSONB object/array values as JSON or text.
@>Containment operator used by types including JSONB and arrays.
<@Contained-by operator.
&&Overlap operator for supported types such as arrays/ranges.
||Concatenate strings and, in PostgreSQL contexts, supported collection-like values.
ANY(array)Compare against any element of an array.
ALL(array)Compare against every element of an array.
High-Value PostgreSQL Syntax
INSERT ... RETURNING idReturn inserted values without issuing a separate SELECT.
UPDATE ... RETURNING *Return rows changed by UPDATE.
DELETE ... RETURNING *Return deleted rows.
INSERT ... ON CONFLICT ...PostgreSQL upsert / conflict handling.
DISTINCT ON (expr)PostgreSQL extension for selecting the first row per distinct expression under a defined ORDER BY.
FILTER (WHERE ...)Apply a condition to an aggregate.
LATERALAllow a FROM item/subquery to reference columns from preceding FROM items.
CREATE EXTENSION nameInstall an available PostgreSQL extension into the current database.
JSONB
payload->'user'Extract a JSON object value.
payload->>'name'Extract a JSON scalar as text.
payload @> '{"active":true}'Test JSONB containment.
jsonb_build_object(...)Construct a JSONB object.
jsonb_array_elements(...)Expand a JSON array into rows.
GIN indexCommon index family for searchable JSONB containment/key workloads.
Arrays
ARRAY[1,2,3]Construct an array.
values[1]Access an array element; PostgreSQL arrays normally use one-based subscripts.
array_length(values,1)Return a dimension length.
unnest(values)Expand an array to rows.
3 = ANY(values)Test whether an array contains a matching value.
values @> ARRAY[3]Array containment test.
Schemas & Search Path
schema.tableFully qualify an object.
CREATE SCHEMA appCreate a PostgreSQL schema namespace.
SHOW search_pathInspect schema lookup order.
SET search_path TO app, publicChange lookup order for the session/transaction scope.
publicDefault schema commonly present in PostgreSQL databases.
\dnpsql meta-command listing schemas.
psql adds a command-line layer around PostgreSQL: connections, discovery, descriptions, variables, formatting, files, timing, and scripting.
SQL / CONCEPT
POSTGRESQL
psql / CLIENT
04 — psql Interactive Reference
Connect from the Shell
psqlConnect using defaults/environment values.
psql -d appdbConnect to a database.
psql -U user -d appdbChoose user and database.
psql -h localhost -p 5432 -U user -d appdbSpecify host, port, user, and database.
psql 'postgresql://user@host:5432/db'Connect using a PostgreSQL connection URI.
psql -c 'SELECT 1;'Run one command and exit.
psql -f script.sql appdbExecute a SQL/psql script file.
psql -XDo not read startup files such as ~/.psqlrc.
psql --set=ON_ERROR_STOP=1 -f script.sql dbMake scripted execution stop after errors.
Discover Databases & Objects
\lList databases.
\l+List databases with additional details.
\dnList schemas.
\dtList tables visible in the search path.
\dt schema.*List tables in a specific schema.
\dvList views.
\dmList materialized views.
\diList indexes.
\dsList sequences.
\dfList functions.
\dTList data types.
\dxList installed extensions.
\duList roles.
Describe Objects
\d tableDescribe a table/relation.
\d+ tableDescribe with additional storage/details.
\d indexDescribe an index.
\d viewDescribe a view.
\df+ functionDescribe functions with more detail.
\dp tableShow access privileges.
\dd objectShow object comments/descriptions where available.
Output & Display
\xToggle expanded row display.
\pset format alignedUse aligned table output.
\pset format unalignedUse unaligned output.
\pset format csvUse CSV output where supported.
\pset border 0Change table border style.
\pset null 'NULL'Choose how NULL is displayed.
\aToggle aligned/unaligned output.
\tToggle tuples-only output.
\HToggle HTML output.
\o fileSend future query output to a file.
\oRestore output to standard output.
Timing & Execution
\timingToggle display of statement execution time.
\gExecute current query buffer.
\gexecExecute each field of query output as SQL commands; powerful and potentially destructive.
\gset prefix_Store a one-row result into psql variables.
\watch 2Repeat the current query every two seconds.
\errverboseRepeat the most recent server error at maximum verbosity.
Files & Scripts
\i file.sqlRead and execute commands from a file.
\ir relative.sqlRead a file relative to the current script file.
\eEdit current query buffer or a file.
\w file.sqlWrite current query buffer to a file.
\cd pathChange psql's current working directory.
\! commandRun a shell command from inside psql.
\qecho textWrite text to the current query-output stream.
\echo textWrite text to standard output.
psql Variables
\set name valueSet a psql variable.
:nameInterpolate a variable without quoting; use only when the inserted text is already safe SQL syntax.
:'name'Interpolate and quote a variable as an SQL literal.
:"name"Interpolate and quote a variable as an SQL identifier.
\unset nameRemove a psql variable.
\setList currently defined psql variables.
ON_ERROR_STOPWhen enabled, scripts stop after an error rather than continuing.
AUTOCOMMITpsql variable controlling whether successful statements are automatically committed outside explicit transactions.
Most database changes are SQL executed by PostgreSQL; psql mainly helps inspect, execute, script, and verify them.
SQL / CONCEPT
POSTGRESQL
psql / CLIENT
05 — DDL, DML, Transactions & Security
Create & Change Tables
CREATE TABLE users (...);SQL DDL creates a table in PostgreSQL.
\d users verifies the resulting definition.
ALTER TABLE users ADD COLUMN ...;SQL changes table structure.
\d+ users inspects the current structure.
ALTER TABLE ... ADD CONSTRAINT ...;SQL adds constraints.
\d table shows many constraints and indexes.
DROP TABLE users;SQL removes a table.
\dt confirms what remains.
CREATE VIEW name AS SELECT ...;SQL creates a view.
\dv lists views.
CREATE MATERIALIZED VIEW ...;PostgreSQL creates a stored query result.
\dm lists materialized views.
Constraints
PRIMARY KEYUniquely identifies a row.
FOREIGN KEYEnforces a relationship to referenced rows.
UNIQUEPrevents duplicate values/combinations.
NOT NULLRequires a value.
CHECK (...)Enforces a row-level predicate.
DEFAULT expressionSupplies a value when INSERT omits the column.
EXCLUDEPostgreSQL constraint preventing rows from matching specified operator combinations.
DEFERRABLEAllows supported constraint checking to be deferred within a transaction.
Data Changes
INSERT INTO ... VALUES ...Create rows.
INSERT INTO ... SELECT ...Insert rows produced by a query.
UPDATE ... SET ... WHERE ...Change matching rows.
DELETE FROM ... WHERE ...Delete matching rows.
TRUNCATE tableQuickly remove all rows; PostgreSQL-specific options affect identity/cascading behavior.
RETURNINGReturn affected rows from INSERT/UPDATE/DELETE/MERGE-style changes.
ON CONFLICTHandle unique/exclusion conflicts during INSERT.
Transactions
BEGIN;Start an explicit SQL transaction.
psql prompt typically changes to indicate transaction state.
COMMIT;Commit SQL transaction changes.
\echo can annotate scripts around transaction boundaries.
ROLLBACK;Undo the current transaction.
\errverbose can inspect the prior error.
SAVEPOINT name;Create an intermediate rollback point.
Still SQL; psql simply sends it to PostgreSQL.
ROLLBACK TO SAVEPOINT name;Undo work after a savepoint.
Useful interactively while testing multi-step changes.
SET TRANSACTION ...;Choose transaction characteristics.
SHOW transaction_isolation can inspect current settings.
Roles & Privileges
CREATE ROLE name LOGINCreate a PostgreSQL login role.
ALTER ROLE name ...Change role properties.
GRANT SELECT ON table TO roleGrant object privileges.
REVOKE SELECT ON table FROM roleRemove object privileges.
GRANT role_a TO role_bGrant membership in another role.
SET ROLE nameAssume another role within permitted membership.
\dupsql: list roles and attributes.
\dp tablepsql: display table/view/sequence privileges.
Schemas & Ownership
CREATE SCHEMA appCreate a namespace.
ALTER SCHEMA app OWNER TO roleChange schema ownership.
GRANT USAGE ON SCHEMA app TO roleAllow name resolution/access within a schema.
GRANT CREATE ON SCHEMA app TO roleAllow object creation in a schema.
ALTER TABLE t OWNER TO roleChange table owner.
\dn+psql: inspect schemas with additional information.
Prepared SQL from Applications
$1, $2 ...PostgreSQL server-side positional parameter notation used in prepared statements/protocol contexts.
Client placeholdersLibraries may expose ?, :name, $1, or another API-specific placeholder syntax.
Values vs identifiersParameters represent data values, not arbitrary table/column names.
Security ruleNever concatenate untrusted values directly into executable SQL.
psql variablesUseful for scripts, but they are a separate psql interpolation mechanism, not application prepared statements.
PostgreSQL adds implementation-specific performance and administration tools; psql is a convenient place to run and inspect them.
SQL / CONCEPT
POSTGRESQL
psql / CLIENT
06 — Indexes, Performance, Maintenance & Tools
Indexes
CREATE INDEX idx ON table(column);Create a B-tree index by default.
CREATE UNIQUE INDEX ...Create an index that also enforces uniqueness.
CREATE INDEX ... USING GIN (...)Create a GIN index for supported collection/search workloads.
CREATE INDEX ... USING GiST (...)Create a GiST index for supported generalized search workloads.
CREATE INDEX ... WHERE conditionCreate a PostgreSQL partial index.
CREATE INDEX ... (LOWER(email))Create an expression index.
REINDEX ...Rebuild an index/table/database index set using PostgreSQL commands.
\di+psql: list indexes with additional information.
EXPLAIN
EXPLAIN SELECT ...PostgreSQL shows the planned execution strategy without normally executing the SELECT.
Run directly in psql and inspect the plan text.
EXPLAIN ANALYZE SELECT ...Executes the query and reports actual timing/rows; use carefully.
\timing can show total client-observed statement time.
EXPLAIN (ANALYZE, BUFFERS) ...Adds execution and buffer-I/O details.
\x can improve readability for some diagnostic outputs.
Seq ScanSequentially scans table pages/rows.
Not automatically bad; can be correct for small/broad queries.
Index Scan / Index Only ScanUses a suitable index path.
\d table and \di help inspect available indexes.
VACUUM & ANALYZE
VACUUM table;Reclaim reusable space and maintain MVCC-related storage metadata.
VACUUM (ANALYZE) table;Vacuum and refresh planner statistics.
VACUUM FULL table;Rewrite/compact a table and take stronger locks; use deliberately.
ANALYZE table;Refresh planner statistics.
autovacuumPostgreSQL background maintenance mechanism for vacuum/analyze work.
\d+ tablepsql: inspect table details while diagnosing storage/schema issues.
Session & Server Settings
SHOW setting;Read one PostgreSQL configuration parameter.
SHOW ALL;Display session-visible configuration parameters.
SET setting = value;Change a setting for the current session where permitted.
SET LOCAL setting = value;Change a setting for the current transaction.
RESET setting;Restore a setting to its default for the session.
SELECT current_setting('name');Read a configuration value through SQL.
\conninfopsql: show current connection endpoint/user/database.
COPY vs \copy
COPY table TO '/server/path/file.csv' CSV HEADER;SQL COPY reads/writes files from the PostgreSQL server's filesystem and uses server privileges.
\copy table TO 'local.csv' CSV HEADER
COPY table FROM '/server/path/file.csv' CSV HEADER;Server-side SQL import.
\copy table FROM 'local.csv' CSV HEADER
PrivilegesServer COPY can require elevated file privileges.
\copy uses the psql/client machine's filesystem and client access.
Use caseFast bulk transfer between tables/queries and files.
\copy is usually more convenient from a developer workstation.
Backup & Restore Utilities
pg_dump appdb > backup.sqlCreate a plain-SQL logical backup using the pg_dump client utility.
pg_dump -Fc appdb -f backup.dumpCreate PostgreSQL custom-format backup.
psql appdb < backup.sqlRestore a plain SQL dump through psql.
pg_restore -d appdb backup.dumpRestore a non-plain pg_dump archive.
pg_dumpallDump all databases plus global objects in a PostgreSQL cluster in SQL form.
createdb / dropdbCommand-line utilities for creating/dropping PostgreSQL databases.
Notepg_dump, pg_restore, createdb, and dropdb are PostgreSQL client utilities, not psql slash commands.
Developer Troubleshooting
Connection refusedConfirm PostgreSQL is running, host/port are correct, and network/firewall rules allow the connection.
password authentication failedVerify role, password, pg_hba.conf rules, and chosen connection target.
relation does not existCheck current database, schema, search_path, quoted/case-sensitive identifiers, and object spelling.
permission deniedCheck role membership, object privileges, schema USAGE, and ownership.
current transaction is abortedA statement failed inside a transaction; ROLLBACK or rollback to a savepoint before continuing.
slow queryInspect EXPLAIN ANALYZE, row estimates, indexes, predicates, join order/strategy, and statistics.
psql aid\conninfo, \d, \dn, \dt, \timing, \errverbose, and \x are high-value diagnostics.
Which Tool Should I Use?
SQLUse when expressing data queries, schema changes, transactions, privileges, and database logic.
Portable concept; PostgreSQL executes its supported SQL dialect.
PostgreSQL featureUse when PostgreSQL provides a capability valuable to the application, such as JSONB, arrays, RETURNING, extensions, or specialized indexes.
Document dialect dependence when portability matters.
psqlUse for interactive querying, discovery, diagnostics, scripts, formatting, and quick administration.
Do not confuse psql meta-commands with SQL embedded in application code.
PostgreSQL utilityUse pg_dump, pg_restore, createdb, dropdb, vacuumdb, and related tools for their dedicated jobs.
These are separate executables, even though they ship with PostgreSQL client tooling.