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

IP XII U2 Ch5 MySQL

Uploaded by

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

IP XII U2 Ch5 MySQL

Uploaded by

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

Informatics Practices Revised

as per
CBSE
Class XII (CBSE Board) Curriculu
m 2021-
22

UNIT-2: Database Query using SQL

Chapter: 5
Relational Database
& Query using
MySQL
Visit
Authoredwww.ip4you.blogspot.com
By:- Rajesh Kumar Mishra, PGT (Comp.Sc.)
Kendriyafor more….
Vidyalaya Khanapara, Guwahati (Assam)
e-mail : [email protected]
Expected Learning
Outcome:
CBSE Syllabus (2021-22) Covered in this presentation:
 Math functions: POWER (), ROUND (), MOD ().
 Text functions: UCASE ()/UPPER (), LCASE ()/LOWER (), MID
()/SUBSTRING ()/SUBSTR (), LENGTH (), LEFT (), RIGHT (), INSTR (),
LTRIM (), RTRIM (), TRIM ().
 Date Functions: NOW (), DATE (), MONTH (), MONTHNAME (), YEAR (),
DAY (), DAYNAME ().
 Aggregate Functions: MAX (), MIN (), AVG (), SUM (), COUNT (); using
COUNT (*).
 Querying and manipulating data using Group by, Having, Order by.

In this presentation you will learn about Relational Database and


MySQL query.
 Revision of important topics of class XI.
 Working with DDL & DML commands of MySQL.
 MySQL functions (Math Functions, Text functions, Date functions and
aggregate functions)
 Using Group by and Order by clause in query.
Revision of important topics of Class XI

What is the Database?


 A database is an organized collection of interrelated data
stored together to serve applications. It work like a
container which may contains various database objects.
 Most of the databases store data in the form of Relations
(also called Tables). Such Databases are known as
Relational Database.
 A Software used to store and manage Relational database
is called RDBMS (Relational Database Management
System).
•Tables
Database
Some Commonly used RDBMS •Queries
•Views
software are- Oracle, MySQL, •Index
MS SQL Server, SyBase
and Ingress, SQLite etc.
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Advantages of Database
System.
 Databases reduces Redundancy
It removes duplicity of data because data are kept at one place
and all applications refers to the centrally maintained database.
 Database controls Inconsistency
Inconsistency is an undesirable situation, when two copies of
the same data do not agree to each other and leads ambiguity.
The inconsistency is also controlled by controlling redundancy.
 Database facilitate Sharing of Data
The data stored in the database can be shared among several
users and application programs simultainiously.
 Database ensures Security
Data are protected against accidental or intentional disclosure
to unauthorized person or unauthorized modification.
 Database maintains Integrity
DBMS enforces some integrity rules to insure the validity or
correctness of data. For example, a date can’t be entered like
25/25/2020, since it is invalid.
Concept Relational Data
Model
Data model describes ‘How data is organized or stored’ in
the database. A Database can be organized on the following Data
models-
 Relational Data Model
 Network Data Model
 Hierarchical Data Model
 Object Oriented Data Model
The Relational Data Model is mostly used by RDBMS software, in
which data is organized into Relation or Tables containing Rows and
Columns. A row is also known as Tuple or Record and a column is
called Attribute or Field.
Attribute (Field) Relational Model

Name Address DOB City Phone ntity


E ecord)
(R
Amar 2/3 Vijay 01.04.199 GUWAHATI 12345
Nagar 0
Kailash 22 Katra Table 23.10.199
(Relation) Lucknow 67890
2
Relational Data Model- Terminology
 Relation (Table)
A Relation or Table is Two-Dimensional structure arranged in Rows
and Columns. It has the following properties-
 Column homogeneous- All values in a column are of same data
type.
 Unique columns- Each column assigned a unique name and must
have atomic (indivisible) value.
 Unique rows- All rows of a relation are distinct i.e. no two identical
rows (records) can exist in the Relation (Table).
 Domain
It is collection (set) of possible values from which the value for a
column is derived.
 Tuple/ Entity/ Record : A Row of a table is called Tuple or
Record.
 Attribute/ Field: A column of a table is called Attribute or
Field.
 Degree : Number of columns (attributes) in a table.
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Concept of
Keys
As, you know that all records in a relation/table must be unique i.e. two
identical records having same value for all columns are not allowed in
the table. So at least one column must have different (unique) value for
all records. A column or combination of columns which has unique values
also identifies a record in the table. Such column(s) is called Key of the
Table.
A key attribute identifies the record and must have unique value.
Consider the following two students having same name and other details
studying in a class, but they must have different Admission Number. So
ADM-No is considered as Key, since it identifies a record uniquely.

Value of Admission
Number is unique i.e. it ADM_NO Name Class Stream Subject
can’t be same for any two 1224 Amar 12 Science Comp.Sc
records in the table, even
they can have same 2456 Amar 12 Science Comp.Sc.
values for other columns.
Types of Keys
A table may have several columns having unique value in the
table. For example in a Admission number and Roll number
both are unique in a class.
Even a combination of columns like Name+Father Name or
Name+Date of Birth may have unique value and these group
of columns may also considered as keys.
So, a relation/table may have multiple keys which are having
distinct values and can identify a record uniquely.
As per utility and applicability of Key columns in the Database,
Keys can be categorized as-
 Primary Key
 Candidate Key
 Alternate Key
 Foreign key
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Types of Keys
 Primary Key : A set of one or more attributes (column) which is
used to identify or search a record in the relation at first preference
is called Primary Key.
 Candidate Key : Some times, a table may have multiple keys
which can identify a record in a table. All such columns are called
Candidate Keys because they all are having candidature to become
as Primary key. So, Primary Key is one of the candidate keys.
A table may have several candidate keys but definitely has only one
primary key.
 Alternate Key : A Candidate Key that is not a Primary key
is called Alternate key, since it can be used in place of primary
key.
 Foreign Key: A Foreign key is non-key column in a table whose
value is derived from the Primary key of some other table. Foreign
Key establishes relationship among two tables. It maintains
Referential integrity, since each time when a record is inserted or
updated in the table, the other table is referenced.
Example of Keys:
Consider the following Student Table containing records of students
in a class. The RollNo, AADHAR_No and Adm_No columns are
having unique values. So, we can consider-
Candidate Keys– Adm_No, AADHAR_No and RollNo
Primary Key – Roll No (Commonly used at first preference)
Alternate Key – Adm_No, Aadhar_No
Adm_No AADHAR_ No RollNo Name Class Marks
2301 45782154 1 Seema Chauhan 12 15
1501 47869852 2 Ajay Kumar 12 23
1678 26845783 3 Vansh Pratap 12 20
7003 85674281 4 Ajay Kumar 12 15

Primary EMPLOYEE DEPARTMENT Primary


key EmpID key
DeptNo
Name
DeptName
City
Foreign Sal
Key HeadName
DeptNo
Location
MySQL- Introduction
MySQL is an open source, free and powerful Relationa
Database Management System l based
SQL. The main
(RDBMS) features of MySQL are -
software on
 Open Source & Free of Cost: It is Open Source and available free
of cost. It is part of LAMP (Linux, Apache, MySQL, PHP/ Perl/
Python) Open Source S/w group.
 Portability: It can be installed and run on any types of Hardware
and OS like Linux, MS Windows or Mac etc.
 Security : It offers security and authorization feature to
keep database secure.
 Connectivity : The MySQL database can be connect using different
protocols and Programming Languages like Python, Java etc.
 Query Language : It uses SQL (Structured Query Language)
as query language, which is standardized by ANSI.

SQL (Structured Query Language) is widely used


standard
Query language that enables you to manage a relational
database where as MySQL is a RDBMS Software based on SQL.
Types of SQL Commands
MySQL
Commands

DDL DML TCL DCL


CREATE SELECT COMMIT GRANT

ALTE INSERT ROLLBACK REVOKE


R
DELETE SAVEPOINT
DROP

UPDAT DDL: Database & Table level


E DML: Record level
TCL: Transaction level
DDL & DML are basic categories
DCL: Security & Privacy level
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Data types in
MySQL
Numeric Data Types:
 INTEGER / INT – up to 11 digit number without decimal.
 SMALLINT – up to 5 digit number without
decimal.
 FLOAT (M,D) / DECIMAL(M,D) / NUMERIC(M,D)
Stores Real numbers upto M digits with D
decimal places.
e.g. Float (9,2) can store 1234567.89
 Date & Time Data Types:
 DATE - Stores date in YYYY-MM-DD format.
 TIME - Stores time in HH:MM:SS format.
 String or Text Data Type:
 CHAR(Size) :
A fixed length string up to 255 characters. (default is 1)
 VARCHAR(Size) :A variable length string up to 65535
Char, Varchar, Date and Time values should be enclosed with single (‘ ‘) or
characters.
double ( “”) quotes in MySQL.
Database Handling commands in
MySQL
 Creating a Database.
The following command will create School database in MySQL.
mysql> CREATE DATABASE School;
 Opening a database
To open an existing database, following command is used.
mysql> USE school ;
 Getting listings of database and tables
mysql> SHOW DATABASES;
mysql> SHOW TABLES;
 Deleting a Database and Table
mysql> DROP DATABASE
School; mysql> DROP TABLE
Student;
 Viewing Table Structure
mysql> DESCRIBE Shows the name of
S
Student; currently
e open database
l
Visit www.ip4you.blogspot.com for more teaching-learning materials...
e
Working with MySQL Tips: Remember
N-D-S-C
N-Name, D- Data type,
 Creating Simple Tables: S- Size, C- Constraints
CREATE TABLE < Table Name>
(<Col name1><data type>[(size)] [Constraints],….);
Data types- INTEGER, NUMERIC(P,D), CHAR(n), VARCHAR(n), DATE etc.
mysql> CREATE TABLE Emp (empID integer,ename
char(30),
city char(25), pay decimal(10,2));
All commands
in MySQL
are ended
with ;

Emp
empID ename city pay
Creating Tables with
Constraints
An Integrity Constraints or Constraints are the rules, condition
or checks applicable to a column or table which ensures the
integrity or validity of data.
The following constraints are commonly used in MySQL.
S.N Constraints Description
1 NOT NULL Ensures that a column cannot have NULL value.
2 DEFAULT Provides a default value for a column, when
nothing is given.
3 UNIQUE Ensures that all values in a column are different.
4 CHECK Ensures that all values in a column satisfy
certain condition.
5 PRIMARY KEY Used to identify a row uniquely.
6 FOREIGN KEY Used to ensure Referential Integrity of the data.

A table may have multiple column with UNIQUE constraints, but


there is only one PRIMERY KEY constraints in a table.
Implementing Constraints in the Table

mysql> CREATE TABLE Student


(StCode char(3) NOT NULL PRIMARY
KEY, Column level
Stname char(20) NOT
constraints are
NULL,
StAd varchar(40), defined with
d char(5) column definitions.

AdmN UNIQUE, ‘M’


o char(1) ,
integer CHECK (StAge>=5)
StSe );
DEFAULT
x
CREATE TABLE EMP ( Code char(3) NOT Table level
NULL, StAg constraints are
e defined after all
Name char(20) NOT column definitions.
NULL, City
varchar(40),
Pay Decimal(10,2),
PRIMARY KEY (Code) );
Modifying Table
Structure
You can alter (modify) the structure of existing table by the
using ALTER TABLE…. Command of MySQL.
You can do the following with the help of ALTER TABLE..
Command.
 Add a new Column or Constraints
 Modifying existing column (data type, size
etc.)
 Delete an existing column or Constraints
 Changing Column Name

ALTER TABLE <Table Name> ADD|MODIFY|DROP|


CHANGE <Column Definition(s)>
You can add/Delete/Modify multiple columns with single ALTER
Command.

Visit www.ip4you.blogspot.com for more teaching-learning materials...


Modifying Table
Structure ..
 Adding new column
ALTER TABLE <Table Name>
ADD <Column>[<data type> <size>][<Constraints>]
mysql> ALTER TABLE Student ADD (TelNo Integer);
mysql> ALTER TABLE Student ADD (Age Integer DEFAUL
10);
 Modifying Existing Column
ALTER TABLE <Table Name>
MODIFY <Column>[<data type> <size>] [<Constraints>]
mysql> ALTER TABLE Student MODIFY Name
VARCHAR(40); mysql> ALTER TABLE EMP CHANGE
ENAME, EMPNAME CHAR(40);
ALTER TABLE <Table Name> Renaming
 Removing
DROP Column
<Column name> Column by
mysql> ALTER TABLE Student DROP TelNo; using
CHANGE
mysql> ALTER TABLE Emp DROP JOB, DROP
Inserting Records in a Table
You can insert record in the table by using by using the
following DML command.
INSERT INTO <Table Name> [<Column list>]
VALUES <list of values>
Suppose a table named STUDENT has been created with the
following structure.
StID NAME FNAME DOB CITY CLASS

We can insert a record as follows-


mysql> INSERT INTO Student VALUES
(‘s1’,’Amitabh’, ‘Harivansh’,’1955-10-25’, ‘Mumbai’,
12); mysql> INSERT INTO Student VALUES
(‘s2’,’Sharukh Khan’, NULL,’1972-5-25’,
‘Delhi’, 10);
mysql> INSERT INTO Student (StID, FName, Name,
Class) VALUES (‘s3’,’Amitabh’,
For missing or unknown values, we can use NULL
’Abhishek’, 10);
Deleting Records from the
Table
You can delete all or selected record(s) from the table by using
the following DML command.

DELETE FROM <Table Name> [WHERE <Condition>]

This command will


mysql> DELETE FROM delete all
Student ; records…
mysql> DELETE FROM Student WHERE
City=‘Mumbai’ ; mysql> DELETE FROM Student
WHERE Class >=11 ;
 You can recall (Undelete) records by giving
ROLLBACK command, if Auto commit is Give
off. mysql> ROLLBACK ; SET AUTOCOMMIT=0
 You can issue COMMIT command to record To disable Auto save
the changes permanently. feature in MySQL
mysql> COMMIT;
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Modifying Records in the
Table
You can modify the values of columns of all or selected records
in the table by using the following DML command.

UPDATE <Table Name> SET <Column> =


<Expression> [WHERE <Condition>]

mysql> UPDATE Student SET Class =10 ;

mysql UPDATE Studen SET Class=10 WHERE ;


> t class=9
mysql UPDATE Emp Sal = Sal+(Sal*10/100);
> SET
mysql UPDATE Emp Sal = Sal+(Sal*10/100)
> WHERE Sal <=10000;
SET
mysql> UPDATE Emp SET City =
‘Dehradun’ WHERE CITY IS
NULL;
Making Simple Queries Using
SELECT
The SELECT command of SQL, empowers you to make a
request (queries) to retrieve stored records from the table.
The syntax of SQL is given below-
Syntax Notation: <> User given values [ ] optional clause
SELECT < [Distinct | ALL] *| column name(s)>
FROM <table(s)> [WHERE <condition> ]
[ORDER BY <column(s)> [ASC | DESC] ] ;
[GROUP BY <column(s)> [HAVING <condition>]
];
Consider the table Student having some records as
StID Name Fname DOB City Class

S1 Amitabh Harivansh Rai 1948-11-10 Allahabad 12
S2 Sharukh Firoz 1970-05-10 Delhi 11
S3 Irphan Akbar 1970-10-05 Jaipur 11
S4 Salman Salim Javed 1972-04-10 Mumbai 10
S5 Abhishek Amitabh 1975-03-12 Mumbai 10
Making Simple Queries – Cont..
 Selecting all columns
If you want to view all columns of the student table, then you
should give the following command-
* represents all columns.
SELECT * FROM Student ;
MySQL will display the all records with all columns in the Student table.

 Selecting specific columns


If you want to view only Name and City columns of the student table
mysql> SELECT Name, City FROM Student ;
City Name
Name City
Allahabad Amitabh
Amitabh Allahabad Delhi Sharukh
Sharukh Delhi Jaipur Irphan
Irphan Jaipur Mumbai Salman
Salman Mumbai Mumbai Abhishek
Abhishek Mumbai SELECT City, Name FROM
Student ;
Making Simple Queries – Cont..
 Eliminating Duplicate values in a column(DISTICT)
SELECT City FROM Student ;
City
City Only Unique
Allahabad
Allahabad Cities are
Mumbai is Delhi displayed
Delhi
repeated Jaipur
Jaipur
Mumbai
Mumba
iMumbai SELECT DISTINCT City FROM Student ;
 Using Column Aliases
We can give a different name to a column or expression (Alias) in the
output of a query.
SELECT Name, Sal*12 AS ‘Annual Salary’ FROM EMP;
SELECT Name, DOB AS ‘Date of Birth’ FROM
Student;
 Doing simple calculations
We can also perform simple calculations with SQL Select
command.
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Selecting Specific Rows – WHERE clause
 WHERE <Condition>
We can select specific records by specifying condition with
WHERE clause.
mysql> SELECT * FROM Student WHERE City=‘Mumbai’;
StID Name Fname DOB City Class
S4 Salman Salim Javed 1972-04-10 Mumbai 10
S5 Abhishek Amitabh 1975-03-12 Mumbai 10

mysql> SELECT Name, Fname, City from


Student WHERE Class >10; Condition
uses
Name Fname City Class
columns
and
Amitabh Harivansh Rai Allahabad 12 operator
Sharukh Firoz Delhi 11 s
Irphan Akbar Jaipur 11
Selecting Specific Rows – WHERE clause
 Relational Operators
We can use the following Relational operators while making
condition.
=, > , < , >=, <=, <>, IS , LIKE, IN,
BETWEEN
 Logical Operators
We can use the following Logical Operators to connect two
conditions.
OR , AND , NOT (!)
mysql> SELECT Name, City from Student
WHERE City <> ‘Mumbai’ AND Class>10;

mysql> SELECT * FROM Emp


WHERE Sal >10000 OR Job =‘Manager’;

mysql> SELECT * FROM Student


WHERE NOT Grade=‘A’;
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Selecting Specific Rows – WHERE clause
 Specifying Range of Values – BETWEEN Operator
SELECT * FROM Emp WHERE Sal BETWEEN 5000 AND 10000 ;
The same query can also be written as -
SELECT * FROM Emp WHERE Sal >= 5000 AND Sal<=10000 ;
Other Logical operators also can be applied-
SELECT * FROM Emp WHERE NOT Sal BETWEEN 5000 AND
10000 ;

 Specifying List – IN Operator


SELECT * FROM Emp WHERE Sal IN (5000, 10000) ;
The same query can also be written as –
SELECT * FROM Emp WHERE Sal = 5000 OR Sal =10000 ;
SELECT * FROM Student WHERE City IN (‘Mumbai’,
‘Delhi’,’Kanpur’) ;

 Searching NULL Values – IS


Operator SELECT * FROM Student WHERE
City IS NULL ; The NOT Operator can also be
Selecting Specific Rows – WHERE clause

 Pattern Matching – LIKE Operator


A string pattern can be used in SQL using the following wild cards
 % Represents a substring in any length
 _ Represents a single character at used
Example. position
‘A%’ represents any string starting with ‘A’ character.
‘_ _A’ represents any 3 character string ending with ‘A’.
‘_B%’ represents any string having second character ‘B’
‘_ _ _’ represents any 3 letter string.

A pattern is case sensitive and can be used with LIKE operator.

mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;


mysql> SELECT * FROM Student WHERE Name LIKE ‘%Singh%’;
mysql> SELECT Name, City FROM Student
WHERE Class>=9 AND Name LIKE ‘%Kumar
%’ ;
End of Revision of important topics of class
Working with Functions
 What is Function?
A function is a special types of command in MySQL that
performs some operation on table and returns a single value
as a result.
 Types of Functions:
 Math or Numeric Functions
 Text or String Functions
 Date & Time Function
 Aggregate Functions

 Numeric, String and Date-Time functions are called Single row functions
because they applied on row-to-row basis. When applied on a table,
they return a single result for every row of the queried table.
 Aggregate Functions are called Multiple row functions because they
operate on a set of rows to return a single value.
Math or Numeric Functions
These functions may accept some numeric values and
performing required operation, returns numeric values as result.

Name Purpose Example


MOD (M, N) Returns remainder of M divide Select MOD(11,4) ;
by N 3
POWER (M, N) Returns MN Select POWER(3,2);
POW (M, N) 9
ROUND (N [,M]) Returns a number rounded off Select ROUND(15.193,1);
up to M place. If M is -1, it 15.2
rounds nearest 10. Select ROUND(15.193);
If M is not given, the N is 15
rounded to the nearest Integer.
TRUNCATE(N,M) Returns number after Select TRUNCATE(15.79,1)
truncating M decimal place.  15.7
SQRT (N) Returns square root of N Select SQRT(25);  5
Numeric/Math Functions
 Mod() : Returns remainder of M devide by N.
MOD(M,N)
mysql> SELECT MOD(5,2) ;  1
mysql> SELECT MOD(Pay, 30) FROM EMPLOYEE;

 POW() : Returns MN.


POW(M,N)
mysql> SELECT POW(5,2) ;  25
mysql> SELECT POW(MARKS, 2) FROM STUDENT;
 ROUND() : Returns rounded value upto defined place.
ROUND (Number, position)
mysql> SELECT ROUND(‘212.567’,1 ) ;  212.6
mysql> SELECT ROUND(PRICE*QTY,2) FROM ITEMS;

 TRUNCATE() : Returns number after removing decimal place


upto defined place.
TRUNCATE (Number, position)
mysql> SELECT TRUNCATE(‘212.567’,1 ) ;  212.5
mysql> SELECT TRUNCATE(PRICE*QTY,2) FROM ITEMS;

Visit www.ip4you.blogspot.com for more teaching-learning materials...


Text or String Functions
Name Purpose Example
CONCAT(str1,str2) Returns concatenated string i.e. Select CONCAT(Name, City)
str1+str2. from Student;
LOWER(str) / Returns the given string in lower Select LOWER(‘ABC’);  abc
LCASE(str) case.

UPPER(str) / Returns the given String in upper Select UPPER(‘abc’);  ABC


UCASE(str) case.

LTRIM(str) Removes Leading/Trailing/both Select TRIM(‘ ABC ‘);


RTRIM(str) spaces from given string.  ‘ABC’
TRIM(str)
LEFT(str, N) Returns the (N) characters from Select LEFT(‘Computer’,4);
RIGHT(str,N) left/right from the given string.  Comp

SUBSTR(str,P,[N]) / Returns the substring for given Select


MID (str,P,N) position(P) and length (N). If M is (- SUBSTR(‘Computer’,3,2);
ve) then backward position counted.  mp
INSTR(str1,str2) Returns the index of first occurrence Select INSTR(‘Common’, ’m’);
of str2 in str1. 3
LENGTH(str) Returns the length of given string Select LENGTH(‘Common’);
6
Text or String Functions
 CONCAT() : Concatenates (Adds) two string.
CONCAT(Str1 , Str2)
mysql> SELECT CONCAT(‘ab’ , ‘cd’ ) FROM DUAL;
 abcd
mysql> SELECT CONCAT(‘Mr’, Name) FROM Student;
 Concat() can be nested.
mysql> SELECT CONCAT(CONCAT(Name,’son of ‘), Fname)
FROM Student;

 LENGTH() : Returns length of given string.


LENGTH (Str)
mysql> SELECT LENGTH(‘abcd’ ) ;
4
mysql> SELECT Name, LENGTH(Name) FROM
Student;
DUAL is an imaginary table in MySQL. Command will also work without DUAL.
Text or String Functions
 LOWER() or LCASE()
Converts given string in lower case.
LOWER (Str)
mysql> SELECT LOWER(‘ABcD’ ) FROM DUAL;
 abcd
mysql> SELECT LOWER(Name) FROM Student;
mysql> SELECT LCASE(Fname) FROM Student;

 UPPER() or UCASE()
Converts given string in upper case.
UPPER (Str)
mysql> SELECT UPPER(‘abcD’ ) FROM DUAL;
 ABCD
mysql> SELECT UPPER(Name) FROM Student;
mysql> SELECT UCASE(Fname) FROM Student;
Text or String Functions
 LTRIM() : Returns string after removing leading spaces.
mysql> SELECT LTRIM(‘ abcd’ ) FROM DUAL;
 abcd
mysql> SELECT LTRIM(Name) FROM Student;

 RTRIM() : Returns string after removing trailing spaces.


mysql> SELECT RTRIM(‘abcd ’ ) FROM DUAL;
 abcd
mysql> SELECT RTRIM(Name) FROM Student;

 TRIM() : Returns string after removing leading and


trailing spaces.
mysql> SELECT TRIM(‘ abcd ’ ) FROM DUAL;
 abcd

Visit www.ip4you.blogspot.com for more teaching-learning materials...


String Functions
 SUBSTR()
Returns a sub string of given length from specified position.
SUBSTR (Str, position [,length])
mysql> SELECT SUBSTR(‘MY COMPUTER’, 4,3’ )  COM
 If position is negative then backward position is counted.
mysql> SELECT SUBSTR(‘ABCDEFG’ , -5, 4) FROM Student;
 CDEF
 If Length is omitted then up to end of the string is considered.
mysql> SELECT SUBSTR(‘ABCDEFG’ , 3) FROM Student;
 CDEFG
 INSTR()
Searches a string in to another string and returns its position.
INSTR(Str1, Str2)
mysql> SELECT INSTR(‘CORPORATE FLOOR’, ‘OR’); 2
mysql> SELECT Name, INSTR(Name,’a’) FROM Student;
String Functions
 LEFT() : Returns leftmost string up to given length.
LEFT (Str , length)
mysql> SELECT LEFT(‘MYSQL’, 2 )  MY
mysql> SELECT LEFT( Name, 4) FROM Student;

 RIGHT() : Returns rightmost string up to given length.


RIGHT (Str , length)
mysql> SELECT RIGHT(‘MYSQL’, 3 )  SQL
mysql> SELECT RIGHT (Name, 4) FROM Student;

 MID() : Returns a substring upto given length from given


position.
MID (Str ,Pos, Length)
Mid() is
mysql> SELECT MID(‘COMPUTER’, 4,3 )  PUT
similar to
mysql> SELECT MID (Name, 4,3) FROM Student; Substr()
Date & Time
Functions
Name Purpose Example
CURDATE() / Returns the current date in Select CURDATE();
CURRENT_DATE() YYYY-MM-DD format.  2013-10-02

NOW() Returns the current date & Time Select NOW();


as YYYY-MM-DD HH:MM:SS  2013-10-02 11:30:02
SYSDATE() Returns the current date & Time Select SYSDATE();
as YYYY-MM-DD HH:MM:SS  2013-10-02 11:30:10
DATE() Returns the date part of a date- Select DATE(SYSDATE());
time expression.  2013-10-02
DAY() Returns the Day/Month/Year Select DAY(‘2021-06-12’);
MONTH() from given date argument. 12
YEAR() Select MONTH(‘2012-10-02’);
10
DAYNAME() Returns the name of the Select DAYNAME(CURDATE());
weekday  SUNDAY
DAYOFMONTH() Returns the day of month Select
[same as DAY()] (1-31). DAYOFMONTH(CURDATE());

DAYOFWEEK() Returns the day of week (1-7). Select DAYOFWEEK(CURDATE());


DAYOFYEAR() Returns the day of year(1-366). Select DAYOFYEAR(CURDATE());
Date & Time
Functions
 CURDATE() or CURRENT_DATE()
Returns current date of the system in YYYY-MM-DD format.
mysql> SELECT CURDATE() ;  2014-01-30
mysql> SELECT CURDATE()+10 ;  2014-02-09

 SYSDATE()
Returns current date and time as YYYY-MM-DD HH:MM:SS
mysql> SELECT SYSDATE() ;
 2014-01-30 10:30:20
 NOW()
Returns current date and time as YYYY-MM-DD HH:MM:SS
mysql> SELECT SYSDATE() FROM DUAL
 2010-01-30 10:30:20

Difference between SYSDATE() & NOW()


NOW() returns the time when command began to execute and does not change
time during execution. Where as SYSDATE() changes its time continuously.
Date & Time
Functions
DATE()
Returns date part of the given date-time
expression.
DATE (Dt)
mysql> SELECT DATE(‘2008-12-31 01:02:03’) ;
 2008-12-32
mysql> SELECT DATE( SYSDATE());
 YEAR()
Returns year of the given date expression.
YEAR (Dt)
mysql> SELECT YEAR(‘2008-12-31’) ;  2008
mysql> SELECT YAER(DOB) FROM Student;

 MONTH()
Returns month of the given date expression.
MONTH (Dt)
mysql> SELECT MONTH(‘2008-12-31’) ;  12
mysql> SELECT MONTH( CURDATE());
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Date & Time
Functions
 DAYNAME()
Returns the name of Week day of the given date expression.
DAYNAME (Dt)
mysql> SELECT DAYNAME(‘2008-12-31’) ;
 SUNDAY
mysql> SELECT DAYNAME( CURDATE()) ;
mysql> SELECT DAYNAME( DOB) FROM Student;

 DAY() / DAYOFMONTH()
Returns day of month of the given date expression.
DAYOFMONTH (Dt)
mysql> SELECT DAYOFMONTH(‘2008-12-31’) ;
 31
mysql> SELECT DAY( CURDATE()) ;
mysql> SELECT DAY( DOB) FROM Student;
Date & Time
Functions
 DAYOFWEEK()
Returns day of week i.e. 1- Sunday, 2- Tuesday.. etc. of given
date.
DAYOFWEEK (Dt)
mysql> SELECT DAYOFWEEK(‘2008-12-31’) ;
1
mysql> SELECT DAYOFWEEK(CURDATE()) ;
 DAYOFYEAR()
Returns the day of year of the given date expression.
DAYOFYAER (Dt)
mysql> SELECT DAYOFYAER(‘2010-02-05’) ;
 36
mysql> SELECT DAYOFYAER( CURDATE()) ;
mysql> SELECT DAYOFYEAR( DOB) FROM Student;

Visit www.ip4you.blogspot.com for more teaching-learning materials...


Aggregate
Functions
Name Purpose Example
SUM() Returns the sum of given Select SUM(Pay) from Emp;
column. Select Sum(Pay), Sum(Net)
from Emp;
MIN() Returns the minimum value in Select MIN(Pay) from Emp;
the given column.
MAX() Returns the maximum value in Select MAX(Pay) from Emp;
the given column.
AVG() Returns the Average value of Select AVG(Pay) from Emp;
the given column.
COUNT() Returns the total number of Select COUNT(Name) from Emp;
values/ records in given Select COUNT(*) from Emp;
column.

Aggregate Functions should not be used with other columns which


may have multiple values in the table. The following query is illogical
and wrong. Why? Think yourself….
Select sum(pay), name from Employee;
Aggregate
 Functions
SUM()
Returns sum of given column in the table.
SUM (<Field>)
mysql> SELECT SUM (Sal) FROM Emp;
mysql> SELECT SUM(Sal) FROM Emo WHERE City=‘Guwahati’;
 MIN()
Returns minimum value in the given column of table.
MIN (<Field>)
mysql> SELECT MIN (Sal) FROM Emp;
mysql> SELECT MIN(Sal) FROM Emp WHERE City=‘Tezpur’;
 MAX()
Returns maximum value in the given column of table.
MAX (<Field>)
mysql> SELECT MAX (Sal) FROM Emp;
mysql> SELECT MAX(Sal) FROM Emp WHERE City=‘Jaipur’;
Aggregate
Functions
AVG()
Returns average value of given column in the table.
AVG (<Field>)
mysql> SELECT AVG (Sal) FROM Emp;
mysql> SELECT AVG(Sal) FROM Emo WHERE City=‘Jaipur’;
 COUNT()
Returns number of values in the given column of table. It also
reflect the number of record in the table.
COUNT (<Field|*>)
mysql> SELECT COUNT (Name) FROM Emp;
mysql> SELECT COUNT(Name) FROM Emp
WHERE City=‘Jaipur’;
mysql> SELECT COUNT (*) FROM Emp;
 Number of records in the Emp table
mysql> SELECT COUNT(*) FROM Emp
WHERE City=‘Jaipur’;
Grouping Records in a Query- GROUP BY Clause
 Some time it is required to apply a Select query on a group
of records instead of whole table.
 You can group records by using GROUP BY <column>
clause with Select command. A group column is chosen
which have non-distinct (repeating) values like City, Job etc.
 Generally, the following Aggregate Functions are applied on
groups.

Name Purpose
SUM() Returns the sum of given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given
column.
Aggregate Functions &
Group
An Aggregate function may applied on a column with DISTINCT
or ALL keyword. If nothing is given ALL is assumed.
 Using SUM (<Column>)
This function returns the sum of values in given column or
expression.
mysql> Select Sum(Sal) from EMP;
mysql> Select Sum(DISTINCT Sal) from EMP;
mysql> Select Sum (Sal) from EMP where
City=‘Kanpur’;
mysql> Select Sum (Sal) from EMP Group By City;
mysql> Select Job, Sum(Sal) from EMP Group By Job;
 Using MIN (<column>)
This functions returns the Minimum value in the given column.
mysql> Select Min(Sal) EMP;
from
mysql> Select Min(Sal) EMP Group By City;
from
mysql> Select Job, from EMP Group By
Aggregate Functions &
Group
 Using MAX (<Column>)
This function returns the Maximum value in given column.
mysql> Select Max(Sal) from EMP;
mysql> Select Max(Sal) from EMP where
City=‘Kanpur’;
mysql> Select Max(Sal) from EMP Group By City;
 Using AVG (<column>)
This functions returns the Average value in the given column.
mysql> Select AVG(Sal) from EMP;
mysql> Select AVG(Sal) from EMP Group By City;
 Using COUNT (<*|column>)
This functions returns the number of rows in the given column.
mysql> Select Count (*) from EMP;
mysql> Select Count(Sal) from EMP Group By City;
mysql> Select Count(DISTINCT Designation) from
EMP; mysql> Select Count(*), Sum(Sal) from EMP
Group By Job;
Aggregate Functions & Conditions (HAVING)

You may use any condition on group, if required. HAVING


<condition> clause is used to apply a condition on a group.
mysql> Select Job, Sum(Pay) from EMP
Group By Job HAVING ‘Having’ is
Sum(Pay)>=8000; mysql> Select Job, Sum(Pay) used with
Group By
from EMP
Clause only.
Group By Job HAVING
Avg(Pay)>=7000; mysql> Select Job, Sum(Pay)
from EMP
mysql> Select Job, Min(Pay),Max(Pay), Avg(Pay)
from EMP Group Group By Job
By Job HAVING
HAVING
Count(*)>=5;
Sum(Pay)>=8000;
mysql> Select Job, Sum(Pay) from EMP Where
City=‘Dehradun’ Group By Job HAVING
Count(*)>=5;
Where clause works in respect of whole table but Having
works on Group only. If Where and Having both are used then
Where will be executed first.
Visit www.ip4you.blogspot.com for more teaching-learning materials...
Aggregate Functions & NULL
Values
Consider a table Emp having following records as-
Emp
Code Name Sal Aggregate function
ignores NULL values i.e.
E1 Ram Kumar NULL
NULL values does not
E2 Suchitra 4500 play any role in
E3 Yogendra NULL calculations.
E4 Sushil Kr 3500
E5 Lovely 4000

mysql> Select Sum(Sal) from 🢧 12000


EMP; mysql> Select Min(Sal) 🢧 3500
from EMP; mysql> Select 🢧 4500
mysql> Select
Max(Sal) fromCount(Sal)
EMP; from 3
EMP; 🢧
mysql> Select Avg(Sal) from 🢧 4000
EMP;
mysql> Select Count(*) from 🢧 5
Visit www.ip4you.blogspot.com for more….

You might also like