Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Database Management and MySQL Part2 CS

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

Database Management and MySQL Part2 CS

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

MySQL Commands

- Aggregate functions
- Group by clause with Having
- Joins
SQL commands
► Aggregate Functions (MULTI ROW FUNCTIONS)

Aggregate functions produce a single value for an entire group of table


entries. Aggregate or column functions can be used with the SELECT
command to calculate summary values from the data in a particular
column of a table. These functions are SUM(), AVG(), MAX(), MIN() and
COUNT().

SELECT SUM(SAL) ,AVG(SAL) SELECT SUM(SAL),NAME


FROM EMP; FROM EMP;
Table : employee
empno name basic dept dob floor
101 Ravi 5000.00 accts 2001-02-09 1
102 Khyati 3000.00 admn 2002-09-08 2
103 Surbhi 6000.00 accts 2003-08-03 2
104 Rohit 5500.00 admn 2001-09-08 2
105 Aaa 67889 admn 2020-09-09 1
Print total basic of each dept for those employees which are on 1st floor.

select dept, sum(basic)

Accts 110000 from employee

Admn 8500 group by dept;


MySQL commands
► Aggregate Functions

Sum()

Sum() calculates the arithmetic SUM of all selected values of a given column holding
numeric entries.

Example
Select SUM (Basic) from employee;
Output :
SUM(BASIC)
19500
MySQL commands
► Aggregate Functions

Avg() - Avg() calculates the average (mean) of all selected values of a


given field holding numeric entries.

Example :

Select avg (Basic) from employee where dept=’ACCTS’;


Output:

AVG(BASIC)
5500
MySQL functions
► Aggregate Functions

Max() - MAX function calculates the largest of all selected values of a


given column.

Example :

Select max (Basic) from employee;

Output:

MAX(BASIC)
6000
MySQL functions
► Aggregate Functions

Min() – MIN function calculates the smallest of all selected values of a


given column.

Example :

Select min (Basic) from employee;

Output:

MIN(BASIC)
3000
MySQL functions
► Multiple Row functions / Aggregate Functions

Count() - Count() counts the number of rows in the output table. Count() with the asterisk(*)
counts the number of rows in the table including NULLs.

Example 1:

Select count(*) from employee; Select count(DEPT) from employee; WILL DISPLAY 3
will count the number of records present in a table including Nulls.

Output: Table : employee


empno name basic dept dob
COUNT(*)
101 Ravi 5000.00 accts 2001-02-09
4 102 Khyati 3000.00 admn 2002-09-08
103 Surbhi 6000.00 NULL 2003-08-03
104 Rohit 5500.00 admn 2001-09-08
MySQL functions
► Multiple Row functions / Aggregate Functions

Example 2:

Select count(*) from employee where dept=’admn’;

will count the number of employee records who are in admn dept.

Output:
COUNT(*) Table : employee
2 empno name basic dept dob
101 Ravi 5000.00 accts 2001-02-09
102 Khyati 3000.00 admn 2002-09-08
103 Surbhi 6000.00 NULL 2003-08-03
104 Rohit 5500.00 admn 2001-09-08
MySQL functions
► Multiple Row functions / Aggregate Functions

Example 3:

Select count(dept) from employee;

will count the number of employee records with non Null dept values.

Output:
COUNT(DEPT) Table : employee
empno name basic dept dob
3
101 Ravi 5000.00 accts 2001-02-09
102 Khyati 3000.00 admn 2002-09-08
103 Surbhi NULL NULL 2003-08-03
104 Rohit 5500.00 admn 2001-09-08
SQL commands
► Group By clause
The GROUP BY clause used with SELECT statement is used to group rows that have
the same values.

Example :

SELECT DEPT, MAX(BASIC) FROM employee GROUP BY DEPT;

This command will group all records which have the same value of DEPT and then
displays the average of salary for each of all groups.

Output: Table : employee


empno name basic dept dob
DEPT MAX(BASIC)
101 Ravi 5000.00 accts 2001-02-09
accts 6000.00 102 Khyati 3000.00 admn 2002-09-08
admn 5500.00 103 Surbhi 6000.00 accts 2003-08-03
104 Rohit 5500.00 admn 2001-09-08
SQL commands
► Having clause

The HAVING clause places condition on groups . These include group functions while
placing conditions.

Example : Display the total number of employees in each department.


Select dept, count(*) from employee group by dept;
SELECT DEPT, COUNT(*) FROM employee GROUP BY DEPT HAVING COUNT(*) >1;

This statement will display no of records in each department where the number of
employees is greater than 1 Table : employee

Output: empno name basic dept dob


101 Ravi 5000.00 accts 2001-02-09
DEPT COUNT(*)
102 Khyati 3000.00 admn 2002-09-08
accts 2 103 Surbhi 6000.00 accts 2003-08-03
admn 2 104 Rohit 5500.00 admn 2001-09-08
SQL commands
► Having clause

The HAVING clause places condition on groups . These include group functions while
placing conditions.

Example : Display the total number of employees in each department.


Select dept, count(*) from employee group by dept;

Example : Display the total number of employees in each department.


where number of employees are more than 1.

Select dept, count(*) from employee group by dept having count(*)>1;


Table : Student (Name, Admno, Board_No, Stream, Grade, Tmarks,
Per)
Write Query to perform the following:
(i) Display the total number of students in each stream
Ans: SELECT STREAM, COUNT(*) FROM STUDENT GROUP BY STREAM;
(II) Display the Names of streams whose average Percentage is >80.
Ans: SELECT STREAM FROM STUDENT GROUP BY STREAM HAVING
AVG(PER)>80;
(III) Display the total number of students who scored above 90% in each
stream.
Ans. SELECT STREAM,COUNT(*) FROM STUDENT WHERE PER>90 GROUP BY
STREAM;
Table : Student (Name, Admno, Board_No, Stream, Grade, Tmarks,
Per)
Write Query to perform the following:
(i) Display the total number of students who scored above 90% in each
stream for those streams whose average percentage >80.
Ans:SELECT STREAM, COUNT(*) FROM STUDENT WHERE PER>90 GROUP BY
STREAM HAVING AVG(PER)>80;

(i) Display the details of each student.


(ii) Display the sum of marks of each stream.
SELECT STREAM,SUM(TMARKS),NAME FROM
STUDENT GROUP BY STREAM;

SELECT STREAM,SUM(TMARKS) FROM


STUDENT GROUP BY STREAM;
NAME OF THE PDF-
XII-C-GROUP1-ART-INTEGRATED-CS

MAIL PROJECTS AT :
computerdepartmentdpsvk@gmail.com
SQL commands
► Joins

When information from more than one tables are to be extracted JOIN concept is
used. A join command combines rows from two or more tables. The main purpose of
joining tables is to establish a link between the tables.

The tables are joined using = operator or join keyword.

In MySQL,there are different types of join:

➢ Equi join

➢ Natural join
SQL commands - Joins

OR
Select * from <table 1> join <table 2>
on <table 1>.column_name = <table 2>.column_name;

SELECT * FROM SUP JOIN ORDER


ON SUP.SNO=ORDER.SNO;
SQL commands - Joins
► Equi Joins
➢ In this join , the values in the columns being joined are compared for equality.
➢ The names of the columns which have matching values need not be same.
➢ The output contains repeated columns , one from each table.
Syntax:

Select * from <table 1> , <table 2>


where <table 1>.column_name = <table 2>.column_name;
SELECT * FROM SUP,ORDER
WHERE SUP.SNO=ORDER.SNO;

SELECT * FROM SUP,ORDER


WHERE SNO=SUPNO;
SQL commands - Joins
► Equi Joins
Example : Consider two Relations – empl and dept_ment as shown below:

Relation :empl Relation :dept_ment


empno name basic deptno
deptno dname
101 Ravi 5000.00 11
11 ADMN
102 Rohit 6500.00 12
12 ACCTS
103 Sakshi 4200.00 11
13 MKTG
104 Jyoti 5200.00 13

Q1 DISPLAY INFORMATION OF ALL EMPLOYEES ALONG WITH DEPARTMENT NAMES WHOSE


BASIC >5000.
ans : SELECT * FROM EMPL, DEPT_MENT
WHERE EMPL.DEPTNO=DEPT_MENT.DEPTNO AND BASIC>5000;
SQL commands - Joins
empno name basic deptno deptno dname

101 Ravi 5000.00 11 11 ADMN

102 Rohit 6500.00 12 12 ACCTS

103 Sakshi 4200.00 11 13 MKTG

104 Jyoti 5200.00 13

Q2. DISPLAY THE DETAILS OF ALL EMPLOYEES WHOSE NAMES BEGIN WITH R.
ANS: SELECT * FROM EMPL WHERE NAME LIKE “R%”;

Q3. DISPLAY THE DETAILS OF ALL EMPLOYEES OF ACCTS DEPT.

ANS: SELECT * FROM EMPL,DEP_MENT


WHERE EMPL.DEPTNO=DEP_MENT.DEPTNO AND DNAME=“ACCTS”;
SQL commands - Joins
► Equi Joins
To get the information from two tables which are empl and dept_ment by
combining rows on the basis of a common column i,e, deptno in the output, the
command would be:

Example :
deptno from
select * from empl,dept_ment where empl.dptno=dept_ment.deptno; both the tables
The output would be: displayed

empno name basic deptno deptno dname

101 Ravi 5000.00 11 11 ADMN

102 Rohit 6500.00 12 12 ACCTS

103 Sakshi 4200.00 11 11 ADMN

104 Jyoti 5200.00 13 13 MKTG


SQL commands - Joins
► Equi Joins

An alternative command to get the same output would be:

select * from empl join dept_ment on empl.deptno=dept_ment.deptno;

empno name basic deptno deptno dname

101 Ravi 5000.00 11 11 ADMN

102 Rohit 6500.00 12 12 ACCTS

103 Sakshi 4200.00 11 11 ADMN

104 Jyoti 5200.00 13 13 MKTG


SQL commands - Joins
► Equi Joins

Command with additional condition along with join condition.

select * from empl , dept_ment where empl.deptno=dept_ment.deptno and basic > 5000;

The output would be:

empno name basic deptno deptno dname

102 Rohit 6500.00 12 12 ACCTS

104 Jyoti 5200.00 13 13 MKTG


SQL commands - Joins
► Equi Joins

Command with selective columns and additional condition along with join condition.

select empno, empl.deptno, dname from empl , dept_ment where


The common
empl.deptno=dept_ment.deptno and basic > 5000; column which is
to be displayed
has to be
The output would be:
prefixed with a
tablename.
SQL commands - Joins
► Table alias
▪ It is observed that in order to use the column which has common values in
either of the tables, it has to be prefixed with the required table_name .
▪ In order to avoid writing such tablenames with bigger notations, it can be
replaced with temporary labels known as Table aliases.
Alternatively the command shown below
select * from empl ,dept_ment where empl.deptno=dept_ment.deptno;
Can be written using table alias as:
select * from empl e, dept_ment d where e.deptno=d.deptno;
where e and d are table aliases for tables names empl and dept_ment
respectively.
SQL commands - Joins
► Natural join
➢ This is a type of join that combines tables based on columns with the same
name and type.
➢ In this the column which has common values appear only once.

Example :

select * from empl natural join dept_ment ; Column


deptno
appears
deptno empno name basic dname
only once
11 101 Ravi 5000.00 ADMN

12 102 Rohit 6500.00 ACCTS

11 103 Sakshi 4200.00 ADMN

13 104 Jyoti 5200.00 MKTG


SQL commands - Joins
► Natural join
➢ Names of primary key and foreign key should be same.

➢ Inspite of giving select * , the common column appears only once.

➢ We don’t specifically give where clause to compare the foreign key

and the primary key. Where will be used only if the query contains a
specific condition to select specific tuples.

select * from empl natural join dept_ment ;


SQL commands - Joins
► Natural join
Command given with selective columns
Example :
select empno,name,dname from empl natural join dept_ment ;

empno name dname


101 Ravi ADMN

102 Rohit ACCTS

103 Sakshi ADMN

104 Jyoti MKTG


SQL commands - Joins
► Natural join
Command given with selective columns and condition
Example :
Display empno, name, deptname for all employees belonging to
department whose names begin with ‘A’.

select empno,name,dname from empl natural join


dept_ment where dname like ‘A%’;
empno name dname
101 Ravi ADMN

102 Rohit ACCTS

103 Sakshi ADMN


SQL commands
► SELECT statement (Overall Syntax)

SELECT */<Col1>,<Col2>,…..,<Col N> / Expression> / <Agg.Func.>

FROM <Table Name>

[WHERE <Conditon>]

[GROUP BY <Grouping Col>>]

[HAVING <Aggregate Condition>]

[ORDER BY <Ordering Col1> [ASC/DESC], <Ordering Col2> [ASC/DESC]….];


Solved Example
Consider the tables shown below:

Table : STORE
Table : Suppliers
Itemno Item Scode Qty Rate Lastbuy Scode Sname
2005 Sharpener Classic 23 60 8 2009-06-31 21 Premium Stationers
2003 Ball Pen 0.25 22 50 25 2010-02-01 23 Soft Plastics
2002 Gel Pen Premium 21 150 12 2010-02-24 22 Tetra Supply
2006 Gel Pen Classic 21 250 20 2009-03-11

2001 Eraser small 22 220 2009-01-19

2004 Eraser Big 22 110 8 2009-12-09

2009 Ball Pen 0.5 21 180 18 2009-11-03


Solved Example
(i) To display the details of all Items in the Store table in ascending order of Lastbuy

Select * from store order by lastbuy ;

(ii) To increase the Qty by 10 of all records of Store whose Lastbuy is before 01-feb-
2010

update store set qty = qty + 10 where lastbuy < ‘2010-02-01’;

(iii) To display minimum rate of items for each supplier as per Scode.

Select scode, min(rate) from store group by scode;

(iv) To remove column qty from store table

Alter table store drop column qty;


Solved Example
(v) To display Itemno,Changed Rate which is 5% of Rate from Store table
Select itemno, 0.05*rate “ Changed Rate” from store;
(vi) To display all records of Store whose rate is not entered in the table.

Select * from store where rate is null;

(vii) To display Itemno,Item and Sname of all Items.

Select itemno, item, s.scode , sname from store s, suppliers sl where


s.scode=sl.scode;

(viii) To display all records from Store table whose Item name starts from G

Select * from store where item like ‘G%’;


Solved Example
(ix) To display Itemno, qty and sname for those whose lastbuy is after ‘2009-01-01’ .

Select itemno, qty, sname from store s, suppliers sl where s.scode=sl.scode


and lastbuy>’2009-01-01’;

(x) To display count of all distinct items.

Select count(distinct item) from store;

(xi) To find sum of rates of all items whose item names starts from ‘Gel’;

Select sum(rate) from store where item like ’Gel%’;

(xii) To delete all records from Store table whose rate is less than 10.

delete from store where rate <10;


Solved Example
Give the outputs for the following according to the tables given below:

a. Select scode, max(qty) from store group by scode;

scode max(qty)
21 250
22 220
23 60

b. Select min(rate), max(rate) from store where item like ‘B%’;


min(rate) max(rate)
18 25
Solved Example
Give the outputs for the following according to the tables given below:

a. Select itemno, item, store.scode from store,suppliers where item in (‘Sharpener


Classic’,’Gel Pen Classic’);

itemno item scode


2005 23 Soft Plastics
2003 21 Premium Stationers

b. Select avg(qty) from store where lastbuy>’2010-01-01’ ;


Avg(qty)
18.5
Solved Example
Consider the table shown below:
Solved Example
(i) To display the names of all items in ascending order of price which are purchased
in July 2015
Select name from shop order by price where Purchase_date>=‘2015-07-01’ and
Purchase_date<=‘2015-07-31’;

(ii) To display the details of all the items whose quantity is more than 10.

Select * from shop where quantity>10;

(iii) To display the name, (price * quantity) with the column heading “Total Value” of
all the items

Select name, price * quantity “Total value” from shop ;

(iv) To increase price of all items by 10% which are in “cos” category

Update shop set price = price + 0.1 * price where category = “cos”;
Solved Example
(v) To display all the records which are starting with the letter “B”.
Select * from shop where name like ‘B%’;
(vi) Delete all the records which are purchased in the year 2014.
Delete from shop where Purchase_date between ‘2014-01-01’ and ‘2014-12-31’ ;
(vii) To display all the item names whose price is less than 50.
Select name from shop where price < 50;

(ix) Display all the records whose quantity is more than 50 in increasing order of price;

Select * from shop where quantity>50 order by price;


Solved Example
(x) Insert a record with the specification (I015, paper,10,500,sta,2015-08-10)
Insert into shop values(1015,’paper’,10,500,’sta’,’2015-08-10’);

(xi) Display the records of all the items whose salesman name contains the word
“singh” .

Select * from shop where Salesman_name like ‘%singh%’;


Solved Example
(xiii) Display all the records whose salesman_name is not entered in the table.
Select * from shop where Salesman_name is Null;

(xiv) Add a new column “Discount” to store discount with 5 integer positions and 2
decimal places

Alter table shop add(Discount decimal(5,2));

(xv) Replace the discount as 10% of the price of All items

Update shop set discount = 0.1* price;


Solved Example
Give the outputs for the following according to the tables given below:

a. Select category , min(price) from shop group by category;

category min(price)
cos 200
gro 100
sta 40

b. Select category, max(quantity) from shop group by category having count(*) > 1;
category max(quantity
gro 130
sta 100
Solved Example
Consider the table shown below:
SCHOOL
CODE TEACHERNAME SUBJECT DOJ PERIOD EXPERIENCE
1001 RAVI SHANKAR ENGLISH 2000-12-03 S24 10
1009 PRIYA RAI PHYSICS 1998-09-03 26 12
1203 LISA ANAND ENGLISH 2000-04-20 27 5
1045 YASHRAJ MATHS 2000-08-02 24 15
1123 GANAN PHYSICS 1999-07-19 28 3
1167 HARISH B CHEMISTRY 1999-10-19 27 5
1215 UMESH PHYSICS 1998-05-11 22 16
Solved Example
(i) To display TEACHERNAME, PERIOD of all teachers whose periods are less than
equals to 25.
Select teachername ,period from school where periods <=25;
(ii) To display the subject wise minimum PERIOD.

Select subject, min(period) from school group by subject;

(iii) To display CODE, TEACHERNAME and SUBJECT of all teachers who have joined the
school in the year 1999.

Select code, teachername, subject from school where doj between ‘1999-01-01’
and ‘1999-12-31’;

(iv) To count all teachers whose experience is more than 10 .

Select count(*) from school where experience>10;


Solved Example
(v) To display minimum experience subjectwise for those subjects whose count of
teachers is more than 1.
Select min(experience) from school group by subject having count(*)>1;

(vi) Remove all the records from the table whose teachername begins with ‘LI’.

Delete from school where teachername like ‘LI%’ ;


(vii) To display average experience of those teachers whose doj is after ‘1998-09-01’.
Select avg(experience) from school where doj>’1998-09-08’;

(ix) To display all the subject names without the duplicates.

Select distinct subject from school ;


Solved Example
(x) Display maximum and minimum period from school table.
Select max(period), min(period) from school ;

(xi) To display average experience of those who have joined in the year 2000.

Select avg(experience) from school where doj between ‘2000-01-01’ and

‘2000-12-31’;
(xii) To increase the period value by 5 of all teachers whose subject is ‘ENGLISH’.
Update school set period=period + 5 where subject=‘ENGLISH’;
Solved Example
Give the outputs for the following according to the tables given below:

a. SELECT MAX(EXPERIENCE), SUBJECT FROM SCHOOL GROUP BY SUBJECT;

MAX(EXPERIENCE) SUBJECT
5 CHEMISTRY
10 ENGLISH
15 MATHS
16 PHYSICS
b. SELECT COUNT(*) FROM SCHOOL WHERE PERIOD > 25;
COUNT(*)
4
Solved Example
Give the outputs for the following according to the tables given below:

a. SELECT COUNT(DISTINCT SUBJECT) FROM SCHOOL;

COUNT(DISTINCT SUBJECT)

b. SELECT 0.5*PERIOD “REDUCED NO” FROM SCHOOL WHERE SUBJECT LIKE “%S”;
REDUCED NO
13
12
14
11
Assessment
Which of the following is not an aggregate function?
a. AVG()
b. SUM()
c. TOTAL()
d. MIN()
Answer : c. TOTAL()

If a table Course has columns- Admno, Name, Aggregate, Stream. Give command
to display highest aggregate obtained in each stream.
a. SELECT STREAM, MAX(AGGREGATE) FROM COURSE;
b. SELECT STREAM, MAX(AGGREGATE) FROM COURSE GROUP BY STREAM;
c. SELECT STREAM, MAX(AGGREGATE) FROM COURSE ORDER BY STREAM;
Answer : b . SELECT STREAM, MAX(AGGREGATE) FROM COURSE GROUP BY STREAM;
Assessment
Which command is used to select a database to make it current?
a. Open databasename
b. Use databasename
c. Select databasename
d. None of the above
Answer : b Use databasename

Which keyword is used to put a condition in a query to select specific row?


a. from
b. where
c. None of these

Answer : b where
Assessment
In which join , there are no duplicate columns?
a. Equi join
b. Natural join
c. Cross join
d. None of the above
Answer : b Natural join

In which type of join , the join condition contains equality operator?


a. Equi join
b. Natural join
c. Cross join
d. None of the above

Answer : a Equi join


Assessment
The SQL keyword _______combines together those rows that have same value in a column.
a. Order by
b. Group by
c. Having
d. None of the above
Answer : b Group by

Aggregate functions can be used in the select list or the _____ clause of a select statement
.They cannot be used in a _______ clause.
a. Where, having
b. Having, where
c. Group by, having
d. Group by , where

Answer : b Having, where


Assessment
The following command has which type of join:
SELECT CUST.CID,ORDER.CID,ORDER_ID FROM CUST,ORDER WHERE CUST.ID=ORDER.CID;
a. Equi join
b. Natural join
c. None of the above
Answer : a Equi join

What is the meaning of where in group by query?


a. To filter out summary groups
b. To filter out rows before creating groups
c. None of the above

Answer : b To filter out rows before creating groups

You might also like