Search code examples
sql-serverregext-sql

Check if starting characters of a string are alphabetical in T-SQL


Is it possible, just using TSQL, to check if the first two characters of a varchar field are alphabetical?

I need to select from my_table only the rows having my_field beginning with two alphabetical chars. How can I achieve this?

Is it possible to use a regex?


Solution

  • You don't need to use regex, LIKE is sufficient:

    WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
    

    Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

    Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.