0% found this document useful (0 votes)
25 views

Chapter 7 - Querying Using SQL

This document discusses SQL commands like ORDER BY, GROUP BY, and HAVING clauses. It explains how ORDER BY sorts result sets, how GROUP BY divides result sets into groups, and how HAVING filters groups. Examples are provided for each clause to illustrate their usage.

Uploaded by

Anjana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Chapter 7 - Querying Using SQL

This document discusses SQL commands like ORDER BY, GROUP BY, and HAVING clauses. It explains how ORDER BY sorts result sets, how GROUP BY divides result sets into groups, and how HAVING filters groups. Examples are provided for each clause to illustrate their usage.

Uploaded by

Anjana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

This chapter will talk about some SQL commands in details.

After this chapter, you shall be able to display groups records,


summary of groups of records and display selected groups of
records.
ORDER BY clause
Although you have read about ORDER BY clause of SQL SELECT
statement in your previous class,here we are covering it again in
a detailed manner.
• The Result set generated by the SQL SELECT statement is not
ordered in any form by default. However, if you want to sort or
order the resultset, you can use thr ORDER BY clause of SQL
SELECT statement as oer following format :
SELECT <comma separated select list> FROM <table>
[ WHERE <condition > ]
ORDER BY <fieldname> [ASC | DESC] [, <fieldname> [ASC |
DESC], . . .] ;
ASC stands for ascending and DESC for descending
default order is ascending
mysql > SELECT * FROM data
For example consider the table
-> ORDER BY marks;
Data having records as shown
• To order the result set on multiple columns, you can specify the
multiple column names in ORDER by clause along with the
desired sort order.

• 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.

mysql > SELECT * FROM data


-> ORDER BY section ASC , marks DESC ;
• Sometimes , we need to display the result of a calculation
or a mathematical expression in the result set.

• In such cases, we may want or need to arrange your result


set in the order of the calculated expression.

• The ORDER BY clause allows you to include the


mathematical exprssion to order the result set by it.
mysql > SELECT rollno, name, grade, section, marks *.35
-> FROM data WHERE marks > 70
-> ORDER BY section ASC, marks*0.35 DESC;
We can provide a column alias name to the mathematical expression as follows:
mysql > SELECT rollno, name, grade, section, marks *.35 as Term1
-> FROM data WHERE marks > 70
-> ORDER BY section ASC, Term1 DESC;
mysql > SELECT rollno, name, grade, section, marks *.35
-> FROM data WHERE marks > 70
-> ORDER BY section ASC, marks*0.35 DESC;
• Aggregate functions work upon groups of rows, rather than on
single row.
• Aggregate functions also known as group functions or multiple
row functions.
• Many group functions accept the following options:

DISTINCT This option causes a group function to consider only distinct


values of the argument expression
ALL This option cause a group function to consider all values
including all duplicates
All the example will be based upon following table empl
1. AVG
This function computes the average of given data.

Syntax AVG ( [ DISTINCT | ALL ] n )

 Returns average value of parameter(s) n .

Argument type : Numeric Return value : Numeric

Example mysql > SELECT AVG (sal ) “Average”


-> FROM empl ;
2. COUNT
This function counts the number of rows in a given column or expression.
Syntax COUNT ( { * [ DISTINCT | ALL ] expr } )

 Returns the number of row in the query.


 If you specify argument expr, this function retirns rows where expr in
not null. You can count either all rows, or only distinct values of expr.
 If you specify the astrisk ( * ) , this funtion returns all rows , including
duplicates and nulls.

Argument type : Numeric Return value : Numeric

Example mysql > SELECT COUNT ( * ) “Total”


-> FROM empl ;
3. MAX
This function returns the maximum value from a given column or
expression.
Syntax MAX ( [ DISTINCT | ALL ] expr )

 Returns maximum value of argument expr.

Argument type : Numeric Return value : Numeric

Example mysql > SELECT MAX( sal ) “Maximum Salary”


-> FROM empl ;
4. MIN
This function returns the minimum value from a given column or
expression.
Syntax MIN ( [ DISTINCT | ALL ] expr )

 Returns minimum value of expr.

Argument type : Numeric Return value : Numeric

Example mysql > SELECT MIN( hiredate) “Minimum Hire Date”


-> FROM empl ;
5. SUM
This function returns the sum of value in given column or expression.
Syntax MIN ( [ DISTINCT | ALL ] expr )

 Returns sum of values of .

Argument type : Numeric Return value : Numeric

Example mysql > SELECT SUM( sal ) “Total Salary”


-> FROM empl ;
Some more examples of group functions are being given below:

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’ );

3. To count the number of employees in employee table, the SQL


command is:
SELECT COUNT ( * ) FROM employee;

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

SELECT job, COUNT (*)


FROM empl
GROUP BY job;
• Now consider the following query , which is also grouping records based on
deptno.

SELECT deptno, COUNT (*) ,SUM(sal)


FROM empl
GROUP BY deptno;

this command is displaying count of


records and sum of salaries in each
group and the groups are formed on the basis of deptno.

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.

Consider Table 7.1 empl.


Example : if we want to count the number of employees in each group, we need to
issue a query statement as below:

SELECT COUNT (empno ) FROM empl


GROUP BY Deptno;
But these are employee-count for which departments? Now modify the query

SELECT deptno, COUNT (empno )


FROM empl
GROUP BY deptno;

group-field (or expression) : is the field that


either have the same value for a group or
contain a group function.

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:

SELECT deptno, Job, COUNT (empno )


FROM empl
GROUP BY deptno, job;
• The HAVING clause places conditions on groups in contrast to WHERE clause that
places conditions on individual rows.
• WHERE conditions cannot include aggregate functions, while HAVING conditions
can do so.
Example : To calculate the average gross and total gross for employee belonging to
‘E4’ grade, the command would be:
SELECT AVG( gross ) , SUM(gross )
FROM employee This conditon would be applicable
GROUP BY grade on group and not on individual rows
HAVING grade = ‘E4’ ;
• To display the job where the number of employees is less than 3, you use
the command

SELECT JOB, COUNT ( * )


FROM empl
GROUP BY job HAVING count ( * ) < 3;

This will produce the following output


• To HAVING clause can contain either a simple boolean expression or use
aggregate function in the having condition.
• We can indluse more than one condition in HAVING clause, by using
logical operator.
example: SELECT Deptno, AVG(Comm) , AVG(Sal)
FROM empl
GROUP BY Deptno
HAVING AVG(Comm) > 750 AND AVG(Sal) > 2000;
• You can an aggregate funtion in the HAVING clause even if it is not in the
SELECT list.
SELECT Deptno, AVG(Sal)
FROM empl
GROUP BY Deptno
HAVING COUNT(*) < =3
• We can also use IN or BETWEEN operators with HAVING clause.

SELECT Deptno, Job ,AVG(Sal)


FROM empl
GROUP BY Deptno , Job
HAVING JOB IN ( ‘CLERK’ , ‘SALESMAN’);

SELECT Deptno, Job ,SUM(Sal)


FROM empl
GROUP BY Deptno , Job
HAVING SUM(sal) BETWEEN 3000 AND 7000
• As mentioned before, if you include a non-group expression in the
select-list of a query with GROUP BY, MySQL will not produce any error.
• It will pick value of the specified non-group files from the first row of
the group.
• It will produce ambiguous result.

mysql > SELECT ename, sum(sal)


FROM empl
GROUP BY deptno;
It is not conveying that AMIR’s
salary-sum is 8750.00
SMITH’s 10885.00 and ANYA’s 9400.00?

We, recommend not to use non-group expression


in GROUP BY query.

You might also like