Course contentsShow
← Databases & SQL
Lesson 852 of 1,9538. PostgreSQL InternalsFree lesson

System Catalogs and Relcache

You will query system catalogs to inspect database metadata and internal configuration states.

In this lesson, you will learn how PostgreSQL keeps track of your database structure using internal tables called "System Catalogs" and how it caches that metadata in memory via the "Relcache."

The System Catalogs

PostgreSQL is "self-describing," meaning it stores information about its own tables, columns, and indexes inside regular database tables. These are known as System Catalogs. For example, the pg_class catalog stores rows representing every table, index, and sequence in your database.

If you want to see the "metadata" of a table you created, you aren't just looking at a configuration file; you are querying a standard system table. You can peek into the catalog with a simple query:

SELECT relname, relkind 
FROM pg_class 
WHERE relname = 'my_table_name';

In this query, relname is the table name, and relkind tells the engine if the entry is a table (r), an index (i), or a sequence (S).

The Relcache (Relation Cache)

While System Catalogs are the "source of truth" stored on disk, querying them for every single operation would be incredibly slow. Imagine needing to hit the disk every time you performed a SELECT just to check if a column exists!

To solve this, PostgreSQL maintains an in-memory structure called the Relcache (Relation Cache). When you access a table for the first time, PostgreSQL reads the relevant rows from the System Catalogs and loads them into a specialized hash table in shared memory. Subsequent lookups for that table’s metadata—like its column types, storage parameters, or OIDs—are served instantly from this cache.

The Relcache is intelligent: it tracks dependencies. If you perform an ALTER TABLE operation, the system automatically invalidates the entry in the Relcache, forcing the engine to reload the updated metadata from the System Catalogs the next time the table is accessed. This ensures that your query plan is always based on the current state of the database while benefiting from the speed of memory.

Key Takeaway: System Catalogs provide the disk-based source of truth for database metadata, while the Relcache provides a high-performance, in-memory copy that the engine uses to execute queries efficiently.