+45 70 27 40 08

sales@meeho.net

— Archive for the ‘PostgreSQL’ category:

» Search a bunch of fields altogether in PostgreSQL with SQL LIKE using multiple words

Posted by Kasper Tidemann on Tuesday 26th of October 2010 12:06:25 AM

Say you want to execute a SELECT * FROM blah WHERE <some fields> LIKE ‘%<some words>%’. To accomplish this, you can 1) concatenate the values of the fields you wish to search and 2) use the % operator to combine the queries. Have a look at this example:

SELECT * FROM your_table WHERE (field_1 || ‘ ‘ || field_2 LIKE ‘%apples%oranges%’);

Notice how I concatenate field_1 and field_2 using the || operator (double-pipe). This is especially useful if you’ve got a table containing some users, and they’ve got a firstname and a lastname. If you want to search for “kasper tidemann” combining both the firstname and lastname in one string, do this:

SELECT * FROM users WHERE (firstname || ‘ ‘ || lastname LIKE ‘%kasper tidemann%’);

Instead of searching firstname for “kasper tidemann” and then lastname for “kasper tidemann”, you search the full name this way.

It works fine and dandy, and it’s an easy, fast way of solving a simple problem. Gotta love SQL.

1

Comment on this post

 

+45 70 27 40 08
Open office hours

info@meeho.net

support@meeho.net

News from the Meeho!™ Blog:

02/14 2011 » Fixing the "NoMethodError: undefined method ‘to_sym' for false:FalseClass" error when working with I18n in Ruby on Rails

02/03 2011 » Soon to come: IMAP integration

01/27 2011 » Meeho!™ App version 1.0.3 is out!

01/26 2011 » Cool new iPad stand

We live at Diplomvej 381, 2800 Kgs. Lyngby, Denmark: