0

I want to search for rows whose column email has only the X character.

For example, if the email is XXXX, it should fetch the row but if the email is XXX@XXX.COM it should not be fetched.

I have tried something like this, but it is returning me all emails having the character X in it:

select *
from STUDENTS
where EMAIL like '%[X+]%';

Any idea what is wrong with my query?

Thanks

Rarblack
  • 4,559
  • 4
  • 22
  • 33
refresh
  • 1,319
  • 2
  • 20
  • 71

3 Answers3

1

Try below query:

select *
from STUDENTS
where LEN(EMAIL) > 0 AND LEN(REPLACE(EMAIL,'X','')) = 0;
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Cato
  • 3,652
  • 9
  • 12
1

I would use PATINDEX:

SELECT * FROM STUDENTS WHERE PATINDEX('%[^X]%', Email)=0

Only X means no other characters than X.

To handle NULLs and empty strings you should consider additional conditions. See demo below:

WITH STUDENTS AS
(
    SELECT * FROM (VALUES ('XXXX'),('XXX@XXX.COM'),(NULL),('')) T(Email)
)
SELECT *
FROM STUDENTS
WHERE PATINDEX('%[^X]%', Email)=0 AND LEN(Email)>0
Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
0

This will find all rows where email only contain 1 or more X and no other characters.

SELECT *
FROM STUDENTS
WHERE Email not like '%[^X]%' and Email <> ''
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92