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

Aggregate Functions

The document contains SQL queries and explanations related to product and student tables, demonstrating various SQL operations such as selection, filtering, aggregation, and ordering of data. It also covers string operations, pattern matching, attribute specification, and set operations like UNION. Additionally, it provides guidelines on using aggregate functions and the GROUP BY clause.

Uploaded by

S HEMALATHA MCA
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Aggregate Functions

The document contains SQL queries and explanations related to product and student tables, demonstrating various SQL operations such as selection, filtering, aggregation, and ordering of data. It also covers string operations, pattern matching, attribute specification, and set operations like UNION. Additionally, it provides guidelines on using aggregate functions and the GROUP BY clause.

Uploaded by

S HEMALATHA MCA
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

SQL> select * from product; ---------- ------------------------------ ---------- --------

PID PNAME QUAN PRICE 3 marker 150 30


---------- ------------------------------ ---------- ------- 4 duster 100 25
1 pen 100 2 5 notebook 50 20
2 pencil 200 10 7 pencil box 300 50
3 marker 150 30 8 waterbottle 500 45
4 duster 100 25
5 notebook 50 20 SQL> select * from product where price not between
6 sticker 150 10 20 and 100;
7 pencil box 300 50
8 waterbottle 500 45 PID PNAME QUAN PRICE
8 rows selected. ---------- ------------------------------ ---------- -------
1 pen 100 2
Select operators: 2 pencil 200 10
6 sticker 150 10
SQL> select * from product where price between 20
and 100;

PID PNAME QUAN PRICE


SQL> select * from product where (price not between 20 and 100) and (quan not in ('100','200'));

PID PNAME QUAN PRICE


---------- ------------------------------ ---------- ----------
6 sticker 150 10

SQL> select * from product where (price not between 20 and 100) or (quan not in('100','200'));

PID PNAME QUAN PRICE


---------- ------------------------------ ---------- ----------
1 pen 100 2
2 pencil 200 10
3 marker 150 30
5 notebook 50 20
6 sticker 150 10
7 pencil box 300 50
8 waterbottle 500 45
------------------------------
SQL> select pid,pname from
marker
product where pname like'w
Sticker
%';
SQL> select
2 pname from product where
PID PNAME
pname like'%n’;
---------- ------------------------------
8 waterbottle
PNAME
SQL> select pname from product
------------------------------
where quan like'_5_';
Pen
SQL> select * from product
PNAME
Arithmetic operators: 8 rows selected.
SQL> select pname,price*10 from product;
SQL> select m1+m2+m3 "marks" from
PNAME PRICE*10 sample1;
----------------------- -------------
pen 20 marks
pencil 100 ----------
marker 300 150
duster 250 155
notebook 200 157
sticker 100 89
pencil box 500
waterbottle 450
Aggregate functions
• Oracle Aggregate function is a type of function which operates on specified column and returns a single row result.
• SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It returns a single
value.
• It is also used to summarize the data.
• GroupFunctionName (DISTINCT / ALL ColumnName).

Guidelines to Use:
• DISTINCT keyword is used to ignore duplicate values and function

consider only non-duplicate values.


• ALL keyword is used to consider all values for the aggregate operation

including duplicates.
• CHAR, VARCHAR2, NUMBER or DATE data types can be used for

argument.
• All group function except COUNT (*) function ignore NULLs. The NVL

function can be a better option to substitute a value for NULLs.


• No single row column(s) should be used with group function in SELECT
SQL> desc student
Name Null? Type
----------------------------------------- -------- ----------------------------
STUD_ID NUMBER(38)
SNAME VARCHAR2(30)
AGE NUMBER(2)
MARKS NUMBER(3)

SQL> select * from student;

STUD_ID SNAME AGE MARKS


---------- ------------------------------ ---------- ----------
3 vishwa 10 45
1 mahima 20 70
2 mahanya 21 80
3 vishwa 10 45
4 vishnu 19 60
3 vishwa 10 45

6 rows selected.
AVG (DISTINCT / ALL ColumnName) Function.

• Output will be the Average value of column.


• It doesn’t consider NULL values.. SNAME
SQL> select sname from student; ------------------------------
mahanya
SNAME mahima
------------------------------ vishwa
vishwa Vishnu
mahima
mahanya SQL> select avg(marks),avg(distinct marks) from
vishwa student;
vishnu
vishwa AVG(MARKS) AVG(DISTINCTMARKS)
---------- ------------------
6 rows selected. 57.5 63.75

SQL> select distinct sname from student;


SUM (DISTINCT / ALL ColumnName) Function.

• Output will be the SUM value of column.


• It doesn’t consider NULL values.
SQL> select sum(age), sum(distinct age) from
student;

SUM(AGE) SUM(DISTINCTAGE)
---------- ----------------
90 70
MAX (DISTINCT / ALL ColumnName) Function
MIN (DISTINCT / ALL ColumnName) Function.
MAX:
• Output will be the maximum value of column.
• It doesn’t consider NULL values.
SQL> select max(marks) from student;

MAX(MARKS)
----------
80
MIN:
• Output will be the minimum value of column.
• It doesn’t consider NULL values.

SQL> select min(marks) from student;

MIN(MARKS)
----------
45
STDDEV (DISTINCT / ALL ColumnName) Function

• Output will be the Standard Deviation of column.


• It doesn’t consider NULL values.
• SQL> select stddev(distinct marks) from student;

STDDEV(DISTINCTMARKS)
---------------------
14.9303941

SQL> select stddev(marks) from student;

STDDEV(MARKS)
-------------
VARIANCE (DISTINCT / ALL ColumnName) Function

• Output will be the Variance of N.


• It doesn’t consider NULL values.
SQL> select variance(marks) from student;

VARIANCE(MARKS)
---------------
227.5
COUNT (*/ DISTINCT / ALL ColumnName) Function

• Output will be the number of rows.


• With COUNT function, * is used to return all rows including duplicates and NULLs.
• It is used to get the count of all rows or distinct values of column.

SQL> select count(marks) from student;


COUNT(MARKS)
------------
6

SQL> select count(distinct marks) from student;


COUNT(DISTINCTMARKS)
--------------------
4

SQL> select count(*) from student;


COUNT(*)
----------
6
GROUP BY Clause with Aggregate Function

• GROUP BY clause is used for grouping the column. mahima 70


• If any aggregate function is included in a SELECT vishwa 45
statement with non-group functional columns then it is vishnu 60
used for grouping the non-group column(s).
calculates the average of the maximum marks of all the
SQL> select sname,max(marks) from student; studentname.
select sname,max(marks) from student SQL> select avg(max(marks)) from student group by sname;
*
ERROR at line 1: AVG(MAX(MARKS))
ORA-00937: not a single-group group function ---------------
returns error because there is a non-group functional column 63.75
is used with an aggregate function MAX. So the
SELECT statement returns all rows for sname column SQL> select sname,sum(age) from student group by
but aggregate function returns only one row. To avoid sname having sum(age)>=20;
the error GROUP BY clause can be used.
SQL> select sname,max(marks) from student group by SNAME SUM(AGE)
sname; ------------------------------ ----------
mahanya 21
SNAME MAX(MARKS) mahima 20
------------------------------ ---------- vishwa 30
SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in ascending or descending order.
• Syntax for using SQL ORDER BY clause to sort data is:
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];

Example: Query to sort the employee table by salary of the employee, the sql query would be.

• SELECT name, salary FROM employee ORDER BY salary;

Orderby two columns:


• SELECT name, salary FROM employee ORDER BY name, salary;

NOTE:
• The columns specified in ORDER BY clause should be one of the columns selected in the SELECT
column list.
• Oracle sorts query results in ascending order by default.
Can also represent the columns in the ORDER BY clause by
specifying the position of a column in the SELECT list, instead of
writing the column name.

• SELECT name, salary FROM employee ORDER BY 1, 2;

• SELECT name, salary


FROM employee
ORDER BY name, salary DESC;

The above query sorts only the column 'salary' in descending order
and the column 'name' by ascending order.
SQL> select * from student; vishwa
vishwa
STUD_ID SNAME AGE vishnu
MARKS mahima
---------- ------------------------------ ---------- ---------- mahanya
3 vishwa 10 45
1 mahima 20 70 6 rows selected.
2 mahanya 21 80
3 vishwa 10 45 SQL> select sname from student order by age desc;
4 vishnu 19 60
3 vishwa 10 45 SNAME
------------------------------
6 rows selected. mahanya
mahima
SQL> select sname from student order by age; vishnu
vishwa
SNAME vishwa
------------------------------ vishwa
vishwa
SQL> select sname,age from student order by age desc; vishwa 10
vishnu 19
SNAME AGE mahima 20
------------------------------ ---------- mahanya 21
mahanya 21
mahima 20 6 rows selected.
vishnu 19 SQL> select sname,age from student order by 2;
vishwa 10
vishwa 10 SNAME AGE
vishwa 10 ------------------------------ ----------
vishwa 10
6 rows selected. vishwa 10
vishwa 10
SQL> select sname,age from student order by age; vishnu 19
mahima 20
mahanya 21
SNAME AGE
------------------------------ ---------- 6 rows selected.
vishwa 10
vishwa 10
The Rename Operation
select name, course id from instructor, teaches where instructor.ID= teaches.ID;
• The result of this query is a relation with the following attributes: name, course id
• The names of the attributes in the result are derived from the names of the attributes
in the relations in the from clause.
• Cannot always derive names in this way, for several reasons:
o First, two relations in the from clause may have attributes with the same name, in
which case an attribute name is duplicated in the result.
o Second, if we use an arithmetic expression in the select clause, the resultant attribute
does not have a name.
o Third, even if an attribute name can be derived from the base relations as in the preceding
example, we may want to change the attribute name in the result.
o Hence,
• SQL provides a way of renaming the attributes of a result relation.
 It uses the as clause
• old-name as new-name is also commonly referred to as a table alias,
• The as clause can appear in both the select or a correlation variable, or a tuple

and from clauses. variable


• if the attribute name name to be replaced SQL> select max(marks) from student;

with the name instructor_name, MAX(MARKS)


 SQL> select name as instructor name, ----------

course id from instructor, teaches where 80

instructor.ID= teaches.ID;
 SQL> select T.name, S.course id from SQL> select max(marks) as maximum_mark

instructor as T, teaches as S where T.ID= from student;

S.ID; MAXIMUM_MARK

An identifier, such as T and S, that is used to ------------

rename a relation is referred to as a 80

correlation name in the SQL standard, but it


String Operations
• SQL specifies strings by enclosing them in single quotes, for example, 'Computer'.

• A single quote character that is part of a string can be specified by using two single quote

characters; for example, the string “It’s right” can be specified by 'It''s right'.

• The SQL standard specifies that the equality operation on strings is case sensitive; as a

result, the expression “'comp. sci.' = 'Comp. Sci.'” evaluates to false. (but mysql or

someother system its case insensitive)

• SQL also permits a variety of functions on character strings, such as concatenating (using

“∥”), extracting substrings, finding the length of strings, converting strings to uppercase

(using the function upper(s) where s is a string) and lowercase (using the function lower(s)),

removing spaces at the end of the string (using trim(s)), and so on.
Pattern matching
Pattern matching can be performed on strings using the operator like.

describe patterns by using two special characters:

Percent (%): The % character matches any substring.

Underscore ( _): The character matches any character.

Patterns are case sensitive; 4 that is, uppercase characters do not match lowercase characters, or

vice versa.

examples:

• 'Intro%' matches any string beginning with “Intro”.

• '%Comp%' matches any string containing “Comp” as a substring, for example, 'Intro. to

Computer Science', and 'Computational Biology'.

• ‘_ _ _ ' matches any string of exactly three characters.

• ' _ _ _%' matches any string of at least three characters.


• SQL allows the specification of an escape character.
• The escape character is used immediately before a
special pattern character to indicate that the special
pattern character is to be treated like a normal character.
• • like 'ab∖%cd%' escape '∖' matches all strings beginning
with “ab%cd”.
• • like 'ab∖∖cd%' escape '∖' matches all strings beginning
with “ab∖cd”.
Attribute Specification in the Select Clause

• The asterisk symbol “ * ” can be used in the select clause to


denote “all attributes.”

• Thus, the use of instructor.* in the select clause of the


query:

• select instructor.* from instructor, teaches where


instructor.ID= teaches.ID
Set Operations
• The SQL operations union, intersect, and except operate on relations and

correspond to the mathematical set operations ∪, ∩, and −.

UNION:
(select course id from section where semester = 'Fall' and year= 2017) union

(select course id from section where semester = 'Spring' and year= 2018);
• The union operation automatically eliminates duplicates and sort them
• , unlike the select clause.

To retain all duplicates, union all can be used in place of union:

(select course id from section where semester = 'Fall' and year= 2017) union all

(select course id from section where semester = 'Spring' and year= 2018);
SQL> select * from student;
SQL> select * from course;
STUD_ID SNAME GE MARKS
---------- ------------------------------ ---------- ---------- CID CNAME
3 vishwa 10 45 ---------- --------------------
1 mahima 20 70 1 mca
2 mahanya 21 80 2 mba
3 vishwa 10 45 3 bsc
4 vishnu 19 60 4 msc
3 vishwa 10 45 5 mca

6 rows selected. SQL> select * from course where cname='mca' union


SQL> select * from subject; select * from student where stud_id<3;
select * from course where cname='mca' union select *
SID SN from student where stud_id<3
---------- -- *
1 c ERROR at line 1:
2 cp ORA-01789: query block has incorrect number of
3 ja result columns
4 da
Intersect:
• automatically eliminates duplicates.
• To find the set of all courses taught in both the Fall 2017 and Spring
2018, we write:
(select course id from section where semester = 'Fall' and year= 2017)
intersect (select course id from section where semester = 'Spring' and
year= 2018);

• To retain all duplicates, we must write intersect all in place of intersect


(select course id from section where semester = 'Fall' and year= 2017)
intersect all (select course id from section where semester = 'Spring'
and year= 2018);
The Except Operation :
• To find all courses taught in the Fall 2017 semester but not in the
Spring 2018 semester, we write:
(select course id from section where semester = 'Fall' and year= 2017)
except (select course id from section where semester = 'Spring' and
year= 2018);
• The operation automatically eliminates duplicates in the inputs before
performing set difference.
• To retain duplicates, we must write except all in place of except:
(select course id from section where semester = 'Fall' and year= 2017)
except all (select course id from section where semester = 'Spring'
and year= 2018);
Null Values
• The null value is a special value that signifies that the value is unknown or does not
exist.
• Null values present special problems in relational operations, including arithmetic
operations, comparison operations, and set operations.
• The result of an arithmetic expression (involving, for example, +, −, ∗, or ∕) is null if
any of the input values is null.
• For example, if a query has an expression r.A + 5, and r.A is null for a particular tuple,
then the expression result must also be null for that tuple.
• consider the comparison “1 < null”. It would be wrong to say this is true since we do
not know what the null value represents.
• But it would likewise be wrong to claim this expression is false; if we did, “not (1 <
null)” would evaluate to true, which does not make sense.
• SQL therefore treats as unknown the result of any comparison involving a null value
• the definitions of the Boolean operations are extended to deal
with the value unknown.
• and:
– The result of true and unknown is unknown,
– false and unknown is false,
– while unknown and unknown is unknown.

• or:
– The result of true or unknown is true,
– false or unknown is unknown,
– while unknown or unknown is unknown.

• not:
– The result of not unknown is unknown
• SQL uses the special keyword null in a predicate
to test for a null value.
• Thus, to find all instructors who appear in the
instructor relation with null values for salary, we
write:
• select name from instructor where salary is null;
SQL> select * from subject; SQL> select sid from subject where sname is null;

SID SN SID
---------- --
----------
1 c
2 cp 8
3 ja 9
4 da 4
8
9
6 = While inserting number value -> add null value
4 as null
ww SQL> insert into subject values(&sid,'&sname');
9 rows selected. Enter value for sid: null
Enter value for sname: ww
SQL> select sname from subject where sid is null; old 1: insert into subject values(&sid,'&sname')
new 1: insert into subject values(null,'ww')
SN
--
ww 1 row created.

You might also like