Describe a table: columns, types and defaults
Every engine has a DESCRIBE-style shortcut, but a plain query is scriptable and gives you the same information in a form you can filter or diff.
The task
You are about to write against a table whose exact column names and types you do not have memorized, or you need to compare one table's shape between two environments.
The snippet
Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.
SELECT column_name, data_type, is_nullable, column_default,
character_maximum_length, numeric_precision, numeric_scale
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'users'
ORDER BY ordinal_position;
它的運作方式
information_schema.columns is the SQL-standard metadata view, so this query shape works on PostgreSQL, MySQL and SQL Server with almost no changes. ordinal_position preserves the column order you declared. character_maximum_length and the numeric precision columns are NULL for types where they do not apply.
Variations
MySQL
MySQLDESCRIBE users;
-- or with more detail:
SHOW FULL COLUMNS FROM users;
SQL Server
SQL ServerEXEC sp_help 'dbo.Users';
-- or just the columns:
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Users'
ORDER BY ORDINAL_POSITION;
SQLite
SQLitePRAGMA table_info(users);
-- with generated/hidden columns included:
PRAGMA table_xinfo(users);
Questions that come up
How do I get the full type with length, like varchar(50)?
Combine data_type with character_maximum_length when it is not NULL, or numeric_precision and numeric_scale for numeric. PostgreSQL can print the declared form directly with format_type(atttypid, atttypmod) from pg_attribute, MySQL has it ready in information_schema.columns.column_type, and SQLite's PRAGMA table_info returns the type exactly as written in CREATE TABLE.
Keep reading
Related on SQLly
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.