Chapter 7 - Querying Using SQL
Chapter 7 - Querying Using SQL
• For example, the following statement will sort the records firstly
on the column name Section and then on the basis of descending
order of column marks.
1. To calculate the total gross for employees of grade ‘E2’, the command
is :
SELECT SUM ( gross ) FROM employee
WHERE grade = ‘E2’
2. To display the average gross of employees with grads ‘E1’ or ‘E2’ the
command used is :
SELECT AVG( gross ) FROM employee
WHERE ( grade = ‘E1’ OR grade = ‘E2’ );
4. To count the number of cities, the different members belong to, you
use the following command:
SELECT COUNT ( DISTINCT city) FROM members;;
SQL supports many and many functions. All these function can be generally categorized
into following two types:
Single Row (Scalar) functions : These functions work with a single row at a time. A
single row function returns a result for every row of a queried table.
Multiple Row(Group or Aggregate ) functions :These functions work with data of
multiple rows at a time and return aggregated value.
examples - sum( ), count( ) , max( ) , mini ( ), avg ( ) etc.
Difference : The difference betwen these two functions is in the number of rows they
act upon.
A single row function works with the data of a single row at a time and returns a single
result for each row queried upon.
A multiple row function works with a group of rows and returns a signle result for that
group.
• The GROUP BY clause is used in SELECT statement to divide the table into
groups.
• Grouping can be done by a column name, or with aggregate functions.
• For example , to calculate the number of employees in each job , the command
will be
In department number 10, there are 3 employee & total of all salaries is 8750.00
In department number 20, there are 5 employee & total of all salaries is 10885.00 and so on.
Nested grouping : With GROUP BY clause, you can create groups. Such type of
grouping is called Nested grouping. This can be done by specifying in GROUP BY
expression, where 1st filed determines the highest group level, the 2nd filed
determines the second group level, and so on.
non- group-field (or expression) : is the field that has different values in the
rows belonging to the group.
While grouping, you should include only group-fileds in the select list
If we include a non-group expression in the select -list, it would not
create any error.
It will return the value from first record of the group.
example: This is non-group field as it has
multiple values for a group
SELECT deptno, COUNT (empno ) ,mgr
FROM empl
GROUP BY deptno;
The output returned will be :
• To create a nested group, you need to specify multiple fields in the
GROUP BY expression.
• Using the empl table to group job wise Deptno wise, we need to create a
query like this: