Tuesday, July 15, 2014

SubQuery in MySQL

A subquery is a query inside another query or it is a nested query which is embedded within the WHERE clause.

Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.

A subquery must be enclosed within parentheses. It can have only one column in the SELECT clause unless multiple columns are in the main query for the subquery to compare its selected columns.

For example:

We have two tables as below:

1)tbl_employees
eid name address email mobile
1 Ryan Ktm ryan@gmail.com 9874512663
2 Sunaina Lagankhel s@gmail.com 98745256325
3 Preeti Budhanagar p@gmail.com 987412321

2) tbl_salaries
sid eid salary
1 1 20000
2 2 10000
3 3 15000


Now you want to know names of those employees who earn more than 12000

So you need to use SQL as below:

SELECT * FROM tbl_employees WHERE eid in (SELECT eid FROM tbl_salaries WHERE salary > 12000)

No comments:

Post a Comment