I am writing a flexible search mechanism for a customer\'s website. I am utilizing union clauses to query a number of different fields in the database in search of a string
How about replacing:
SELECT * FROM test_table WHERE phone = 'email@example.com'
with:
SELECT * FROM test_table WHERE phone = 'email@example.com' and phone <> 0
<> means different from.
This will work for you because you are using 0 in the phone column to mean there isn't a phone number (although it would be better style to use NULL for no phone number).
This query should fail:
SELECT * FROM test_table WHERE cast(phone as char) = 'email@example.com';
The cause of the original problem is that when comparing strings and numbers, it converts the string to a number (so you can write where phone = '123'
). You need to use an explicit cast of the field to make it a string-to-string comparison, to prevent this default conversion.
Unfortunately, casting like this is likely to prevent it from using indexes. Even if the field is already char
, the cast apparently prevents it from indexing.
You could also solve it during input validation: if phone
is an integer, don't allow the user to provide a non-integer value in the search field.