Sub-query syntax
SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);
- The subquery (inner query) is performed once before the main query.
- Results of the subquery by the main query (outer query) used.
Example:
SELECT last_name FROM employees WHERE salary > ( SELECT salary FROM employees WHERE last_name = 'Abel' );
Precautions
- Subquery to be included in parentheses.
- The subquery on the right side of the comparison condition.
- Corresponding to one-line single-row subquery operators, operators corresponding to a plurality of rows multiple rows subqueries.
Subqueries type
single-row subquery
- Returns only one row.
- Using single row comparison operators.
Example:
- Job_id returned with the same number of 141 employees, salary of employees and more than 143 employee name, job_id and wages
SELECT last_name, job_id, salary FROM employees WHERE job_id = ( SELECT job_id FROM employees WHERE employee_id = 141 ) AND salary > ( SELECT salary FROM employees WHERE employee_id = 143 );
The use of group functions in a subquery
- Returns the minimum wage of employees of the company last_name, job_id, and salary
SELECT last_name, job_id, salary FROM employees WHERE salary = ( SELECT MIN(salary) FROM employees );
HAVING clause subquery
- First, the implementation of sub-queries.
- Return results to the main query in the HAVING clause.
- Topic: Query No. 50 is greater than the minimum wage sector minimum wage and the minimum wage department id
SELECT department_id, MIN(salary) FROM employees GROUP BY department_id HAVING MIN(salary) > ( SELECT MIN(salary) FROM employees WHERE department_id = 50 );
Illegal use subqueries
Null sub-query problem
SELECT last_name, job_id FROM employees WHERE job_id = ( SELECT job_id FROM employees WHERE last_name = 'Haas' );
Multiple-row subqueries
- Return multiple rows.
- Using multiple-row comparison operators.
ANY operator using the multi-row subqueries
Example: the return of any member of the other departments of a low-wage employees as 'IT_PROG' department than job_id
Job number, name, job_id, and salary
SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary < ANY ( SELECT salary FROM employees WHERE job_id = 'IT_PROG' ) AND job_id <> 'IT_PROG';
Use ALL operators in a multi-line subquery
example: Return to other sectors than job_id 'IT_PROG' department employees all wages are low
employee number, name, salary and job_id
SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary < ALL ( SELECT salary FROM employees WHERE job_id = 'IT_PROG' ) AND job_id <> 'IT_PROG';
Null sub-query problem
SELECT emp.last_name FROM employees emp WHERE emp.employee_id NOT IN ( SELECT mgr.manager_id FROM employees mgr );