// SQL snippet

Validate phone number shape

Allow an optional leading plus, digits, spaces, parentheses and hyphens, with a sane minimum length, and list the violations.

Main statement
PostgreSQL
还支持
SQL Server

The task

customers.phone is free text and holds 'n/a', extension notes, and pasted addresses. A shape test isolates the rows that need normalizing before an SMS integration goes live.

The snippet

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

PostgreSQL
SELECT id, phone
FROM customers
WHERE phone IS NOT NULL
  AND phone !~ '^\+?[0-9 ()-]{7,20}$'
ORDER BY id;

工作原理

The regex reads: optional leading plus, then 7 to 20 characters drawn from digits, space, parentheses and hyphen, and nothing else. !~ is PostgreSQL's 'does not match' operator, so the query returns the rows that fail. The window counts formatting characters too, which is why it is wider than E.164's 15-digit maximum; the digits-only variant checks the real digit count.

Variations

SQL Server: LIKE with character classes

SQL Server
SELECT id, phone
FROM customers
WHERE phone IS NOT NULL
  AND (phone NOT LIKE '%[0-9]%' OR phone LIKE '%[^0-9+() -]%');

Digits-only length after stripping separators

SELECT id, phone,
       LENGTH(REGEXP_REPLACE(phone, '[^0-9]', '', 'g')) AS digit_count
FROM customers
WHERE phone IS NOT NULL
  AND LENGTH(REGEXP_REPLACE(phone, '[^0-9]', '', 'g')) NOT BETWEEN 7 AND 15;

Questions that come up

Why not store phones as numbers?

A numeric column silently destroys leading zeros, cannot hold the + prefix, and blocks formatting characters that humans actually read. Store the raw string, validate its shape, and keep a normalized E.164 column alongside it when you need to dial or match.

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.