views:

99

answers:

3

What's the best way to run a query so that spaces in the fields are ignored? For example the following queries....

SELECT * FROM mytable WHERE username = "JohnBobJones"

SELECT * FROM mytable WHERE username = "John Bob Jones"

.

would find the following entries:

John Bob Jones

JohnBob Jones

JohnBobJones

.

I am using php or python but I think this doesn't matter.

+5  A: 
SELECT * FROM mytable 
    WHERE REPLACE(username, ' ', '') = REPLACE("John Bob Jones", ' ', '')
SLaks
+1  A: 

One way would be to use LIKE and WildCards to build your query citeria. Something like:

SELECT * FROM mytable WHERE username LIKE 'John*Bob*Jones';

QB
This will incorrectly match `John Paul Bob Jones`.
SLaks
+3  A: 

It depends. If you don't care about good performance then there are lots of things you could do but most of them will be slow. Maybe that's OK for you, but I will leave this answer here in case others reading do want a fast solution.

If you want very fast performance you should index the string without spaces in the database. In PostgreSQL you can create an index on a function. You can use this to create an index on the column with spaces replaced with the empty string. The advantage of this method is that it requires no maintenance apart from creating the index.

In MySQL you cannot do this so the simplest way would be to duplicate the data in the database - once with spaces and once without. Use the column without spaces in your WHERE clause, but the original column in your SELECT column list. This requires more maintenance as the columns must be kept in sync. You can do this with application logic or database triggers.

Mark Byers