Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Simplify SQL “where” conditions with the “in” statement

Thursday, November 22nd, 2012 by Servage

When you select some thing with SQL and accept any record where a given parameter has one of multiple values, you often see long where conditions like the following:

Simple example

SELECT * FROM `table` WHERE `id` = "2" OR `id` = "4" OR `id` = "6";

This is based around the regular “where” conditions, where you can append multiple rules with AND/OR – plus even group the with parenthesis, thus creating very complex and long where conditions.

This process can be simplified a bit by using the “in” statement. It is used to indicate that the statement is fulfilled if a field has any of a set of following values. Consider the example from above using the “in” statement:

Simple example – using the “in” statement

SELECT * FROM `table` WHERE `id` IN ("2", "4", "6");

MySQL offers many nice features like this, to simplify and optimize your queries. A look at the documentation is always worth the effort.

 

Simplify SQL "where" conditions with the "in" statement, 4.0 out of 5 based on 3 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.