List columns of a table from system catalogs
INFORMATION_SCHEMA is fine for portable work, but the native catalogs expose extra detail such as identity flags, computed columns and collation. This recipe lists one table's columns from the engine's native views.
The task
The portable views give you names, types and nullability but stop there; when the answer depends on whether a column is an identity or a computed column, you have to ask the native catalogs.
The snippet
Written for SQL Server. Versions for PostgreSQL and MySQL are under Variations.
SELECT c.name AS column_name,
t.name AS data_type,
c.max_length, c.precision, c.scale,
c.is_nullable, c.is_identity, c.is_computed
FROM sys.columns c
JOIN sys.types t ON t.user_type_id = c.user_type_id
WHERE c.object_id = OBJECT_ID('dbo.Orders')
ORDER BY c.column_id;
工作原理
sys.columns carries one row per column of a table-valued object, with column_id giving declaration order. max_length is in bytes, so nvarchar(50) shows 100 and any (max) type shows -1. Joining sys.types on user_type_id returns the declared type name, which is the alias type's own name for a user-defined type; join on system_type_id as well if you need the underlying base type.
Variations
PostgreSQL
PostgreSQLSELECT a.attname AS column_name,
format_type(a.atttypid, a.atttypmod) AS data_type,
NOT a.attnotnull AS is_nullable,
pg_get_expr(ad.adbin, ad.adrelid) AS column_default
FROM pg_attribute a
JOIN pg_class c ON c.oid = a.attrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
WHERE c.relname = 'orders' AND n.nspname = 'public'
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum;
MySQL
MySQLSHOW COLUMNS FROM orders;
Questions that come up
Why do I see dropped columns in the pg_attribute version?
Postgres implements DROP COLUMN by marking the pg_attribute row attisdropped instead of rewriting the table, so the row stays and attnum values of the other columns do not shift. The NOT a.attisdropped filter hides those rows. The space is only reclaimed when the table is rewritten, for example by VACUUM FULL.
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.