Rana Maninder Singh
Lesson 1 of 11PostgreSQL

Postgres Orientation & psql

Lesson opener

In one line: How Postgres sits next to the MySQL-flavoured SQL you already know - same job, different engine habits.

Why it matters: GUIs hide what the server actually sees. psql is the common language between analysts, DBAs, and deploy scripts.

Before this lesson: SQL & DBMS (MySQL) / sql11

Before you start

ResourceLink
PreviousConstraints & transactions (finish SQL & DBMS (MySQL) first)
NextTypes & dialect that matter
PrerequisitesSQL & DBMS (MySQL) through sql11 — SELECT, joins, CTEs, basic windows
Time~45 minutes
InstallPostgreSQL & pgAdmin — server running, then the GUI. Do this first if psql is missing.
What you needPostgreSQL 14+ installed locally (or a cloud sandbox), and the psql client

What you will learn

  • How Postgres sits next to the MySQL-flavoured SQL you already know — same job, different engine habits
  • How to connect with psql and use the meta-commands you will use every day
  • A small lab schema mindset for this track (you will reuse patterns from the SQL course, not rebuild ANSI SQL)
  • Where extensions fit (awareness only — when to reach for them)

Why a second database course?

You already write SELECT, JOIN, GROUP BY, CTEs, and intro window functions. That skill travels.

What does not travel unchanged:

AreaIn the SQL course (MySQL-leaning)In this track
ClientWorkbench-firstpsql as the daily tool
TypesMySQL spellings (TINYINT, IFNULL, DATE_FORMAT)Postgres types and functions
Semi-structured dataRarely usedJSONB, arrays
UpsertsManual UPDATE/INSERT dancesON CONFLICT
Indexes“Create an index on this column”B-tree vs GIN vs GiST vs BRIN
PlansOne-line EXPLAIN mentionReal EXPLAIN ANALYZE
SecurityMostly app-layerRoles + row-level security

This course assumes you can already pull data. We focus on what Postgres is good at and how teams run it day to day.


Install check (one minute)

If this fails, stop and do PostgreSQL & pgAdmin. pgAdmin cannot create a server that is not already running — and this course does not stay in the GUI after that install lesson.

If Postgres is installed, this should print a version:

psql --version

Connect to a database (adjust user/host if your install differs):

psql -U postgres -d postgres

You should see a prompt like postgres=#. Type \q to quit.

Workplace note: On many teams the connection string lives in a secrets manager; locally you will often use a .pgpass file or env vars. For this lab, a local superuser is fine — never paste production passwords into lesson notes.


Tutorial — Your first five minutes in psql

[Orient yourself in a new database]

WHY: GUIs hide what the server actually sees. psql is the common language between analysts, DBAs, and deploy scripts.

WHEN: You just got credentials to a Postgres box and need to learn the landscape before writing reports.

\conninfo          -- where am I connected?
\l                 -- list databases
\c learnings_lab   -- connect to a database (create it first if needed)
\dt                -- list tables in the current schema
\d customers       -- describe one table (columns, indexes, FKs)
\x                 -- toggle expanded display (great for wide rows)
\timing            -- show how long each query took
\q                 -- quit

Breaking it down:

Create a practice database (once):

CREATE DATABASE learnings_pg;

Then:

\c learnings_pg

A tiny starter schema (optional)

You can recreate familiar lab ideas in Postgres. Example:

CREATE TABLE customers (
  customer_id  TEXT PRIMARY KEY,
  segment      TEXT NOT NULL,
  total_revenue NUMERIC(12,2) NOT NULL DEFAULT 0,
  churned      BOOLEAN NOT NULL DEFAULT FALSE,
  tags         TEXT[] DEFAULT '{}',
  profile      JSONB NOT NULL DEFAULT '{}'::jsonb
);

CREATE TABLE sales (
  sale_id     BIGSERIAL PRIMARY KEY,
  customer_id TEXT NOT NULL REFERENCES customers(customer_id),
  sale_month  DATE NOT NULL,
  revenue     NUMERIC(12,2) NOT NULL CHECK (revenue >= 0)
);

You will use arrays and JSONB for real in later lessons — this just plants the columns.


Callout — Extensions (awareness only)

Extensions = optional plugins for Postgres. You do not need them for day-one SELECT. You need to know they exist so you do not reinvent them badly.

ExtensionWhat it is forWhen people reach for it
pg_trgmTrigram similarity / fuzzy text“Find customers whose name is almost this spelling”; accelerate LIKE '%foo%' patterns with the right index
pgcryptoCrypto helpers in SQLHashing tokens, encrypting sensitive columns when policy allows DB-level crypto
PostGISSpatial types and functionsMaps, distances, “stores within 5 km” — GIS workloads

Enable pattern (once, as a privileged user):

CREATE EXTENSION IF NOT EXISTS pg_trgm;

Rule of thumb: Prefer a well-maintained extension over a clever custom function you alone understand. Deeper use of these tools is out of scope for this course — know the names, the job, and when to ask a DBA.


Essential commands

Command / actionWhat it does
psql -U user -d dbOpen an interactive session
\l / \c db / \dt / \d tableList DBs, connect, list tables, describe table
\x / \timingExpanded display / show query duration
\qLeave psql
CREATE EXTENSION …Turn on an optional extension (awareness)

Practice

Do this now:

  1. Connect with psql and run \conninfo, \l, and \timing.
  2. Create database learnings_pg if setup6 did not already.
  3. Create the customers / sales starter tables above (or your own equivalent).
  4. Insert two customers and three sales rows with plain INSERT.
  5. Save your script as exercises/answers/pg/01_orientation.sql.

Where This Connects

Scale-up: Once a single Postgres instance isn't enough, the usual first moves are connection pooling (e.g. PgBouncer) and read replicas, then managed cloud Postgres (RDS, Cloud SQL, Azure Database, Supabase-style hosts). Heavy analytics scans sometimes leave OLTP Postgres for a warehouse — same awareness note as in the SQL track. Not taught here.

Cross-ecosystem: This track follows SQL & DBMS (MySQL) — especially SQL commands. Same SELECT / join job; Postgres types and ops habits from here on.

Teacher walkthrough: psql daily loop

All figures illustrative.

Steps: Connect, list DBs/tables with meta-commands, run a simple SELECT, quit cleanly.

Failure example

Symptom: psql not found after GUI install

Diagnosis: PATH/binaries not on shell PATH; server may still be running.

Correction: Use setup6; open full path or fix PATH; verify psql --version then connect.

Validation: Re-run the lesson's verify query/EXPLAIN snippet and confirm expected plan or result.

Guided practice

You need to list tables in the current schema. Which meta-command family?

Complete solution: \dt (and \dn/\d as taught) — not a SQL invent-your-own SHOW in MySQL dialect.

Independent practice

Acceptance criteria:

Common mistakes

  1. Copying MySQL dialect unchanged.
  2. Skipping EXPLAIN when performance is the claim.
  3. Changing production without a transaction/backup habit (pg10).

Checklist

  • [ ] I can open psql and confirm which database I am on
  • [ ] I used \dt and \d without opening a GUI
  • [ ] I know pg_trgm / pgcrypto / PostGIS at “what/when” level
  • [ ] Next: Types & dialect that matter