SQL

SQL Subquery select statement with example

A Subquery is a select query that is enclosed inside another query. The inner select query is usually used to determine the results of the outer select query.

Example:

Write a query to display the name with the highest salary from the employees table.

Write a query to display name, age, address and salary of employees with salary less than the average from the employees table.

Input Employees Table:

Use the following code to enter data:

create table Employees (Name VARCHAR(25), Age int,
sex CHAR(1), address varchar(15), salary float);

insert into Employees
values(“Mohamed”, 35, “M”, “Sousse”, 150000),
(“Ali”, 35, “M”, “Sousse”, 155000),
(“Chaima”, 22, “F”, “Sousse”, 62000),
(“Hasna”, 21, “F”, “Tunis”, 57000),
(“Wala”, 25, “F”, “Alger”, 72000),
(“Oumaima”, 26, “F”, “Annaba”, 80000);

Question 1: 

Write a query to display name with the highest salary from the employees table.

select name from employees where salary=(select Max(salary) from employees);

Output:

Question 2:

Write a query to display name, age, address and salary of employees with salary less than the average from the employees table.

select name, age, address, salary from employees where salary<(select avg(salary) from employees);

Read also:

SQL inner Join full explanation with example

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button