Sub topic 13
Finding and Inspecting Views in the Catalog
This chapter assumes you can create views with CREATE VIEW, you know SELECT, JOIN and WHERE, and you have a rough idea of schemas and privileges. The examples use the employees and departments tables and the views from earlier chapters. Examples are written for PostgreSQL unless a heading says otherwise.
Why look at the catalog
A database stores more than your data. It also keeps a description of itself: which tables, columns, views and privileges exist. This description is the system catalog. It is exposed as ordinary tables and views that you read with SELECT.
You query the catalog when you need to answer questions like these:
- Which views exist in this schema, and who owns them?
- What exact query defines a view?
- Can I insert through this view?
- Which tables does this view depend on, and what breaks if I change one of them?
Because a view is only a stored query, the catalog is the one place where its definition is recorded.
Two layers: the standard and the vendor
SQL defines a standard catalog called information_schema. PostgreSQL, MySQL and SQL Server provide it. Oracle does not. Each system also has its own, richer catalog, and that is where the details live.
| Question | Standard (`information_schema`) | PostgreSQL | MySQL | Oracle | SQL Server |
|---|---|---|---|---|---|
| List views | `views` | `pg_views` | `information_schema.views` | `user_views`, `all_views` | `sys.views` |
| Get the definition | `views.view_definition` | `pg_get_viewdef()` | `SHOW CREATE VIEW` | `text` column of `user_views` | `sys.sql_modules`, `OBJECT_DEFINITION()` |
| List materialized views | not covered | `pg_matviews` | none | `all_mviews` | indexed views, see below |
Prefer information_schema for scripts that must run on several systems. Use the vendor catalog when you need exact definitions, materialized views, or dependency details.
Listing views with information_schema
The views catalog view has one row per view. These columns are the useful ones:
table_schemaandtable_name: where the view lives and what it is called.view_definition: the text of the defining query.check_option: whetherWITH CHECK OPTIONis in effect (NONE,LOCALorCASCADED).is_updatableandis_insertable_into: whether the system treats the view as writable.
SELECT table_name, check_option, is_updatable, is_insertable_into
FROM information_schema.views
WHERE table_schema = 'public'
ORDER BY table_name;With the views from earlier chapters, PostgreSQL returns something like this:
| table_name | check_option | is_updatable | is_insertable_into |
|---|---|---|---|
| active_employees | CASCADED | YES | YES |
| employee_directory | NONE | NO | NO |
| employee_summary | NONE | YES | YES |
employee_directory is not updatable because it joins two tables. This is the check you would run before you tell someone "just insert through the view". It answers the question from the chapter on updatable views without trying a write.
The 'public' schema name is PostgreSQL's default. In MySQL a schema is a database, so filter with table_schema = DATABASE(). In SQL Server the default schema is usually dbo.
Reading the definition
SELECT view_definition
FROM information_schema.views
WHERE table_schema = 'public'
AND table_name = 'employee_directory';The text is not the SQL you typed. The database stores a parsed form of your query and prints it back. In PostgreSQL the result looks like this:
SELECT e.id,
e.name,
d.name AS department
FROM (employees e
JOIN departments d ON ((d.id = e.department_id)));Your comments, spacing and some syntax choices are gone, and the output may have extra parentheses. If your view used SELECT *, the output shows the column list that was expanded when the view was created. The next sections return to this.
Vendor catalogs
PostgreSQL
pg_views lists views with their owner and definition. It does not include materialized views. Those are in pg_matviews.
SELECT schemaname, viewname, viewowner
FROM pg_views
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, viewname;
SELECT schemaname, matviewname, ispopulated, hasindexes
FROM pg_matviews;The ispopulated column matters for materialized views. A view created with WITH NO DATA exists but cannot be queried until its first refresh.
To get one definition as formatted text, call pg_get_viewdef. It works for both regular and materialized views. Passing true as the second argument asks for pretty-printed output.
SELECT pg_get_viewdef('employee_directory'::regclass, true);In psql, the shortcuts \dv (list views), \dm (list materialized views) and \d+ employee_directory (columns and definition) run catalog queries for you.
MySQL
MySQL puts the definition in information_schema.views, and it has a statement that returns something you can re-run.
SHOW FULL TABLES WHERE table_type = 'VIEW';
SHOW CREATE VIEW employee_directory;SHOW CREATE VIEW returns a complete CREATE VIEW statement. That makes it the easiest way to copy a view to another database. MySQL has no materialized views.
Oracle
Oracle has three layers of the same catalog view. USER_VIEWS shows what you own. ALL_VIEWS shows what you can access. DBA_VIEWS shows everything and needs elevated privileges.
SELECT view_name, text
FROM user_views
ORDER BY view_name;Materialized views appear in ALL_MVIEWS, including their last refresh time.
SQL Server
SELECT s.name AS schema_name, v.name AS view_name, m.definition
FROM sys.views v
JOIN sys.schemas s ON s.schema_id = v.schema_id
JOIN sys.sql_modules m ON m.object_id = v.object_id;Unlike the other systems, SQL Server keeps the original text, including your formatting and comments. information_schema.views in SQL Server truncates view_definition to 4000 characters, so use sys.sql_modules for long definitions. Views can also be created WITH ENCRYPTION, in which case the definition is not returned.
Finding dependencies
Before you change a table, you want to know which views read from it. The standard catalog has two views for this:
information_schema.view_table_usagelists the tables a view reads from.information_schema.view_column_usagelists the individual columns.
SELECT view_name, table_name
FROM information_schema.view_table_usage
WHERE view_schema = 'public'
ORDER BY view_name, table_name;Both have a limit in PostgreSQL. They only show objects owned by a role you currently hold, so they can look incomplete when you query as a non-owner. They also do not cover materialized views.
PostgreSQL's own catalog is more reliable. It records a view's dependencies as rows in pg_depend, attached to the view's rewrite rule in pg_rewrite.
SELECT DISTINCT
v.relname AS view_name,
t.relname AS depends_on
FROM pg_depend d
JOIN pg_rewrite r ON r.oid = d.objid
JOIN pg_class v ON v.oid = r.ev_class
JOIN pg_class t ON t.oid = d.refobjid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE d.classid = 'pg_rewrite'::regclass
AND d.refclassid = 'pg_class'::regclass
AND v.oid <> t.oid
AND n.nspname = 'public'
ORDER BY view_name, depends_on;This query also finds views built on other views, and materialized views. That makes it suitable for tracing nested views, where a change to one base table can affect a chain of views. Oracle offers ALL_DEPENDENCIES. SQL Server offers sys.sql_expression_dependencies.
Gotchas
You only see what you may see
Catalog views filter by privilege. In PostgreSQL, information_schema.views shows a view only if you own it or hold some privilege on it, and view_definition is empty unless you are the owner or hold a role that owns it. A "missing" view or a blank definition is often a permissions issue, not a bug. The vendor catalogs such as pg_views show every view and its definition to any user.
The stored definition is a snapshot of the columns
A view that uses SELECT * has its column list fixed when the view is created. If you later add a column to the base table, the view does not gain it. Compare information_schema.columns for the view with the base table to spot this drift. Recreate the view with CREATE OR REPLACE VIEW to refresh it. Listing columns explicitly avoids the problem.
Views are mixed in with tables
information_schema.tables lists views as well, with table_type = 'VIEW'. Filter on that column when you want only base tables:
SELECT table_name, table_type
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_type, table_name;Materialized views are easy to miss
Because materialized views store data, PostgreSQL does not treat them as views in information_schema. A script that audits views through information_schema.views alone will skip them. Query pg_matviews as well.
Catalog structure changes between versions
information_schema is stable. Vendor catalogs such as pg_class can change between major versions. Keep catalog queries in version control and test them after upgrades.
Exercises
Exercise
You run SELECT viewdefinition FROM informationschema.views for a view you do not own, and the column is NULL in PostgreSQL. What are two ways to get the definition?
Show answer
The NULL is caused by privilege filtering: viewdefinition is only shown to the owner or a member of the owning role. You can ask the owner (or a superuser) to run the query, or use pggetviewdef('schema.view'::regclass, true) or the definition column of pgviews, which are not filtered this way.
Exercise
Write a query that lists every view in the public schema of PostgreSQL that has WITH CHECK OPTION set, with its check option type.
Show answer
SELECT tablename, checkoption FROM informationschema.views WHERE tableschema = 'public' AND checkoption <> 'NONE' ORDER BY tablename;
Exercise
A script counts views with SELECT count(*) FROM informationschema.views WHERE tableschema = 'public' and reports 3, yet departmentsalarytotals also exists. Why is it not counted, and where should the script look?
Show answer
departmentsalarytotals is a materialized view, and PostgreSQL does not list materialized views in informationschema.views. The script should also query pgmatviews, for example SELECT matviewname FROM pg_matviews WHERE schemaname = 'public';