Mysql Ppt1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 93

Review of Chapter 1

MySQL Querying And


SQL Functions

Q L
B A S E
M yS
TA
DA D B M S

M N
O W CO LU
R

R Y N A L
M A A T I O
P R I
Y R E L BA S E
K E D AT A
Review of Chapter 1
MySQL Querying And
SQL Functions

MySQL is an open-source relational


database management system. Its name is
a combination of "My", the name of co-
founder Michael Widenius's daughter My,
and "SQL", the abbreviation for Structured
Query Language
Review of Chapter 1
MySQL Querying And
SQL Functions

We have also learnt how to populate,


manipulate and retrieve data from
a database using SQL queries.
LO: To learn more SQL commands which are
required to perform various queries in a
database
Review of Chapter 1
MySQL Querying And
SQL Functions
❖ A database is an organized collection of inter related data

❖ A database management system is a software application for


interaction between users and the database.
Eg. MySQL, Microsoft Access, Oracle, Microsoft SQL Server, DB2 and
Sybase.

❖ A table is a two dimensional representation of data in rows and columns

❖ Row/Tuple/Record: The horizontal subset of a table

❖ Column/Attribute / field: The vertical subset of the Table

❖ Relational database: A database that stores data in separate tables that


are related through the use of a common column
Review of
MySQL
❖ RDBMS: A DBMS used to manage Relational Databases is called an
RDBMS (Relational Data Base Management System). Some popular
RDBMS software available are: Oracle, MySQL, Sybase, Ingress
❖ Degree : Number of attributes/ columns in a relation is the degree of
that relation

❖ Cardinality : Number of tuples/ rows in a relation is the cardinality of


that relation

❖ A primary key : An attribute or column that uniquely identifies each


record in a table. It does not have duplicate values or null values.

❖ Candidate Key: An attribute or column that has the ability to become a


primary key. A Primary Key is one of the candidate keys. A table may
have more than one candidate keys but definitely has one and only one
primary key.
Review of
MySQL
❖ Alternate Key: A table can have multiple choices for a primary key but
only one can be set as the primary key. All the keys which are not
primary key are called an Alternate Key.

❖ FOREIGN KEY is a column that creates a relationship between two


tables. It is a field in the table that is the primary key of another table.
Review of
MySQL
MySQL is an open source and freely available RDBMS that uses SQL.
It can be downloaded freely from www.mysql.org.

Categories of SQL commands:


Review of
MySQL
Categories of SQL commands:

DDL (Data Definition Language)Commands in SQL are


the type of commands used to create, modify or alter
the table's structure in a relational database
management system. It can modify the schema of the
database and can control how data will look like.
Review of
MySQL
Categories of SQL commands:

DML Commands stand for Data Manipulation


Language commands. These commands are used to
modify the data in the table. In MySQL, they are used
to insert, update and remove data present in the
database tables, views, etc.
Review of
MySQL

Difference between DDL and DML

DDL DML
1. DDL stands for Data DML stands for Data
Definition Language Manipulation Language
2.DDL is used to create the DML is used to populate and
database schema manipulate the data in the table
3.The DDL language is used to The DDL language is used to
change the structure of the manage the data in the database.
database.

4. Example: CREATE,ALTER Example: INSERT,DELETE,


TABLE, DROP UPDATE
Review of
MySQL
Review of
MySQL

COMMANDS DESCRIPTION SAMPLE QUERY


CREATE Used to create table or CREATE DATABASE School;
databases
USE Used to open a database USE SCHOOL;
SHOW DATABASES Used to get a list of the SHOW DATABASES;
available databases
DROP DATABASE Used to delete a database DROP DATABASE School;

SELECT DATABASE(); Used to show the name of SELECT DATABASE();


currently open database
Review of
MySQL
Review of
MySQL

COMMANDS DESCRIPTION SAMPLE QUERY


CREATE TABLE < Table Used to create a table CREATE TABLE Learner(RollNo
INTEGER,
Name>(<Col name1> with the structure
<data type>[(size)],….); given Name VARCHAR(25));

SHOW TABLES; Used to show a list of Show tables;


tables in the current
database
DROP TABLE <Table Name>; Used to remove a DROP TABLE STUDENT;
table from the
database
INSERT INTO <TABLE Used to insert INSERT INTO TABLE
NAME> VALUES (VALUE1, records to a table LEARNER(101,”Raj”);
VALUE2, ….)
Review of
MySQL

COMMANDS DESCRIPTION SAMPLE QUERY


DESCRIBE <TABLE Used to view the DESCRIBE LEARNER;
NAME>; structure of the table
SELECT <COLUMN Used to retrieve the SELECT ROLLNO,NAME
NAME1,COLUMN NAME2, selected FROM LEARNER;
….> FROM <TABLE columns/attributes
NAME> from a table
ALTER TABLE <TABLE NAME> Used to add a column ALTER TABLE LEARNER
ADD <COLUMN to the table ADD MARKS INTEGER;
NAME><DATA TYPE>

ALTER TABLE <TABLE Used to change the ALTER TABLE LEARNER


NAME> data type of a column MODIFY ROLLNO
MODIFY <COLUMN VARCHAR(5);
NAME><DATA TYPE>
Functions in
MySQL

SELECT command is used to retrieve information from one or


more databases
It will follow the words like keywords, clause and statements

Keyword – Refers to an individual SQL statement… SELECT


and FROM
Clause is a part of SQL statement ie., SELECT tname,tno,…is
a clause
Statement is a combination of two or more clauses ie., SEELCT
* FROM teacher is a SQL statement
Review of
MySQL

COMMANDS DESCRIPTION SAMPLE QUERY


ALTER TABLE <TABLE NAME> Used to delete a ALTER TABLE LEARNER
DROP <COLUMN NAME> column from the DROP MARKS;
table
ALTER TABLE <TABLE Used to rename a ALTER TABLE LEARNERS
NAME> column CHANGE ROLLNO SNO
CHANGE <OLD COLUMN INT;
NAME> <NEW COLUMN
NAME>

DELETE FROM <TABLE Used to remove all DELETE FROM LEARNERS;


NAME> [WHERE the records of the
<CONDITION>] table ,if no condition
is given
Review of
MySQL

CLAUSE DESCRIPTION SAMPLE QUERY


FROM FROM clause states which table to SELECT * FROM
look in for data. LEARNERS;
WHERE WHERE clause is used with SELECT SELECT NAME FROM
to retrieve records based on LEARNERS WHERE
condition MARKS>90;
Review of
MySQL

ARITHMETIC RELATIONAL LOGICAL


OPERATORS OPERATORS OPERATORS

+ > < AND


- <>
OR
*
>=
/ NOT
% <=
Renaming of columns
The ‘AS’ keyword is used for column alias to
rename a column in the SELECT query for
display purposes.
Syntax :
SELECT <COLUMN NAME 1> AS <NEW
CLOUMN NAME>, <COLUMN NAME 2> AS
<NEW COLUMN NAME>,…FROM TABLE
NAME;
EXAMPLE:
SELECT NAME, EXPERIENCE+10 AS “TOTAL
EXPERIENCE” FROM DOCTOR;
ALTER TABLE COMMAND
To remove a column
Syntax:
ALTER TABLE Students
DROP COLUMN age ;
Example:
ALTER TABLE Students
DROP column age;
To remove primary key constraints
ALTER TABLE Students
DROP primary key;
ALTER TABLE COMMAND
Adding and deleting Primary Key constraints:
We can add or delete Primary Key constraint using
ALTER TABLE command even if the table has already
been created.
To add a Primary Key constraint on the column
Emp_ID in the table Employee, the statement will
be:
mysql> ALTER TABLE EMPLOYEE ADD
PRIMARY KEY(Emp_ID);
To delete a Primary Key constraint from the table
Employee, the statement will be:
mysql> ALTER TABLE EMPLOYEE DROP
PRIMARY KEY;
ALTER TABLE COMMAND TO ADD FOREIGN KEY

Consider the table STUDENT and GUARDIAN:


Syntax:
ALTER TABLE Student
ADD FOREIGN KEY (GUID)
REFERENCES GUARDIAN (GUID)
ORDER BY CLAUSE :

Sorting records
Order by clause is used with SELECT statement in the query
to sort the data in ascending or descending order of one or
more columns.
This is important to note that the data in table is not sorted, only the results that appear on the
screen are sorted.

Syntax:
SELECT <column name> [,<column name>, ….] FROM <table name>
[WHERE <condition>]
[ORDER BY <column name> [, <column name>…]];
Example:
(Sorting on single column)
SELECT * FROM EMPL ORDER BY ENAME;
Example :
(Sorting on Multiple columns)
SELECT * FROM EMPL ORDER BY ENAME, JOB;
BETWEEN OPERATOR

The BETWEEN operator defines the range of values


in which the column value must fall into, to make the
condition true.
It includes both the upper limit and lower limit
Syntax :
SELECT <COLUMN NAME 1> , <CLOUMN NAME2>
FROM TABLE NAME WHERE <COLUMNNAME>
BETWEEN <RANGE1> AND <RANGE2>;
EXAMPLE:
SELECT NAME,EXPERIENCE FROM DOCTOR
WHERE EXPERIENCE BETWEEN 20 AND 30;
Substring pattern matching
The LIKE operator in MySQL can be used with WHERE
clause to search for a specified pattern in a column.
The LIKE operator makes use of the following two wild
card characters:
❖% (percent)— used to represent zero, one, or
multiple characters
❖_ (underscore)— used to represent a single
character
Syntax :
SELECT <COLUMN NAME 1> , <CLOUMN NAME2>
FROM TABLE NAME WHERE <COLUMNNAME> LIKE
“%s”
EXAMPLE:
SELECT * FROM EMPLOYEE
WHERE Ename LIKE 'K%';
Substring pattern matching
Data Updation
The UPDATE statement is used to make such
modifications in the existing data.
Syntax:
UPDATE table_name
SET attribute1 = value1, attribute2 =
value2, ... ;

EXAMPLE:
UPDATE STUDENT
SET GUID = 101
WHERE RollNumber = 3;
Data Deletion
The DELETE statement is used to delete one or more
record(s) from a table.
Syntax:
DELETE FROM table_name
WHERE condition;

EXAMPLE:
DELETE FROM STUDENT WHERE RollNumber = 2;
Note:
Be careful to include WHERE clause while using DELETE statement to
delete records in a table. Otherwise, all the records in the table will
get deleted.

The DROP TABLE statement is used to remove the entire table from the
database along with the records
Syntax:
DROP TABLE table_name;

EXAMPLE:
DROP TABLE STUDENT;
Inserting NULL
mysql>INSERT INTO Student(Rollno, Name,
Gender, Marks, DOB)
VALUES(12,'Swati Mehra', 'F', NULL, NULL);
Eliminating Duplicate/Redundant Data
DISTINCT clause
➢ DISTINCT clause is used to remove
duplicate rows from the results of a
SELECT statement. It is used to retrieve
only unique values for a column in the
table.
➢ The DISTINCT keyword can be used
only once with a given SELECT statement.
Syntax:
SELECT DISTINCT <column-name> from
<table-name>;
Handling NULL Values
NULL represents a missing or unknown value.
For example, the village column in a table called address
will have no value for cities.
Hence, NULL is used to represent such unknown values. It is
important to note that NULL is different from 0 (zero).
Also, any arithmetic operation performed with NULL value
gives NULL.
For example, 100 + NULL = NULL because
NULL is undefined and unknown and,
hence, the result is also undefined.
In order to check for NULL value in a column, we use IS NULL
operator.
Handling NULL Values
Display details of all those students who have
not been awarded any marks.

mysql>SELECT * FROM STUDENT


WHERE Marks IS NULL;
Handling NULL Values
Display details of all those students who have
been awarded some marks.

mysql>SELECT * FROM STUDENT


WHERE Marks IS NOT NULL;
Sample data is given for STUDENT table. Answer the queries that follow.
Sample Data in Student Table:
ROLL NO SNAME GENDER DOB HOUSEID FEES HOBBY
1001 RAVI M 2002‐01‐20 10 850 HOCKEY
1002AMAR M 2001‐03‐20 11 550 SOCCER
1003 SUJA F 2004‐11‐25 10 650 KARATE
1004 RUMA F 2003‐12‐31 12 650 SKATING
1005 SIJU M 2002‐09‐11 13 550 KARATE
1006 ARUNA F 2001‐12‐20 10 750 HOCKEY
1007 HYDER M 2004‐09‐18 11 850 NULL
1008 RAINA M 2005‐08‐21 12 850 SOCCER
i. Write SQL query to display the details of STUDENT table in the descending order
of the FEES.
ii. Write SQL query to display the SNAME, GENDER and FEES for all the students
whose HOUSEID is either 10 or 11 or 13.
iii. Write SQL query to display the SNAME, FEES and HOBBY for all the students who
do not have a hobby.
iv. Write SQL query to display the SNAME and GENDER for all the students who are
paying fees in the range of 600 to 800.
v. Write SQL query to display the ROLLNO and SNAME for all the students whose
SNAME is ending with ‘A’.
vi. Write SQL query to display the STUDENT details whose year of birth is 2002. vii.
Update the FEES by increasing Rs. 1000 for female student.
viii. SELECT MAX(FEES) from student; ix. SELECT COUNT(DISTINCT(HOBBY) ) FROM
Sample data is given for STUDENT table. Answer the queries that follow.
Sample Data in Student Table:
ROLL NO SNAME GENDER DOB HOUSEID FEES HOBBY
1001 RAVI M 2002‐01‐20 10 850 HOCKEY
1002 AMAR M 2001‐03‐20 11 550 SOCCER
1003 SUJA F 2004‐11‐25 10 650 KARATE
1004 RUMA F 2003‐12‐31 12 650 SKATING
1005 SIJU M 2002‐09‐11 13 550 KARATE
1006 ARUNA F 2001‐12‐20 10 750 HOCKEY
1007 HYDER M 2004‐09‐18 11 850 NULL
1008 RAINA M 2005‐08‐21 12 850 SOCCER
Chapter 1 Functions in
Querying & MySQL
SQL Functions

♣ To learn More on MySQL

♣To learn about aggregate or group


functions

♣How aggregate functions works on


NULL

♣How aggregate functions works on


groups
Functions in
MySQL

What is a function ?
A set of predefined codes to do a specific task and return a
zero or more values.A function is used to perform some
particular task and it returns zero or more values as a
result.
What are the two categories of functions you have already
learnt?
➢ Single Row
➢ Multiple Row functions
What are single row functions?
➢ Single row functions works on a single row to return a
single value
Functions in
MySQL

What are multiple row functions?


➢ Multiple row functions works on a multiple rows to return a single
value
Functions in
MySQL

Mention few examples of single row functions.


❖SUBSTR( )
❖ROUND( )
❖TRIM( )
❖CONCAT( )
Can you think of any functions that work on
multiple rows?
❖MIN( )
❖MAX( )
❖SUM( )
❖AVG ( )
Functions in
MySQL
Functions in Single row functions: Numeric
MySQL

❖POWER( ) - returns the value of a number


raised to the power of another number
➢Syntax: POWER(M,N);
Functions in Single row functions: Numeric
MySQL

ROUND( ) - rounds a number specified as an


argument up to a number specified as another
argument.
Functions in Single row functions: Numeric
MySQL

Write the output of the following :

1.SELECT ROUND(345.156, 0);


2.SELECT ROUND(20.5);
3.SELECT ROUND(20.5, 0);
4.SELECT ROUND(-10.5);
5.SELECT ROUND(-4.53);
6. SELECT ROUND(-4.535,2);
7. SELECT ROUND(34.4158,-1);
8. SELECT ROUND(4.43);
9. SELECT ROUND(100.61) AS Rounded_Number;
10. SELECT ROUND(1567.1100,3) AS Rounded_Number;
Functions in Single row functions: Numeric
MySQL

ROUND( ) function
Functions in Single row functions: Numeric
MySQL

1. Let us now add a new column Commission to the SALE table. The
column Commission should have a total length of 7 in which 2 decimal
places to be there.
2. Let us now calculate commission for sales agents as 12 per cent of the
SalePrice, insert the values to the newly added column Commission
3.Display records of the table SALE where commission > 73000.
4. Display the salesprice and commission rounded to 1 decimal place
Functions in Single row functions: Numeric
MySQL

3. Display InvoiceNo, SalePrice and Commission such


that commission value is rounded off to 0.
Functions in Single row functions: Numeric
MySQL

MOD( ) -Returns the remainder after dividing number


A by number B.
Syntax:
SELECT MOD(21, 2);
Output:
1
Constraints

➢ Constraints are certain types of restrictions on the data values that an


attribute can have.
➢ They are used to ensure the accuracy and reliability of data.

Commonly used SQL Constraints


Functions in Single row functions: Numeric
MySQL

❖ TRUNCATE( ) -returns a number after truncated to


certain decimal places. The number and the number of
decimal places are specified as arguments of the
TRUNCATE function.
➢Syntax: truncate(N,D);
Functions in Single row functions: Numeric
MySQL
EMP

Write a query to display the


salary rounded off as “Rounded
Salary” from the table given
Functions in
MySQL
1. LENGTH( ) - returns the length of a given string
➢Syntax: Select length(str)

2. Upper(str) or UCASE( str) –returns the string in


upper case

3. LOWER(str) or LCASE (str) – returns the string


in lowercase
4. TRIM( ) – Returns the string after removing
the trailing and leading spaces
Functions in
MySQL
5. LTRIM(string) - Returns the given string after
removing leading white space characters.

6. RTRIM(string) - Returns the given string after


removing trailing white space characters.

7.LEFT(String,n) – Returns the ‘n’ number of


characters from left of the string

8.RIGHT(String,n) – Returns the ‘n’ number of


characters from right of the string
Functions in Single row functions: String Functions
MySQL
EMP

Write the output of the following:


1) SELECT LENGTH(EMP_NAME) FROM
EMP;
2) SELECT RIGHT(EMP_NAME,3) FROM
EMP;
3) SELECT LEFT(EMP_NAME,2) FROM EMP;
Functions in Single row functions: String
MySQL
9. SUBSTR( ) → returns the specified number of
characters from a particular position of a given
string.
➢ Syntax:
SUBSTR(STR,POSITION,No.OfCharacters)
Functions in
MySQL
10. CONCAT( ) – Adds or joins two or more strings
➢Syntax: concat(String1,String2, String3,…)
Functions in
MySQL
11. INSTR(string,substring) -Returns the position
of the first occurrence of the substring in
the given string.
➢ Returns 0, if the substring is not present in the
string.
➢Syntax: INSTR(string,substring)
Functions in
MySQL

LIBRARY
Write the output for the query given:
1. SELECT book_name,
INSTR(book_name,'an') FROM
LIBRARY WHERE
INSTR(book_name,'an')>0;
Functions in Single row functions: Numeric
MySQL
CUSTOMER

Write the SQL queries based on the table given:


1) Display customer name in lower case and customer email in upper case from table
CUSTOMER.
2) Display emails after removing the domain name extension “.com” from emails of the
customers
3) Display details of all the customers having yahoo emails only.
4) Display the length of the email and part of the email from the email ID
before the character ‘@’. Note – Do not print ‘@’
5) Convert the Customer name to uppercase if its value starts with the letter ‘R’.
Functions in Single row functions: Numeric
MySQL

Answers :
1. SELECT LOWER(CustName), UPPER(Email) FROM CUSTOMER;

2. SELECT TRIM(“.com” from Email) FROM CUSTOMER;

3. SELECT * FROM CUSTOMER WHERE Email LIKE "%yahoo%";

4. SELECT LENGTH(Email), LEFT(Email, INSTR(Email, "@")-1) FROM


CUSTOMER;

5. SELECT UPPER(CUSTNAME) FROM CUSTOMER WHERE CustName LIKE


“R%";
Functions in Single row functions: Numeric
MySQL

Write the output produced by the following SQL commands:


a) SELECT POW(2,3);
b) SELECT ROUND(123.2345, 2), ROUND(342.9234,-1);
c) SELECT LENGTH("Informatics Practices");
d) SELECT LEFT("INDIA",3), RIGHT("Computer Science",4);
f) SELECT MID("Informatics",3,4), SUBSTR("Practices",3);
Functions in Single row functions: Date and Time
MySQL
❖ CURDATE() – Returns the current date in
YYYY-MM-DD or YYYYMMDD
Syntax : SELECT CURDATE()
❖ DATE() – Returns the date part of a date and time
expression
➢ Syntax : SELECT DATE(‘2010-04-12 01:02:03’);
Result : 2010-04-12
❖ MONTH(date) – Returns the numeric month from the date
passed
➢ Syntax : SELECT month(‘2010-04-12 01:02:03’);
Result : 4
YEAR(date) – Returns the year for the date passed in the
range 0 to 9999
➢ Syntax : SELECT year(‘2010-04-12 01:02:03’);
Result : 2010
Functions in Single row functions: Date and Time
MySQL
➢ DAY() – Returns the day part from the date.
YYYY-MM-DD or YYYYMMDD
❖ Syntax : SELECT DAY(‘2010-04-12’)
Result : 12
❖ DAYNAME(date) - Returns the name of the day from
the date
➢ Syntax : SELECT DAYNAME(‘2021/05/1’);
Result : Saturday
❖ MONTHNAME(date) – Returns the month name from the
specified date
➢ Syntax : SELECT monthname(‘2010-04-12’);
Result : April
NOW( ) – It returns the current system date and time.
➢ Syntax: SELECT NOW();
Output: 2019-07-11 19:41:17
Functions in Single row functions: Date and Time
MySQL

➢ Difference Between SYSDATE() and NOW()


Both functions return the current date and time.
However, here's where they differ:
➢ SYSDATE() returns the time at which it executes.
➢ NOW() returns a constant time that indicates the time at which the
statement began to execute
➢ What is the difference between NOW() and CURDATE()

Do as directed :
1. Take the input as todays date and display in the format :
Wednesday,9 November 2022
Functions in Single row functions: String Functions
MySQL

Write the name of the functions to perform the following


operations:
i) To display the day like “Monday”, “Tuesday”,from the
date when India got independence.
ii) To display the specified number of characters from a
particular position of the given string.
iii) To display the name of the month in which you were
born.
iv) To display your name in capital letters.
Functions in Single row functions: Date and Time
MySQL

Write SQL queries for the following:


1) Display the name of the day on which the employee was born
2) Display the month of joining for employees who have ‘J’ in their name
3) Display the employee ID ,employee name and designation whose salary is greater
than 30000 and are salesman
4) Display the years of service as ‘Service in years’ for all employees as on today
5) Display designation of employee and the position of character ‘e’ in designation,
if present.
Aggregate Multiple Row Functions
Functions
Sl.N Name of the Purpose
o. function
1. MAX() Returns the MAXIMUM of the values
under the specified column/expression
2. MIN() Returns the MINIMUM of the values
under the specified column/expression
3. AVG( ) Returns the AVERAGE of the values
under the specified column/expression
4. SUM( ) Returns the SUM of the values under the
specified column/expression
5. COUNT(*) Returns the number of records in the
table
6. COUNT(column) Returns the COUNT of the number of
values under the specified column
ignoring the NULL values
Working on Aggregate
Functions
Consider the table EMP having the following records:

EMP
CODE NAME SAL
E1 Ram Kumar 4000
E2 Suchitra 4500
E3 Yogendra 3000
E4 Sushil 3500
E5 Rajesh 4000

mysql> SELECT SUM(SAL) FROM EMP; 19000

mysql> SELECT MIN(SAL) FROM EMP; 3000

mysql> SELECT MAX(SAL) FROM EMP; 4500

mysql> SELECT AVG(SAL) FROM EMP; 3800


Aggregate Functions
and NULL values
Consider the table EMP having the following records:

EMP Aggregate functions ignores


CODE NAME SAL NULL values i.e. NULL values
does not play any role in
E1 Ram Kumar NULL calculations.
E2 Suchitra 4500
E3 Yogendra NULL
E4 Sushil 3500
E5 Rajesh 4000
mysql> SELECT SUM(SAL) FROM EMP; 12000

mysql> SELECT MIN(SAL) FROM EMP; 3500

mysql> SELECT MAX(SAL) FROM EMP; 4500

mysql> SELECT AVG(SAL) FROM EMP; 4000


THE DIFFERENCE BETWEEN COUNT(*)
AND COUNT(COLUMN NAME)
Consider the table EMP having the following records:

EMP
CODE NAME SAL
E1 Ram Kumar NULL
E2 Suchitra 4500
E3 Yogendra NULL
E4 Sushil 3500
E5 Rajesh 4000
mysql> SELECT COUNT(*) FROM EMP; 5

mysql> SELECT COUNT(SAL) FROM EMP; 3

➢ COUNT(column_name) returns the number of non- NULL


NOTE values in that column.
➢ If the argument is a *, then COUNT( ) counts the total
number of rows satisfying the condition, if any, in the table
COUNT(DISTINCT(COLUMN NAME))
➢ The keywords DISTINCT and COUNT can be used together to count
the number of records without taking duplicate values
➢ Syntax: SELECT COUNT(DISTINCT(column_name)) FROM
<table_name>;
Consider the table STUDENT having the following records:

STUDENT
ROLL_NO NAME STREAM
101 Ankit Sharma Science
102 Payal Goel Commerce COUNT(DISTINCT(STREAM))
103 Gurpreet Kaur Humanities OUTPUT
3
104 Radhika Science
105 Akhay Dureja Commerce

mysql> SELECT COUNT(DISTINCT(STREAM)) FROM STUDENT;


Lab Activity:
Lab Activity:
Consider the table Shoes:

Write MySQL queries :


1. To find the highest cost of any type of shoe in the factory.
2. To find the highest cost of any shoe of type 'School'.
3. To find the highest selling price of any type of shoe.
(where SP =cost + cost*margin/ 100 )
4. To find the highest selling price of any type of shoe rounded to 2 decimal
places.
5. To count the different types of shoes that the factory produces
6. To count the total number of records in the table Shoes.
Lab Activity:
Consider the table HOSPITAL:

Gender
Lab Activity:

Write MySQL queries :


1. To find the total charges of those patients who are admitting in
Orthopaedic department.
2. Display the sum of charges of various departments.
3. Display the average charges of female patients.
4.Display the total charges of all patients whose date of admission is
before 12/08/98
5. Display the maximum age of male patients
6.Display the count of various departments in the hospital
7. To display the various departments in the hospital
8.Display the count of male patients form hospital table
9. To show all information about the MALE patients of cardiology
department
10. To display Patient’s name, charges, Age for female patients.
11. To count the number of patients with Age < 30.
12. Increase the charges of male patient in ENT department by 4%.
13. To show the name of those patients who have first alphabet as ‘S’
and third alphabet as ‘n’ from hospital table
LEARNING OBJECTIVE

♣To learn about ORDER BY clause


♣ Sorting data on multiple columns
♣Sorting on column alias
♣To learn about GROUP BY clause in
aggregate functions
♣How aggregate functions works on
groups
♣How to retrieve data from groups
based on the criteria given
Order By clause

Order By : Is used to sort the data in a table in


ascending or descending order
Syntax:
SELECT <COLUMN LIST> FROM <TABLE NAME>
[WHERE <CONDITION>]
ORDER BY <COLUMN NAME> [ASC/DESC];
AGGREGATE FUNCTIONS AND GROUP BY CLAUSE

GROUP BY
GROUP BY clause is used in SQL to group the rows on the basis
of common values in a column
Syntax:
SELECT <COLUMN NAME>,<AGGREGATE FUNCTION>
FROM <TABLE NAME>
GROUP BY <COLUMN NAME>
Example :
HAVING Clause
HAVING Clause is used to specify conditions on the rows with
GROUP BY clause.
Syntax:
SELECT <COLUMN LIST> FROM <TABLE NAME>
GROUP BY < COLUMN NAME> HAVING CONDITION;
GROUP BY Clause
SALE

2. Display the number of people in each category of payment mode from the
table SALE.
SELECT PaymentMode, COUNT(PaymentMode) FROM SALE GROUP BY
Paymentmode ORDER BY Paymentmode;
HAVING Clause
SALE

1. Display the customer Id and number of cars purchased if the customer


purchased more than 1 car from SALE table.
SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING Count(*)>1;
LAB ACTIVITY - PRACTICALS
Consider the table EMP:

EMP
CODE NAME SAL DEPT
E1 Ram Kumar NULL Sales
E2 Suchitra 4500 Accounts
E3 Yogendra 2000 Sales
E4 Sushil 3500 Accounts
E5 Rajesh 7000 IT
E6 Ranbir 5000 Operations
E7 Suhas 4000 IT

Write queries :
➢ To display the minimum and maximum salary of the employees
department wise
➢ To display the total salary of employees in each department
➢ To display the number of employees in each department
Worksheet:
Write a query to display the names of the shoes in the
ascending order of price
Practical applications:
The need for the following reports:
1. The management of the school may want to know
what is the total salary of teachers of various
departments. i.e., what is the total salary of
teachers in each department
2. The management may also want to know what is
the maximum, minimum salary of teachers in
each of these departments.
3. It may also be required to find the total number
of teachers in each department.
AGGREGATE FUNCTIONS AND GROUP BY CLAUSE
Consider the table HOSPITAL:

Eg. SELECT dept, sum(charges) from HOSPITAL GROUP BY dept;


Dept sum(charges)
Surgery 700
Orthopedic 400
ENT 550
Cardiology 1600
Gynecology 500
Medicine 400
AGGREGATE FUNCTIONS AND GROUP BY CLAUSE
Note:
❖ Group By is always used in conjunction
with some aggregate function(s)
❖ A SELECT command with GROUP BY
clause has a column name and one or
more aggregate functions which are
applied on that column and grouping is
also done on this column only.
❖ Eg. SELECT DEPT,COUNT(*)
FROM HOSPITAL
GROUP BY DEPT;
What will be the output of the
above command?
A quick Recap : Consider the table Orders:

Write the output for the queries given :


1. SELECT cust_code, SUM(order_qty) FROM orders GROUP BY
cust_code;

2. SELECT shoe_code, SUM(order_qty) FROM orders GROUP BY


shoe_code;
CONDITIONS ON
GROUPS

Sometimes we do not use the whole output


produced by the GROUP BY clause

Eg. SELECT type, SUM(qty) FROM shoes


GROUP BY type;
Output :
CONDITIONS ON
GROUPS
Now suppose we are interested in viewing only
those types of shoes whose total quantity is more
than 1500

Can you write the query ?

Output :
Using WHERE and
HAVING with GROUP BY
Now the management of the shoe factory may want to
know what is the total quantity of shoes, of sizes other
than 6, of various types. i.e., what is the total quantity of
shoes (of sizes other than 6) of type School, Office, and
Sports each whose total quantity greater than 1500.
Query :
SELECT type, SUM(qty) FROM shoes
where size<>6 Condition on individual rows /
GROUP BY type Checks individual rows

HAVING SUM(qty) > 1500;


Condition on individual groups / checks
individual group
WHERE Vs HAVING

Difference between WHERE and HAVING :

WHERE Vs HAVING:
WHERE is used to put a condition on individual row of
a table whereas HAVING is used to put condition on
individual group formed by GROUP BY clause in a
SELECT statement.

You might also like