Introduction to PostgreSQL
PostgreSQL 19.0
We compared databases by the jobs an application needs to do. Now take one of the relational options and see how an application uses it to read and change related records. PostgreSQL, often called Postgres, is a free, open-source object-relational database management system. It organizes data into tables with rows and columns. You use SQL to create tables, query data, and make changes.
On this page
PostgreSQL, SQL, and psql
When you ask for the list of students enrolled in a course, you can type an SQL query into psql. The client sends that query to the PostgreSQL server, which reads the database and sends the results back.
SELECT students.name
FROM enrollments
JOIN students ON students.id = enrollments.student_id
WHERE enrollments.course_id = 1
ORDER BY students.name;
PostgreSQL- The database software. It manages the data and executes queries. It is an object-relational system, so it also supports extensions and custom data types.
SQL- The language for creating tables, reading data, and making changes.
psql- The terminal client you will use to connect to the PostgreSQL server and run SQL.
History and SQL standards
PostgreSQL traces its roots to the POSTGRES research project at the University of California, Berkeley, which began in 1986. The project has been developed for more than 40 years and is known for reliability, data integrity, and extensibility. PostgreSQL implements many features of the SQL standard. Syntax and behavior can still differ across database engines.
-- Standard SQL that PostgreSQL supports
SELECT CURRENT_DATE AS today;
-- PostgreSQL's shorthand cast syntax
SELECT '42'::integer AS number;
ACID transactions
A single SQL query can read a record. Some application actions, such as enrolling a student, need several changes to succeed together. In a course registration app, you can save the enrollment and reduce the number of available seats in one transaction. COMMIT saves the changes. ROLLBACK discards the uncommitted changes. ACID describes four properties of a transaction.
-- The course_seats_demo table tracks seats for course 1.
BEGIN;
WITH reserved_seat AS (
UPDATE course_seats_demo
SET seats_open = seats_open - 1
WHERE course_id = 1 AND seats_open > 0
RETURNING course_id
)
INSERT INTO enrollments (student_id, course_id, enrolled_on)
SELECT 3, course_id, CURRENT_DATE
FROM reserved_seat
RETURNING student_id, course_id;
-- When no seat is available, the insert returns zero rows.
COMMIT;
Atomicity- Both changes succeed together. If reducing the available seats fails and the transaction is aborted, the enrollment is discarded too.
Consistency- The saved data must satisfy the rules you define. A foreign key can require a valid course, and a CHECK constraint can require the remaining seats to be zero or more.
Isolation- Other transactions cannot see the unfinished changes. The isolation level controls what each transaction can observe when several run at once.
Durability- With the default durability settings, changes remain saved after a successful COMMIT even if PostgreSQL crashes afterward.
Concurrent reads and writes with MVCC
A transaction keeps the steps of one enrollment together. What will another user see if they read the data while those changes are in progress? Multi-Version Concurrency Control (MVCC) lets a query read a snapshot of the data. If an administrator is updating a course fee, a plain SELECT can still read the previously committed fee while that update is in progress. Ordinary reads and writes can proceed together. If two transactions try to update the same row, one can still have to wait for a lock.
-- Session A: run these two statements and leave the transaction open.
BEGIN;
UPDATE courses SET fee = 45.00 WHERE id = 1;
-- Session B: run this query while Session A is open.
SELECT fee FROM courses WHERE id = 1;
-- The query sees the previously committed fee.
-- Session A: finish the demonstration and restore the original fee.
ROLLBACK;
Data types, text search, and extensions
PostgreSQL provides column types for structured and flexible data, and it can be extended for specialized searches.
SELECT CAST(19.95 AS numeric(10, 2)) AS price,
ARRAY['html', 'css'] AS tags,
'{"level":"beginner"}'::jsonb ->> 'level' AS course_level,
to_tsvector('english', 'Learning HTML') @@
plainto_tsquery('english', 'learn') AS text_matches;
Built-in types- Use numeric for exact amounts, arrays for lists such as tags, and UUID for identifiers. JSON keeps the original JSON text. JSONB stores a parsed representation and can be indexed for many JSON queries.
Full-text search- Search course descriptions by words, match word forms for a configured language, and rank results by relevance.
Extensions and custom code- You can define custom data types and functions. When available on your server, PostGIS adds geographic queries such as finding nearby branches. The pgvector extension stores embeddings and searches them by similarity.
Data integrity and growing workloads
Constraints enforce data rules. Indexes, partitioning, and replication address different needs as a database grows.
-- The enrollment's course_id must reference an existing course.
CREATE TEMP TABLE enrollment_example (
student_id integer NOT NULL REFERENCES students(id),
course_id integer NOT NULL REFERENCES courses(id),
PRIMARY KEY (student_id, course_id)
);
-- Support lookups that filter on course_id.
CREATE INDEX ON enrollment_example (course_id);
Constraints- UNIQUE can prevent duplicate student emails. A foreign key prevents an enrollment from pointing to a missing course.
Indexes- A suitable index can speed up frequent lookups, such as finding enrollments by course ID. Indexes also use storage and add work when data changes.
Partitioning- Split one logical table into parts, such as enrollments by year. A query that filters on the partition key can skip parts it does not need.
Replication- Copy data changes to another PostgreSQL server. A standby configured for reads can serve queries, and a standby can be promoted if the primary fails. In a typical primary–standby setup, application writes go to the primary.
PostgreSQL compared with other databases
These databases differ in how they organize data, what features they offer, and how applications connect to them.
-- PostgreSQL: read a field from a JSONB document.
SELECT '{"name":"Notebook","stock":12}'::jsonb ->> 'name' AS product;
-- MongoDB shell: read that field from a stored BSON document.
db.products.findOne({ _id: 1 }, { name: 1, _id: 0 });
MySQL and MariaDB- Both are relational database servers with open-source editions. The SQL features and syntax you can use depend on the engine and version. For example, a project built around PostGIS requires PostgreSQL with PostGIS available.
MongoDB- MongoDB stores BSON documents in collections. PostgreSQL can store and query flexible documents in a JSONB column while retaining relational tables, joins, and foreign keys for the surrounding data.
SQLite- SQLite runs inside the application and usually reads and writes a local database file directly. PostgreSQL runs as a separate server that many clients can connect to over a network.
Use cases and cloud hosting
In a course registration app, the frontend requests a course list from the backend API. The API checks permissions, sends SQL to PostgreSQL through a database client library, and returns the results. In the next lesson, you will install PostgreSQL and connect directly with psql.
// Backend: a database pool configured for your PostgreSQL server.
app.get("/api/courses", requireSignIn, async (_request, response) => {
const { rows } = await pool.query("SELECT id, title FROM courses ORDER BY id");
response.json(rows);
});
Web and mobile backends- Store accounts, orders, or enrollments behind the app’s API.
Analytics and reporting- Use SQL to count enrollments by course or compare registrations by month.
Geospatial and AI applications- Use PostGIS to find nearby locations, or use pgvector to find course descriptions with similar meanings using their embeddings.
Managed PostgreSQL- Examples include Amazon RDS for PostgreSQL, Google Cloud SQL for PostgreSQL, Azure Database for PostgreSQL, Supabase, and Neon. Supported versions and extensions vary by service.
Official references
- PostgreSQL · About and features
- PostgreSQL · Tables
- PostgreSQL · Primary and foreign keys
- PostgreSQL · Transactions
- PostgreSQL · MVCC
- PostgreSQL · Locking
- PostgreSQL · Data types
- PostgreSQL · Full-text search
- PostgreSQL · Indexes
- PostgreSQL · Partitioning
- PostgreSQL · Replication and standby servers
- PostGIS · Documentation
- pgvector · Documentation
- MySQL · About
- MariaDB · Documentation
- MongoDB · Documents
- SQLite · Embedded architecture
- AWS · Amazon RDS for PostgreSQL
- Google Cloud · Cloud SQL for PostgreSQL
- Microsoft Azure · Azure Database for PostgreSQL
- Supabase · PostgreSQL database
- Neon · Documentation