Surprising SQL String comparison with untrimmed string

I’m a bit big-headed about my SQL abilities generally, and must admit that when it came to doing straight string equality comparisons in T-SQL I thought that LIKE and = were identical (ok, I should have really read BOL). Thus which of the following would you expect to return a row and which wouldn’t?

select 'Oh yeah' where 'a' = 'a  '           -- Statement 1

select 'Oh yeah' where 'a' = RTRIM('a  ')    -- Statement 2

select 'Oh yeah' where 'a' LIKE 'a  '        -- Statement 3

select 'Oh yeah' where 'a' LIKE RTRIM('a  ') -- Statement 4

-- 

select 'Oh yeah' where 'a' = 'a'             -- Statement 5

select 'Oh yeah' where 'a' LIKE 'a'          -- Statement 6

Give it a try, I’m not going to spoil it for you…I’ve included statements 5 & 6 so that you can look at the execution plan and relative costs, I never thought that LIKE could be less expensive than =. Learn some new SQL every day…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s