2.2 Querying the Catalog
That the catalog is a table means users can query it with SQL. For example, "which tables are in my database and what are their columns" can be checked with a query like the following.
SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_name = 'customer';
Figure 2-1. Result of a catalog query
block-beta
columns 6
src["information_schema.columns (all tables, one row per column)"]:6
h1["table_name"] h2["column_name"] h3["data_type"] space:3
a1["..."] a2["..."] a3["..."] an["<- other tables: filtered out"]:3
b1["customer"] b2["id"] b3["integer"] bn["<- WHERE table_name = 'customer'"]:3
c1["customer"] c2["name"] c3["text"] space:3
d1["customer"] d2["phone"] d3["text"] space:3
e1["customer"] e2["grade"] e3["smallint"] space:3
f1["..."] f2["..."] f3["..."] fn["<- other tables: filtered out"]:3
res<["result: 4 rows"]>(down):3 space:3
r0["table_name"] r1["column_name"] r2["data_type"] space:3
g1["customer"] g2["id"] g3["integer"] space:3
i1["customer"] i2["name"] i3["text"] space:3
j1["customer"] j2["phone"] j3["text"] space:3
k1["customer"] k2["grade"] k3["smallint"] space:3
class src,res plain
class h1,h2,h3,r0,r1,r2 meta
class a1,a2,a3,f1,f2,f3,an,fn muted
class b1,b2,b3,c1,c2,c3,d1,d2,d3,e1,e2,e3,g1,g2,g3,i1,i2,i3,j1,j2,j3,k1,k2,k3 data
class bn hot
The upper table shows the catalog view information_schema.columns. This view holds the column information of every table in the database, one row per column. table_name is the table the column belongs to, column_name is the column name, and data_type is the column type. The rows marked ... are columns of tables other than customer.
The WHERE table_name = 'customer' condition works exactly as it does when querying an ordinary table: it keeps only the rows that belong to the customer table and filters out the rest. The lower table is the result. The number of rows in the result is the number of columns in the customer table, and each row gives a column's name and type, so the result alone is enough to understand the table's structure. The four columns shown here (id, name, phone, grade) appear again when we decode bytes in Section 2.4.
information_schema is a set of catalog tables or views defined by the SQL standard, and it can be queried in almost the same way in PostgreSQL, MySQL, and SQL Server. Beyond the standard, each database also supports its own views: pg_catalog in PostgreSQL, the sys views in SQL Server, and the data dictionary views in Oracle (USER_TABLES, ALL_TAB_COLUMNS, and so on).
In practice, when you first take over an existing project, it helps to improve your understanding of the system by querying the catalog. Even without documentation, a few lines of query reveal the table list, column layout, indexes, and foreign key relationships.