Return Rows that Contain Only Non-Alphanumeric Characters in SQL

Here are examples of using SQL to return rows that contain non-alphanumeric characters in various DBMSs.

Non-alphanumeric characters include punctuation characters like !@#&()–[{}]:;',?/* and symbols like `~$^+=<>“, as well as whitespace characters like the space or tab characters.

SQL Server

In SQL Server, we can use NOT LIKE with a list of alphanumeric characters that we want to exclude from the result:

SELECT c1 FROM t1
WHERE c1 NOT LIKE '%[a-zA-Z0-9]%';

That returns rows that only contain non-alphanumeric characters.

To return rows that contain non-alphanumeric characters, but may also contain alphanumeric characters, we can do this:

SELECT c1 FROM t1
WHERE c1 LIKE '%[^a-zA-Z0-9]%';

Oracle

In Oracle Database we can use the REGEXP_LIKE() function to compare the value to a regular expression, then negate it with the NOT operator.

Oracle’s regular expression capability includes support for the POSIX character classes. Therefore, we can use the [:alnum:] POSIX character class in our regular expressions to find the rows that contain non-alphanumeric characters.

SELECT c1 FROM t1 
WHERE NOT REGEXP_LIKE(c1, '[[:alnum:]]');

If you have more specific range, then you can provide that range instead of the character class.

MySQL

Like Oracle Database, MySQL also supports the POSIX character classes. We can use MySQL’s REGEXP_LIKE() function or one of its equivalent operators, such as REGEXP or RLIKE.

SELECT c1 FROM t1 
WHERE c1 NOT REGEXP '[[:alnum:]]';

If you need to exclude a specific character, you can always use the NULLIF() function.

The following example excludes any rows that only contain the empty string:

SELECT c1 FROM t1
WHERE NULLIF(c1, '') NOT REGEXP '[[:alnum:]]';

MariaDB

In MariaDB, we can do the same as with MySQL:

SELECT c1 FROM t1 
WHERE c1 NOT REGEXP '[[:alnum:]]';

And to exclude rows that contain only the empty string:

SELECT c1 FROM t1
WHERE NULLIF(c1, '') NOT REGEXP '[[:alnum:]]';

PostgreSQL

PostgreSQL also supports POSIX character classes, but in Postgres, we use the !~ operator instead:

SELECT c1 FROM t1 
WHERE c1 !~ '[[:alnum:]]';

We can exclude empty strings by using NULLIF():

SELECT c1 FROM t1 
WHERE NULLIF(c1, '') !~ '[[:alnum:]]';

SQLite

In SQLite, we can provide a range of characters to exclude. SQLite has a REGEXP operator, so we can negate that with the NOT operator.

SELECT c1 FROM t1
WHERE c1 NOT REGEXP '[A-Za-z0-9]';

For unicode characters, you’ll need to include those in the range.

For example:

SELECT c1 FROM t1
WHERE c1 NOT REGEXP '[A-Za-zÀ-Þß-ÿ0-9]';

And we can use SQLite’s NULLIF() function to exclude the empty string from the output:

SELECT c1 FROM t1
WHERE NULLIF(c1, '') NOT REGEXP '[A-Za-zÀ-Þß-ÿ0-9]';