A sub query is a select statement , which is embedded in the clause of another select statement. In that case the sub-query is called the inner query and the SQL statement in which the inner query is attached with is called the parent query or main query.
Suppose you want to find out those employees names who have joined after Ramesh? then what will you do ? the solution is:
Select select_list
From table
Where expr operator
( select select_list From table ) ;
In the above syntax:
Operator includes a comparison operator such as > , = or IN.
The sub-query executes once before the main query. The result of the sub-query is used by the main query.
Sub-query is of two types.
Comparison operator is of two types:
Select emp_name
From emp
Where hire_date > ( select hire_date from emp
Where emp_name =" Ramesh" ) ;
In the above example first the inner query will get execute, which will return the hire_date of Ramesh. Then the hire_date of Ramesh will be used by the where clause of the main query to display the name of the employees whose hire_date is after the hire_date of Ramesh.
Suppose you want to display the department id and minimum salary grouped by department id where the minimum salary of each group should be more than the minimum salary of the department 50.
Select dept_id, min (emp_salary )
From emp
Group by dept_id
Having min (emp_salary ) > ( select min ( emp_salary)
From emp
Where dept_id =50 ) ;
In the above example you saw how to use group function in a sub-query and using the sub-query with the having clause.
Note:- use single-row operator with single row sub-queries and use multiple row operator with multiple row sub-queries.
The IN operator equal to any value returned by the sub-query.
Suppose you want to display all the employees name who gets the salary as the minimum salary of each department.
Select emp_id, emp_name
From emp
Where emp_salary IN ( select min (emp_salary)
From emp
Group by dept_id ) ;
Select emp_id, emp_name
From emp
Where emp_salary IN ( select min (emp_salary)
From emp
Group by dept_id ) ;
In the above example it will display employees id, employees name, employees salary of those employees who are not IT programmers and whose salary is < ANY IT programmer.
The ALL operator compares a value two every value returned by a sub-query.
Select emp_id, emp_name, emp_salary
From emp
Where emp_salary < ALL ( select emp_salary from emp
Where job_id =IT_PROG)
AND
Job_Id >> IT_PROG ;
Inj the above example it will display employees id, employees name , employees salary of those employees who are not IT programmers and whose salary is < ALL IT programmer
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc