MySQL Subquery Exercises: Display the employee ID, first name, last name, and department name of all employees
MySQL Subquery: Exercise-13 with Solution
Write a query to display the employee ID, first name, last name, and department names of all employees.
Sample table: employees
Sample table : departments
Code:
SELECT employee_id, first_name, last_name,
(SELECT department_name FROM departments d
WHERE e.department_id = d.department_id) department
FROM employees e ORDER BY department;
Explanation:
MySQL Subquery Syntax:
- The subquery (inner query) executes once before the main query (outer query) executes.
- The main query (outer query) use the subquery result.
MySQL Code Editor:
Structure of 'hr' database:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous:Write a query to find the name (first_name, last_name) of the employees who are not supervisors.
Next:Write a query to display the employee ID, first name, last name, salary of all employees whose salary is above average for their departments.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework