SQL: Selecting Specifying Multiple Field Values

Here are 3 different ways to perform a DB select when you want to specify two or more values for a field.

1. Use th OR operator

SQL:
  1. SELECT * FROM people
  2. WHERE (first_name = 'pete'
  3. OR first_name = 'paul');

2. Use a Regular Expression

SQL:
  1. SELECT * FROM people
  2. WHERE first_name ~'^pete|paul$';

3. Use an array

SQL:
  1. SELECT * FROM people
  2. WHERE first_name = ANY('{pete,paul}');

Note: These should all work in PostgreSQL, I suspect the SQL may need altering for 2 and 3 to work with MySQL.

# Pete Graham

Comments 1

  1. Naggy wrote:

    Mhh nice.

    But why not use the IN Statemant?

    SELECT * FROM people
    WHERE first_name IN (’pete’, ‘paul’);

    You can also use Subquerys with the IN Statement.

    Posted 01 Feb 2009 at 12:34 pm

Post a Comment

Your email is never published nor shared. Required fields are marked *