1

I am in the process of converting some t-sql queries to postgres and I am having trouble wrapping my head around the postgres wildcard logic.

eg:

The following query in tsql will yeild 'A' however in postgres it returns 'B'

    Select 
    case when 'abcd 1234' like '%[a-z]%[0-9]%' then 'A' else 'B' end as Q1

What would be the postgres equivalent to the above case when statement? Furthermore, does anyone have a general rule of thumb for converting tsql string logic to postgres ?

Thanks in advance!

1

1 Answer 1

3

The difference that you're running into here is that SQL Server's TSQL accepts character range wildcards through the square bracket [] syntax but PostgreSQL does not.

Instead, PostgreSQL incorporates support for POSIX regular expressions within a query using the RegEx match operators - variations of ~ - in place of LIKE and offer quite a bit of flexibility with respect to case sensitivity and string-matching.

Restating your original query in a POSIX RegEx syntax to achieve an output of 'A' will resemble this:

  Select 
    case when 'abcd 1234' ~ '(.*)[a-z](.*)[0-9](.*)' then 'A' 
    else 'B' end as Q1

As for the notion of general heuristics for handling these sorts of conversions, I would suggest that T-SQL character-set wildcards should be implemented as POSIX regular expressions using the RegEx match operator rather than LIKE. Otherwise, the T-SQL % and _ wildcards behave equivalently to the same PostgreSQL wildcards.

References:

Sign up to request clarification or add additional context in comments.

2 Comments

Just as a side note: the SQL standard only defines the wildcards % and _ for the LIKE operator and nothing else. This is not specific to Postgres. SQL Server's support for "regex like" wildcards in T-SQL is non-standard
@a_horse_with_no_name That's an important note! Thank you for that and the edit for the current doc URL (I wasn't watching closely)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.