PostgreSQL – How to List Tables Used by A View
To list the tables used by a view in PostgreSQL, you can query the system catalog to inspect the view’s underlying SQL query. PostgreSQL stores view definitions in the pg_views
system catalog table. Here’s how you can retrieve the tables used by a specific view:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name IN ( SELECT regexp_replace(regexp_replace(view_definition, E'^.*\\bFROM\\s+', ''), '\\s.*$', '', 'g') AS table_name
FROM pg_views
WHERE viewname = 'your_view_name' );
Replace 'public'
with the schema where your view is located. Replace 'your_view_name'
with the name of the view you want to examine.
This query retrieves the names of tables used by the specified view by parsing the view definition and extracting table names from the FROM
clause of the SQL query that defines the view. It then checks if those tables exist in the specified schema.