Using the IN Operator


Using the IN Operator

Parentheses have another very different use in WHERE clauses. The IN operator is used to specify a range of conditions, any of which can be matched. IN takes a comma-delimited list of valid values, all enclosed within parentheses. The following example demonstrates this:

Input

SELECT prod_name, prod_price FROM products WHERE vend_id IN (1002,1003) ORDER BY prod_name;

Output

+----------------+------------+ | prod_name      | prod_price | +----------------+------------+ | Bird seed      |      10.00 | | Carrots        |       2.50 | | Detonator      |      13.00 | | Fuses          |       3.42 | | Oil can        |       8.99 | | Safe           |      50.00 | | Sling          |       4.49 | | TNT (1 stick)  |       2.50 | | TNT (5 sticks) |      10.00 | +----------------+------------+

Analysis

The SELECT statement retrieves all products made by vendor 1002 and vendor 1003. The IN operator is followed by a comma-delimited list of valid values, and the entire list must be enclosed within parentheses.

If you are thinking that the IN operator accomplishes the same goal as OR, you are right. The following SQL statement accomplishes the exact same thing as the previous example:

Input

SELECT prod_name, prod_price FROM products WHERE vend_id  = 1002 OR vend_id = 1003 ORDER BY prod_name;

Output

+----------------+------------+ | prod_name      | prod_price | +----------------+------------+ | Bird seed      |      10.00 | | Carrots        |       2.50 | | Detonator      |      13.00 | | Fuses          |       3.42 | | Oil can        |       8.99 | | Safe           |      50.00 | | Sling          |       4.49 | | TNT (1 stick)  |       2.50 | | TNT (5 sticks) |      10.00 | +----------------+------------+

Why use the IN operator? The advantages are

  • When you are working with long lists of valid options, the IN operator syntax is far cleaner and easier to read.

  • The order of evaluation is easier to manage when IN is used (as there are fewer operators used).

  • IN operators almost always execute more quickly than lists of OR operators.

  • The biggest advantage of IN is that the IN operator can contain another SELECT statement, enabling you to build highly dynamic WHERE clauses. You'll look at this in detail in Chapter 14, "Working with Subqueries."

New Term

IN A keyword used in a WHERE clause to specify a list of values to be matched using an OR comparison.





MySQL Crash Course
MySQL Crash Course
ISBN: 0672327120
EAN: 2147483647
Year: 2004
Pages: 214
Authors: Ben Forta

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net