SQL - In
In is a special kind of operator for use in your where clauses. Recall that in a where expression only one value is allowed to be sent through the query. With the in operator one can send multiple values in the where clause.
SQL Code:
SELECT * FROM table_name
WHERE some_column IN('value1','value2','value3');
The rows returned will have one of the values listed (value1, value2, or value3) in brackets as the value for the specified column (column_one).
SQL - In Subqueries
To better understand the power of this function, let's use an example involving a subquery. Say we have a database with the following tables.
Employees:
| user_id | last | first |
| 0045 | Davis | Julie |
| 0067 | Smith | John |
| 0098 | Hodgensen | Bruce |
Logbook:
| user_id | timestamp |
| 0045 | 000000002345 |
| 0045 | 000000045666 |
| 0098 | 000000076444 |
Now above we have an employees table giving us a user_id along with a first and last name of employees we have working in the office. The second table might be a log type table that keeps track of who accessed the database and at what time. This a security check. A standard operating procedure if many people will be accessing the database.
What we want to know is the last name and first name of those that accessed the database. To do this we may use a subquery like in the example below.
SQL Code:
SELECT first,last FROM employees WHERE user_id IN
(Select user_id FROM logbook);
The subquery highlighted in red selects all the values of user_id in the logbook and returns those to the previous in statement. The result is a complete listing of the names of the employees that have accessed the database and have been recorded inside the logbook table. The good news is that this feat was accomplished without having to know the user_ids of every employee in the office. This definatly adds some depth to your SQL knowledge thus far.
|