Here are three examples of returning rows that contain alphanumeric characters in SQL Server.
Alphanumeric characters are alphabetic and numeric characters.
Sample Data
Suppose we have the following table:
CREATE TABLE t1 (
c1 varchar(255) NULL
);
INSERT INTO t1 VALUES
('Music'),
('Live Music'),
('Café'),
('Café Del Mar'),
('100 Cafés'),
('[email protected]'),
('1 + 1'),
('()'),
('!@#&()–[{}]:;'',?/*'),
('`~$^+=<>“'),
('$1.50'),
('Player 456'),
('007'),
(null),
(''),
('é'),
('É'),
('é 123'),
('ø'),
('ø 123');
SELECT c1 FROM t1;
Result:
+----------------------+ | c1 | +----------------------+ | Music | | Live Music | | Café | | Café Del Mar | | 100 Cafés | | [email protected] | | 1 + 1 | | () | | !@#&()–[{}]:;',?/* | | `~$^+=<>“ | | $1.50 | | Player 456 | | 007 | | NULL | | | | é | | É | | é 123 | | ø | | ø 123 | +----------------------+
Example 1: Row Contains Alphanumeric Data
The following code returns rows that contain alphanumeric characters (and may also contain non-alphanumeric characters):
SELECT c1 FROM t1
WHERE c1 LIKE '%[a-zA-Z0-9]%';
Result:
+-------------------+ | c1 | |-------------------| | Music | | Live Music | | Café | | Café Del Mar | | 100 Cafés | | [email protected] | | 1 + 1 | | $1.50 | | Player 456 | | 007 | | é | | É | | é 123 | | ø | | ø 123 | +-------------------+
Example 2: Row Contains ONLY Alphanumeric Data
The following code returns rows that only contain alphanumeric characters:
SELECT c1 FROM t1
WHERE c1 NOT LIKE '%[^a-zA-Z0-9]%'
AND c1 LIKE '%[a-zA-Z0-9]%';
Result:
+-------+ | c1 | |-------| | Music | | Café | | 007 | | é | | É | | ø | +-------+
Spaces are considered non-alphanumeric. We can include spaces by adjusting the code to the following:
SELECT c1 FROM t1
WHERE c1 NOT LIKE '%[^a-zA-Z0-9 ]%'
AND c1 LIKE '%[a-zA-Z0-9 ]%';
Result:
+--------------+ | c1 | |--------------| | Music | | Live Music | | Café | | Café Del Mar | | 100 Cafés | | Player 456 | | 007 | | é | | É | | é 123 | | ø | | ø 123 | +--------------+
Example 3: An Alternative Method
We can alternatively use the PATINDEX()
function to achieve the same result.
The following code returns rows that only contain alphanumeric characters:
SELECT c1 FROM t1
WHERE PATINDEX('%[^0-9a-zA-Z]%', c1) = 0
AND PATINDEX('%[a-zA-Z0-9]%', c1) > 0;
Result:
+-------+ | c1 | |-------| | Music | | Café | | 007 | | é | | É | | ø | +-------+
And with spaces:
SELECT c1 FROM t1
WHERE PATINDEX('%[^0-9a-zA-Z ]%', c1) = 0
AND PATINDEX('%[a-zA-Z0-9 ]%', c1) > 0;
Result:
+--------------+ | c1 | |--------------| | Music | | Live Music | | Café | | Café Del Mar | | 100 Cafés | | Player 456 | | 007 | | é | | É | | é 123 | | ø | | ø 123 | +--------------+