← Back to SQL, page 8

sql-0151 · Medium mid

Write a query that finds phone values made up only of digits.

In SQLite use GLOB with a negated character class: phone NOT GLOB '*[^0-9]*' AND phone <> ''. In PostgreSQL use a regular expression: phone ~ '^[0-9]+$'. LIKE cannot express character classes, so it is the wrong tool here.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id, phone FROM contacts
WHERE phone NOT GLOB '*[^0-9]*' AND phone <> ''
ORDER BY id;
idphone
412345

GLOB '*[^0-9]*' matches any string that contains at least one non-digit. NOT GLOB therefore keeps strings with only digits. The empty-string check is needed because an empty string contains no non-digit either. GLOB is case-sensitive and uses * and ? instead of % and _.

PostgreSQL:

sql
SELECT id, phone FROM contacts WHERE phone ~ '^[0-9]+$' ORDER BY id;
idphone
412345

Only 12345 qualifies; the others contain spaces, brackets, dashes or +. For validating new data, a CHECK constraint with the same expression rejects bad values at insert time.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id, phone FROM contacts
WHERE phone NOT GLOB '*[^0-9]*' AND phone <> ''
ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • SQLite GLOB supports character classes like [0-9]
  • NOT GLOB '*[^0-9]*' means only digits
  • PostgreSQL uses ~ with a regular expression
  • Guard against empty strings

Common mistakes

  • Trying to express character classes with LIKE
  • Forgetting that an empty string passes the negated test

Follow-ups

  • How would you enforce this with a CHECK constraint?
  • How would you find emails without exactly one '@'?

Tips

  • Explain the double negative in the GLOB pattern