List views and their definitions
Views accumulate quietly and hide logic nobody remembers writing. This recipe lists every view in a schema with the full SQL that defines it.
The task
A report returns numbers nobody can trace to a base table, or a column change is planned and you must know which views reference it. Read the definitions.
The snippet
Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.
SELECT schemaname, viewname, viewowner, definition
FROM pg_views
WHERE schemaname = 'public'
ORDER BY viewname;
So funktioniert es
pg_views renders each view's stored SELECT through pg_get_viewdef, so definition is the actual query text you could re-run. viewowner matters for permission debugging because a view reads its base tables with the owner's privileges unless it was created WITH (security_invoker = true), available since PostgreSQL 15. Materialized views are not in pg_views; they are listed in pg_matviews.
Variations
SQL Server
SQL ServerSELECT s.name AS schema_name, v.name AS view_name,
sm.definition
FROM sys.views v
JOIN sys.schemas s ON s.schema_id = v.schema_id
JOIN sys.sql_modules sm ON sm.object_id = v.object_id
ORDER BY v.name;
MySQL
MySQLSHOW FULL TABLES IN mydb WHERE table_type = 'VIEW';
-- then per view:
SHOW CREATE VIEW myview;
SQLite
SQLiteSELECT name, sql
FROM sqlite_master
WHERE type = 'view'
ORDER BY name;
Questions that come up
Why is the view definition cut off?
Usually the client is clipping a long column, so export the result to a file or call pg_get_viewdef('myview'::regclass, true) on its own. In SQL Server, sys.sql_modules.definition is nvarchar(max) and holds the full text; INFORMATION_SCHEMA.VIEWS.VIEW_DEFINITION stops at 4000 characters, and SSMS grid output is also truncated by default.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.