You are on page 1of 5

Subqueries

By Diksha Nagpal
Introduction
• A subquery is a nested query where the result of one query can be used
in another query via relational operator or Aggregation Functions.
And a subquery must be enclosed with in parentheses and contain only
one column in the Select clause if used in where clause.
An Order By Clause is not allowed in a subquery. And this can be
nested within other subqueries. Subquries are used in Where, Having, from
and in Select clauses.
Syntax

• The syntax for MySQL SubQueries is as follows:



Select <column_name1>,<column_name2> from <table_name> where
<column_name2> <condition> (select <column_name2> from
<table_name> where condition);
• table name => Any accurate table in the database.
• column name =>The column names that are inserted in the table.
• condition => Is a logic.
Examples

• mysql> select emp_id,ename,sal from employee where salary >(select salary


from employee where ename='rambo');
• +--------+-------+-------+
• | emp_id | ename |salary |
• +--------+-------+-------+
• | 1003 | kate | 14000 |
• | 1003 | jeo | 14000 |
• | 1003 | finn | 14000 |
• +--------+-------+-------+
• 3 rows in set (0.08 sec)
Examples
• mysql> select min(salary) from employee where salary=(select salary
from employee where ename='rambo');
• +--------+-------+-------+--------+-----------+
• | emp_id | ename |salary | deptno | job |
• +--------+-------+-------+--------+-----------+
• | 1002 | rambo | 13000 | 20 | salesman |
• +--------+-------+-------+--------+-----------+
• 1 rows in set (0.08 sec)

You might also like