Using SUB queries

A subquery is a SELECT statement within another statement. Suppose you want to find the name of the employees who started as a Senior Engineer on 1986-06-26. You can get the emp_no from the titles table, and name from the employees table. You can also use JOIN to find out the results.

To get the emp_no from titles:

mysql> SELECT emp_no FROM titles WHERE title="Senior Engineer" AND from_date="1986-06-26";+--------+| emp_no |+--------+|  10001 ||  84305 || 228917 || 426700 || 458304 |+--------+5 rows in set (0.14 sec)

To find the name:

mysql> SELECT first_name, last_name FROM employees WHERE emp_no IN (< output from preceding query>)mysql> SELECT first_name, last_name FROM employees WHERE emp_no IN (10001,84305,228917,426700,458304); ...

Get MySQL 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.