I’m using postgres, and I have a “users” table which contains users first and last names:
id | first_name | last_name | ...
-----------------------------------
1 | daniel | johnston |
2 | jane | austin |
I’d like to use a select a set of users based on a single string (matching to the beginning of both first_name and last_name. So if I search for “j”, both records will be returned. If I search for “jo”, only the the first record will be returned.
Is there an efficient way to do this query in postgres using only SQL? Or will I have to do several select calls and then format the results afterwards using another programming language?
Thanks!
Why not just use the
ORoperator.e.g.
If either first_name or last_name start with ‘jo’ then the row will be returned.
As far as efficiency goes, this type of ‘starts with’ query can leverage an index however depending on how you are going to query, you may be better off with a full text index – especially if you are going to use the wildcard on both sides of the string (e.g. LIKE ‘%jo%’.) More info can be found here: http://wiki.postgresql.org/wiki/Full_Text_Indexing_with_PostgreSQL