// SQL snippet

Find columns by data type

Planning a type migration starts with a census: which columns are varchar(50), which are float, which still use money. This query lists every column of a given type and length.

Main statement
PostgreSQL
还支持
SQL Server MySQL

The task

A type is being retired or widened, and before touching anything you need the complete inventory of columns declared with that type and length.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT table_schema, table_name, column_name,
       data_type, character_maximum_length
FROM information_schema.columns
WHERE table_schema = 'public'
  AND data_type = 'character varying'
  AND character_maximum_length = 50
ORDER BY table_name, column_name;

工作原理

information_schema.columns exposes type plus the length and precision attributes, so filtering on both finds exactly varchar(50)-style columns. data_type for varchar reads 'character varying'; for timestamp-with-time-zone it reads 'timestamp with time zone', so match the full spelled-out type. Drop the length filter to see every column of the type.

Variations

SQL Server

SQL Server
SELECT SCHEMA_NAME(tb.schema_id) AS schema_name,
       tb.name AS table_name,
       c.name AS column_name,
       t.name AS type_name, c.max_length
FROM sys.columns c
JOIN sys.tables tb ON tb.object_id = c.object_id
JOIN sys.types t ON t.user_type_id = c.user_type_id
WHERE t.name = 'varchar' AND c.max_length = 50
ORDER BY schema_name, table_name;

MySQL

MySQL
SELECT table_name, column_name, column_type
FROM information_schema.columns
WHERE table_schema = 'mydb' AND column_type = 'varchar(50)'
ORDER BY table_name;

Questions that come up

Why does max_length look doubled for nvarchar on SQL Server?

sys.columns.max_length is measured in bytes, and nvarchar stores UTF-16, so nvarchar(50) reports 100 and nvarchar(max) reports -1. Adjust the comparison accordingly: max_length = 100 for nvarchar(50).

Keep reading

// snippets are better with a schema brain

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.