Chapetr 07 SQL SubQueries
Chapetr 07 SQL SubQueries
SubQueries
Outlines
Subqueries
SELECT Statement: Other
Clauses and Functions
Subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as
follows :-
Example:7.1
SELECT *
FROM employees WHERE ID IN (SELECT ID
FROM employees
WHERE SALARY > 450) ;
Output:
Subqueries with insert
statement
Example:7.5
DELETE FROM employees WHERE AGE IN (SELECT AGE FROM
employees1 WHERE AGE >= 27 );
Output:
SELECT Statement: Other Clauses
and Functions.
Grouping Data
SELECT ...... FROM ...... WHERE condition ;
GROUP BY groupexpr [HAVING requirement]
The GROUP BY clause is used to combine, or group, rows with related
values to element of a smaller set of rows. GROUP BY is often used in
conjunction with SQL aggregate functions
GROUP BY Clause
The GROUP BY clause defines one or more columns as a group such
that all rows within any group have the same values for those columns.
EXAMPLE 6.26 Get all jobs of the employees:
USE sample
SELECT NAME, SUM(SALARY) FROM employees
GROUP BY NAME;
SELECT Statement: Other Clauses
and Functions.
Aggregate Functions
Aggregate functions are functions that are used to get summary values.
aggregate functionsThe
functions Transact-SQL language supports six aggregate
functions:
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( ) COUNT_BIG ()
SELECT Statement: Other Clauses
and Functions.
EXAMPLE 7.6
Get the lowest employees salary:
USE sample;
SELECT MIN(salary) AS min_Salary
FROM employees;
EXAMPLE : 7.7
Get the highest employee salary:
SELECT Max(salary) AS max_Salary
FROM employees;
SELECT Statement: Other Clauses
and Functions.
EXAMPLE 7.8
Calculate the sum of all employees salaries:
USE sample;
SELECT SUM (salary) sum_of_salaries
FROM employees;
EXAMPLE 7.9
Calculate the average of all salaries of the employees
USE sample;
SELECT AVG(salary) avg_salary
FROM employees;
SELECT Statement: Other Clauses
and Functions.
EXAMPLE 7.12
Get id for all employes and their id should be < 1:
USE sample;
SELECT id
FROM employees
GROUP BY id
HAVING COUNT(*) < 1;
END