Informatics Practices 3
Class XII (CBSE Board) ee
UNIT-2: Database Query using SQL
Chapter: 5
Relational Database &
Query using MySQL
Visit www.ip4you.blogspot.com for more....
Open Teaching-Learning Material
e-mail : [email protected]Expected Learning Outcome:
CBSE Syllabus (2021-22) Covered in this presentation:
O Math functions: POWER (), ROUND (), MOD ().
O 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 ().
O Aggregate Functions: MAX (), MIN (), AVG (), SUM (), COUNT (); using
COUNT (*).
O Querying and manipulating data using Group by, Having, Order by.
In this presentation you will learn about Relational Database and
MySQL query.
O Revision of important topics of class XI.
O Working with DDL & DML commands of MySQL.
O MySQL functions (Math Functions, Text functions, Date functions and
aggregate functions)
O Using Group by and Order by clause in query.Revision of important topics of Class XI
What is the Database?
O 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.
O Most of the databases store data in the form of Relations
(also called Tables). Such Databases are known as
Relational Database.
O A Software used to store and manage Relational database
is called RDBMS (Relational Database Management
System).
¢Tables
Queries
°Views
«Index
Some Commonly used RDBMS
software are- Oracle, MySQL,
MS SQL Server, SyBase and
Ingress, SQLite etc.
Visit www.ip4you.blogspot.com for more teaching-learning materials...Advantages of Database System.
Oo
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)
Name Address DOB City Entity
" (Record)
Amar | 2/3 Vijay Nagar | 01.04.1990 | GUWAHATI J
Kailash 22 Katra 23.10.1992 | LucknowoO
Ee Geel
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.
Cardinality : Number of Records 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.
WA 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
can’t be same for any two
records in the table, even
Class |Stream | Subject
Science
they can have same
_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-
O Primary Key
O Candidate Key
O Alternate Key
O Foreign key
Visit www.ip4you.blogspot.com for more teaching-learning materials...Oo
Oo
oO
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 RollINo, 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
AADHAR_ No! RollINo) Name Class Marks
Seema Chauhan| 12 15
Ajay Kumar se 23
Vansh Pratap le 20
Ajay Kumar 12 15
DeptNo
DeptName
HeadName
LocationMySQL- Introduction ans’
MySQL is an open source, free and powerful Relational
Database Management System (RDBMS) software based on
SQL. The main features of MySQL are -
O 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.
O Portability: It can be installed and run on any types of Hardware
and OS like Linux, MS Windows or Mac etc.
O Security : It offers security and authorization feature to keep
database secure.
O Connectivity : The MySQL database can be connect using different
protocols and Programming Languages like Python, Java etc.
O 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
CREATE
COMMIT GRANT
INSERT
ROLLBACK REVOKE
DELETE
SAVEPOINT
UPDATE DDL: Database & Table level
DML: Record level
: ion | |
DDL & DML are basic categories JEL: Transaction leve
DCL: Security & Privacy level
Visit www.ip4you.blogspot.com for more teaching-learning materials...Data types in MySQL
O 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
O Date & Time Data Types:
= DATE - Stores date in YYYY-MM-DD format.
= TIME - Stores time in HH:MM:SS format.
O 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
characters.
Char, Varchar, Date and Time values should be enclosed with single (‘ ‘) or
double ( “”) quotes in MySQL.Database Handling commands in MySQL
rr
O Creating a Database.
The following command will create School database in MySQL.
mysql> CREATE DATABASE School;
O Opening a database
To open an existing database, following command is used.
mysql> USE school ;
O Getting listings of database and tables
mysql> SHOW DATABASES;
mysql> SHOW TABLES;
O Deleting a Database and Table
mysql> DROP DATABASE School;
mysql> DROP TABLE Student;
O Viewing Table Structure
mysql> DESCRIBE Student;
Select database();
Shows the name of
currently open database
Visit www.ip4you.blogspot.com for more teaching-learning materials...Working with MySQL Tips: Remember
5 = N-Name, D- Data type,
Creating Simple Tables: S- Sie, 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(1@,2));
PARTE Me mn ELC a
Query OK, 1 row affected (0.60 sec) All commands
mysql> USE SCHOOL; in MySQL
Database change: 7
CREATE TABLE EMP (EMP INTEGER(2
f ALC1@,2));
ma ameitecmy are ended
CITY CHAR(25), PAY DECIMAI with ;
YOK, @ rows affected (0.07 sec)
ENAME | char ae
(any Pre yl ae
rst f a
mysql> city payCreating 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.
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.
CHECK Ensures that all values in a column satisfy
certain condition.
PRIMARY KEY | Used to identify a row uniquely.
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
a
mysql> CREATE TABLE Student
(StCode char(3) NOT NULL PRIMARY KEY,
Stname char(2@) NOT NULL,
StAdd varchar(4@),
AdmNo char(5) UNIQUE,
StSex char(1) DEFAULT ‘M’,
StAge integer CHECK (StAge>=5) );
CREATE TABLE EMP ( Code char(3) NOT NULL,
Name char(2@) NOT NULL,
City varchar(4@),
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 anew Column or Constraints
= Modifying existing column (data type, size etc.)
= Delete an existing column or Constraints
= Changing Column Name
ALTER TABLE
ADD|MODIFY|DROP|CHANGE
You can add/Delete/Modify multiple columns with single ALTER
Command.
Visit www.ip4you.blogspot.com for more teaching-learning materials...Modifying Table Structure ..
O Adding new column
ALTER TABLE
ADD [ ][]
mysql> ALTER TABLE Student ADD (Tel1No Integer);
mysql> ALTER TABLE Student ADD (Age Integer DEFAUL 10);
O Modifying Existing Column
ALTER TABLE
MODIFY [ ] []
mysql> ALTER TABLE Student MODIFY Name VARCHAR(4@) ;
mysql> ALTER TABLE EMP CHANGE ENAME, EMPNAME CHAR(4@);
O Removing Column
ALTER TABLE
DROP
mysql> ALTER TABLE Student DROP Te1No;
mysql> ALTER TABLE Emp DROP JOB, DROP Pay;
Renaming
Column by
using
CHANGEInserting Records in a Table
You can insert record in the table by using by using the
following DML command.
INSERT INTO
[]
VALUES
Suppose a table named STUDENT has been created with the
following structure.
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’, ’Abhishek’, 10);
For missing or unknown values, we can use NULLDeleting Records from the Table
You can delete all or selected record(s) from the table by using
the following DML command.
DELETE FROM
[WHERE ]
mysql> DELETE FROM Student ; dene
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 off.
mysql> ROLLBACK ;
You can issue COMMIT command to record
the changes permanently.
mysql> COMMIT;
Give
SET AUTOCOMMIT=0
To disable Auto save
feature in MySQL
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
SET =
[WHERE ]
mysql> UPDATE Student SET Class =10 ;
mysql> UPDATE Student SET Class=10 WHERE class=9 ;
mysql> UPDATE Emp SET Sal
Sal+(Sal*10/10@) ;
mysql> UPDATE Emp SET Sal
WHERE Sal <=10000;
Sal+(Sal*10/100)
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
[WHERE ]
[ORDER BY [ASC | DESC] ];
[GROUP BY [HAVING ] ] ;
Consider the table Student having some records as —
Amitabh Harivansh Rai 1948-11-10 | Allahabad
Sharukh Firoz 1970-05-10 | Delhi
Irphan Akbar 1970-10-05 | Jaipur
Salman Salim Javed 1972-04-10 | Mumbai
Abhishek Amitabh 1975-03-12 | MumbaiMaking Simple Queries — Cont..
O 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 ; eee eenenereenennnnenemennnmeeenes
MySQL will display the all records with all columns in the Student table.
O Selecting specific columns
If you want to view only Name and City columns of the student table
mysql> SELECT Name, City FROM Student ;
Allahabad Amitabh
Amitabh Allahabad Delhi Sharukh
Sharukh Jaipur Irphan
Mumbai Salman
Salman Mumbai Mumbai Abhishek
Abhishek Mumbai SELECT City, Name FROM Student ;Making Simple
Queries — Cont..
O Eliminating Duplica
SELECT City FROM Student ;
O Using Column Aliases
Mumbai is
repeated
te values in a column(DISTICT)
Only Unique
Cities are
displayed
Allahabad
Jaipur
Mumbai
SELECT DISTINCT City FROM Student ;
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;
O Doing simple calculations
We can also perform simple ca
SELECT 4*3 ;
Iculations with SQL Select command.
Visit www.ip4you.blogspot.com for more teaching-learning materials...Selecting Specific Rows — WHERE clause
O WHERE
We can select specific records by specifying condition with
WHERE clause.
mysql> SELECT * FROM Student WHERE City=‘Mumbai’;
S4 Salman Salim Javed 1972-04-10 | Mumbai 10
SS Abhishek Amitabh 1975-03-12 | Mumbai 10
mysql> SELECT Name, Fname, City from Student
WHERE Class >10;
Condition
uses
columns
and
Amitabh Harivansh Rai Allahabad operators —
Sharukh Firoz Delhi
Irphan Akbar JaipurSelecting Specific Rows —- WHERE clause
O Relational Operators
We can use the following Relational operators while making
condition.
=, >,<, >=,
O Logical Operators
We can use the following Logical Operators to connect two
conditions.
<=, <>, 1S, LIKE, IN, BETWEEN
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
O 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;
O 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’) ;
O Searching NULL Values —- IS Operator
SELECT * FROM Student WHERE City IS NULL ;
The NOT Operator can also be applied -
SELECT * FROM Student WHERE City IS NOT NULL;Selecting Specific Rows —- WHERE clause
O 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 position
Example.
‘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 XIWorking with Functions
O 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.
O 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.
Neva Purpose fepccanle)(-)
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) 29
ROUND (N [,M]) | Returns a number rounded off | Select ROUND(15.193,1);
up to M place. If M is -1, it 315.2
rounds nearest 10. Select ROUND(15.193);
If M is not given, the N is 315
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); > 5Numeric/ Math Functions
O Mod() : Returns remainder of M devide by N.
MOD(M,N)
mysql> SELECT MOD(5,2); > 1
mysql> SELECT MOD(Pay, 30) FROM EMPLOYEE;
O POW(): Returns M".
POW(M,N)
mysql> SELECT POW(5,2) ; > 25
mysql> SELECT POW(MARKS, 2) FROM STUDENT;
O ROUND() : Returns rounded value upto defined place.
ROUND (Number, position)
mysq|> SELECT ROUND(‘212.567’,1 ); > 212.6
mysql> SELECT ROUND(PRICE*QTY,2) FROM ITEMS;
O 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
CONCAT(str1,str2)
Purpose
Returns concatenated string i.e.
stri+str2.
Example
Select CONCAT(Name, City)
from Student;
LOWER(str) /
LCASE(str)
Returns the given string in lower
case.
Select LOWER(‘ABC’); > abc
UPPER(str) /
UCASE(str)
Returns the given String in upper
case.
Select UPPER(‘abc’); > ABC
LTRIM(str)
RTRIM(str)
TRIM(str)
Removes Leading/Trailing/both
spaces from given string.
Select TRIM(*
> ‘ABC’
ABC ‘);
LEFT(str, N)
RIGHT(str,N)
SUBSTR(str,P,[N]) /
MID (str,P,N)
INSTR(stri,str2)
Returns the (N) characters from
left/right from the given string.
Returns the substring for given
position(P) and length (N). If M is
ve) then backward position counted.
Returns the index of first occurrence
of str2 in str1.
Select LEFT(‘Computer’,4);
> Comp
Select
SUBSTR(‘Computer’,3,2);
> mp
Select INSTR(‘Common’, 'm’);
25
LENGTH(str)
Returns the length of given string
Select LENGTH(‘Common’);
36Text or String Functions
rr
O 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;
O 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
rr
O 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;
1 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
eS CU
O LTRIM() : Returns string after removing leading spaces.
mysql> SELECT LTRIM(‘ abcd’ ) FROM DUAL;
> abcd
mysql> SELECT LTRIM(Name) FROM Student;
O RTRIM() : Returns string after removing trailing spaces.
mysql> SELECT RTRIM(‘abcd =‘) FROM DUAL;
> abcd
mysql> SELECT RTRIM(Name) FROM Student;
O 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
a
Oo
SUBSTR()
Returns a sub string of given length from specified position.
Oo
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(Stri, Str2)
mysql> SELECT INSTR(‘CORPORATE FLOOR’, ‘OR’); > 2
mysql> SELECT Name, INSTR(Name,’a’) FROM Student;String Functions
O LEFT() : Returns leftmost string up to given length.
LEFT (Str , length)
mysql> SELECT LEFT(‘MYSQL’,2) > MY
mysql> SELECT LEFT( Name, 4) FROM Student;
O RIGHT() : Returns rightmost string up to given length.
RIGHT (Str , length)
mysql> SELECT RIGHT(‘MYSQL’,3) > SQL
mysql> SELECT RIGHT (Name, 4) FROM Student;
O MID() : Returns a substring upto given length from given
position.
MID (Str ,Pos, Length) ae
mysql> SELECT MID(‘COMPUTER;, 4,3 ) > PUT press
mysql> SELECT MID (Name, 4,3) FROM Student; SubstrDate & Time Functions
Purpose
Example
CURDATE() /
CURRENT_DATE()
Returns the current date in
YYYY-MM-DD format.
Select CURDATE();
> 2013-10-02
NOW()
Returns the current date & Time
as YYYY-MM-DD HH:MM:SS
Select NOW();
> 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. 312
YEAR() >Select MONTH(‘2012-10-02’);
310
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
O 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
O SYSDATE()
Returns current date and time as YYYY-MM-DD HH:MM:SS
mysql> SELECT SYSDATE() ;
> 2014-01-30 10:30:20
O 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
O 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());
O YEAR()
Returns year of the given date expression.
YEAR (Dt)
mysql> SELECT YEAR(‘2008-12-31') ; > 2008
mysql> SELECT YAER(DOB) FROM Student;
O 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
O 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;
O 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
O DAYOFWEEK()
Returns day of week i.e. 1- Sunday, 2- Tuesday.. etc. of given
date.
DAYOFWEEK (Dt)
mysql> SELECT DAYOFWEEK(‘2008-12-31’) ;
21
mysql> SELECT DAYOFWEEK(CURDATE()) ;
O 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
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
column.
Select COUNT(*) from Emp;
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
O SUM()
Returns sum of given column in the table.
SUM ()
mysql> SELECT SUM (Sal) FROM Emp;
mysql> SELECT SUM(Sal) FROM Emo WHERE City=‘Guwahati’;
O MIN()
Returns minimum value in the given column of table.
MIN ()
mysql> SELECT MIN (Sal) FROM Emp;
mysql> SELECT MIN(Sal) FROM Emp WHERE City=‘Tezpur’;
O MAX()
Returns maximum value in the given column of table.
MAX ()
mysql> SELECT MAX (Sal) FROM Emp;
mysq|> SELECT MAX(Sal) FROM Emp WHERE City=‘Jaipur’;Aggregate Functions
O AVG()
Returns average value of given column in the table.
AVG ()
mysql> SELECT AVG (Sal) FROM Emp;
mysql> SELECT AVG(Sal) FROM Emo WHERE City=‘Jaipur’;
O COUNT()
Returns number of values in the given column of table. It also
reflect the number of record in the table.
COUNT ()
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’;
Visit www.ip4you.blogspot.com for more teaching-learning materials...Grouping Records in a Query- GROUP BY Clause
rr
O Some time it is required to apply a Select query on a group
of records instead of whole table.
O You can group records by using GROUP BY
clause with Select command. A group column is chosen
which have non-distinct (repeating) values like City, Job etc.
O Generally, the following Aggregate Functions are applied on
groups.
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() eres 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.
Q Using SUM ()
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;
Q Using MIN ()
This functions returns the Minimum value in the given column.
mysql> Select Min(Sal) from EMP;
mysql> Select Min(Sal) from EMP Group By City;
mysql> Select Job, Min(Sal) from EMP Group By Job;Aggregate Functions & Group
es
Q Using MAX ()
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;
Q Using AVG ()
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;
Q 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)
a
You may use
mysql> Select
mysql> Select
mysql> Select
mysql> Select
mysql> Select
any condition on group, if required. HAVING
clause is used to apply a condition on a group.
Job, Sum(Pay) from EMP
Group By Job HAVING Sum(Pay) >=8000;
Job, Sum(Pay) from EMP
Group By Job HAVING Avg(Pay)>=7000;
Job, Sum(Pay) from EMP
Group By Job HAVING Count(*)>=5;
Job, Min(Pay),Max(Pay), Avg(Pay) from EMP
Group By Job HAVING Sum(Pay) >=8000;
Job, Sum(Pay) from EMP Where City=‘Dehradun’
Group By Job HAVING Count(*)>=5;
‘Having’ is
used with
Group By
Clause only.
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-
Aggregate function
ignores NULL values i.e.
NULL values does not
play any role in
calculations.
Code Name Sal
El Ram Kumar | NULL
EQ) Suchitra 4500
ES) Yogendra NULL
E4 Sushil Kr 3500
E5 Lovely 4000
mysql> Select Sum(Sal) from EMP;
mysql> Select Min(Sal) from EMP;
mysql> Select Max(Sal) from EMP;
=> 12000
> 3500
> 4500
mysql> Select Count(Sal) from EMP; > 3
mysql> Select Avg(Sal) from EMP;
mysql> Select Count(*) from EMP;
=> 4000
>5“Education is the most
ey MrT eli
which you can use to
change the world.”
- Nelson Mandela
G)
r Visit i ( for more....