0% found this document useful (0 votes)
120 views56 pages

11th IP Unit-3 Database Concept and SQL

Uploaded by

f0911157
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views56 pages

11th IP Unit-3 Database Concept and SQL

Uploaded by

f0911157
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

UNIT – 3

Database concepts and the


Structured Query Language

Subject - Informatics Practices (065)


Class - XI
www.ipzone.wordpress.com
Objective
In this presentation you will learn about the
fundamental concepts of Database and Database
Management Systems.
 Concept of Database
 Advantages of Database
 Concept of Data Model
 Basics of Relational Data Model
 Concept of Keys
 Types of key - Primary Key, Candidate Key
and Alternate key
www.ipzone.wordpress.com
What is the Database?
 Data is raw facts and figures which does not convey any
meaning or idea because it is not organized.
 A database is a well organized collection of inter-related
that ensures safety, security and integrity of data. It
works like a container which contains the various object
like Tables, Queries, Reports etc. in organized way.
 Most of the databases stores data in the form of
Relations (also called Tables). Such Database are known
as Relational Database.
Database • Queries
• Tables
• Views
• Index

www.ipzone.wordpress.com
What is the Database Management System
(DBMS)?

 A DBMS refers to a software that is


responsible for storing, maintaining and
utilizing database in an efficient way.
 A Database along with DBMS software is
called Database System.
 Example of DBMS software are Oracle, MS
SQL Server, MS Access, Paradox, DB2 and
MySQL etc.
 MySQL is open source and freeware DBMS.

www.ipzone.wordpress.com
Why Database System is used? (Advantages)
 Databases reduces Redundancy
It removes duplication of data because data are kept at one
place and all the application refers to the centrally maintained
database.
 Database controls Inconsistency
When two copies of the same data do not agree to each other,
then it is called Inconsistency. By controlling redundancy, the
inconsistency is also controlled.
 Database facilitate Sharing of Data
Data stored in the database can be shared among several
users.
 Database ensures Security
Data are protected against accidental or intentional disclosure
to unauthorized person or unauthorized modification.
 Database maintains Integrity
It enforces certain integrity rules to insure the validity or
correctness of data. For ex. A date can’t be like 25/25/2000.
www.ipzone.wordpress.com
Data Model- Way of data organisation
Data model is a model or presentation which shows How data is
organized ? or stored in the database. A data is modeled by one of
the following given-
 Relational Data Model
In this model data is organized into Relations or Tables (i.e. Rows
and Columns). A row in a table represents a relationship of data to
each other and also called a Tuple or Record. A column is called
Attribute or Field.
 Network Data Model
In this model, data is represented by collection of records and
relationship among data is shown by Links.
 Hierarchical Data Model
In this model, Records are organized as Trees. Records at top level
is called Root record and this may contains multiple directly linked
children records.
 Object Oriented Data Model
In this model, records are represented as a objects. The collection of
similar types of object is called class.
www.ipzone.wordpress.com
Representation of Data Models

Attribute (Field) Table (Relation)

Name Address DOB City Phone Entity


(Record)
Amar 2/3 Chowk 01.04.1990 Kanpur 12345
Kailash 22 Katra 23.10.1992 Lucknow 67890

Relational Model

R1 R1

E1 E2 E3
E1 E2 E3

Network Model Hierarchical Model

Representation of Records and Relationship in various Data Model


www.ipzone.wordpress.com
Basics of the Relational Data Model

Relational Databases stores data or information in tables. A table or Relation


is a two dimensional representation of data using rows and columns.
Relational Model was developed by E.F.Codd of the IBM and used widely in the
most of the DBMS. The following key-terms are used in the Relational Model-
 Relation (Table)
A Relation or Table is Matrix like structure arranged in Rows and Columns. It has
the following properties-
 Atomicity : Each column assigned a unique name and must have atomic
(indivisible) value i.e. a value that can not be further subdivided.
 No duplicity: No two rows of relation will be identical i.e. in any two rows
value in at least one column must be different.
 All items in a column are homogeneous i.e. same data type.
 Ordering of rows and column is immaterial.
 Domain :
It is collection of values from which the value is derived for a column.
 Tuple / Entity / Record - Rows of a table is called Tuple or Record.
 Attribute/ Field- Column of a table is called Attribute or Field.
 Degree - Number of columns (attributes) in a table.
 Cardinality - Number of rows (Records) in a table.
www.ipzone.wordpress.com
Concept of Keys
As discussed earlier, In a Relation each record must be unique i.e. no
two identical records are allowed in the Database.
A key attribute identifies the record and must have unique value.
 Primary Key
A primary key is a column in a table that is unique for each record.
Every table in a database should have a column or a group of
columns designated as the primary key. The value this key holds
should be unique for each record in the table.
Some common examples of Primary key are:
Admission Number in student table of School,
Accession Number of a Book in the Book table,
Employee ID of an employee in the Employee Table,
Item Code of an item in the Stock table etc.

A set of one or more attribute (column) that can identify a record


uniquely in the relation is called Primary Key.

www.ipzone.wordpress.com
Concept of Keys
 Candidate Key
Some time a table may have more than one column that uniquely
identifies a record in a table. All such columns are called Candidate
Keys because they all are having candidature to work as key.
A Candidate key also uniquely identifies a record. 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.
 Alternate Key
All candidate keys that not chosen as primary key are called
alternate keys. A Candidate Key that is not a Primary key is called
Alternate key.
 Foreign Key
A non-key attribute whose values are derived from the primary key
of some other table is called Foreign key. Foreign Key is used to
implement Referential Integrity in the Database. It establishes
relationship among two tables.

www.ipzone.wordpress.com
Concept of Keys- Example
Consider the following Student Table. The RollNo and Admission_no
both may be used to uniquely identify each record in the Table, so both
are candidate keys.
So, Candidate Keys are - RollNo and Admission_no
Pramary Key - Admission_No and
Alternate Key – RollNo or vice-versa.

Admission_No RollNo Name Class Marks


2301 1 Seema Chauhan 11 23
1501 2 Ajay Kumar 11 15
1678 3 Vansh Pratap 11 20
7003 4 Manohar Lal 11 15

www.ipzone.wordpress.com
Objective
In this presentation you will learn about-
 Introduction & features of MySQL
 MySQL and SQL
 Types of SQL Commands- DDL, DML, TCL
& DCL
 Data types in MySQL
 Creating Database & Tables
 Inserting, Deleting and modifying records
 Making Simple Queries
 Altering Table Structure
www.ipzone.wordpress.com
Introduction to MySQL
MySQL is an Open Source, Fast and Reliable Relational Database
Management System (RDBMS) software like Oracle, Sybase, MS SQL
Server etc. It was developed by Michael Widenius and AKA Monty and is
alternative to many of the commercial RDBMS.
The main features of MySQL are-
 Open Source & Free of Cost:
It is Open Source and available at free of cost.
 Portability:
It can be installed and run on any types of Hardware and OS like Linux,
MS Windows or Mac etc.
 Security :
It creates secured database protected with password.
 Connectivity
It may connect various types of Network client using different protocols
and Programming Languages .
 Query Language
It uses SQL (Structured Query Language) for handling database.
www.ipzone.wordpress.com
MySQL & SQL
In order to access data from the MySQL database, all
program and user must use SQL (Structured Query
Language). SQL is a set of commands that are
recognized by all the RDBMSs and has become a
standard language for database handling.
SQL is a language that enables you to create and manage
a relational database, in which all the information are
kept in tables.
There are numerous version of SQL. The original version
was developed at IBM’s San Jose Research Laboratory
with a name of Sequel, as a part of System R project
in 1970s. It was standardized by ANSI in 1986 by the
name of SQL.
SQL is a Standard Query language whereas MySQL is a DBMS Software
based on SQL.
www.ipzone.wordpress.com
Types of SQL Commands
MySQL follows SQL specifications for its commands . These
SQL commands can be categorized as -
 Data Definition Language (DDL)
These SQL commands are used to create, alter and delete
database objects like table, views, index etc.
Example : CREATE , ALTER , DROP etc.
 Data Manipulation Language (DML)
These commands are used to insert, delete, update and retrieve
the stored records from the table.
Ex. SELECT…., INSERT…, DELETE…, UPDATE…. etc.
 Transaction Control Language (TCL)
These commands are used to control the transaction.
Ex. COMMIT, ROLLBACK, SAVEPOINT etc.
 Data Control Language (DCL)
These commands are used to manipulate permissions or access
rights to the tables etc.
Ex. GRANT , REVOKE etc.
www.ipzone.wordpress.com
Data type in MySQL
 Numeric Data Types:
 INTEGER or INT – up to 11 digit number without decimal.
 SMALLINT – up to 5 digit number without decimal.
 FLOAT (M,D) or DECIMAL(M,D) or NUMERIC(M,D)
Stores Real numbers upto M digit length (including .) with D
decimal places.
e.g. Float (10,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 255 characters.
Char, Varchar, Date and Time values should be enclosed with single (‘ ‘) or
double ( “”) quotes in MySQL.
www.ipzone.wordpress.com
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
Select database();
mysql> DESCRIBE Student; Shows the name of
currently open database
www.ipzone.wordpress.com
Creating Tables & Inserting records
 Creating Simple Tables:
CREATE TABLE < Table Name>
(<Col name1><data type>[(size)],….);
Data types- INTEGER, NUMERIC(P,D), CHAR(n), VARCHAR(n), DATE etc.

mysql> CREATE TABLE Employee


(empID integer, Employee
ename char(30),
empID ename city pay
city char(25),
pay decimal(10,2));

 Inserting Records:
INSERT INTO <Table Name> VALUES (value1, vale2, …...);
String and Date type values must be enclosed in single or double quotes.
mysql> INSERT INTO Employee VALUES (1,‘Amitabh’,‘Allahabad’,15000);
mysql> INSERT INTO Employee VALUES (2, ‘Akbar’, ‘Dehradun’,20000);
mysql> INSERT INTO Employee VALUES (3, ‘Anthony’, ‘Mumbai’,10500);
www.ipzone.wordpress.com
Making Simple Queries Using SELECT
The SELECT command of SQL, empower you to make a
request (queries) to retrieve stored records from the
database.
The syntax of SQL is given below-
SELECT < [Distinct | ALL] *| column name(s)>
FROM <table(s)>
WHERE <condition>
ORDER BY <column name> [ASC | DESC] ;
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
www.ipzone.wordpress.com
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-
mysql> SELECT * FROM Student ;

MySQL will display the all records with all columns in the Student table.
* Is used to represent all columns.

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

www.ipzone.wordpress.com
Making Simple Queries – Cont..
 Selecting columns
If you want to view only Name and City columns of the student table
mysql> SELECT Name, City FROM Student ;
Name City
Amitabh Allahabad
Sharukh Delhi
Irphan Jaipur
Salman Mumbai
Abhishek Mumbai

mysql> SELECT City, Name FROM Student ;


City Name
Allahabad Amitabh
Delhi Sharukh
Jaipur Irphan
Mumbai Salman
Mumbai Abhishek
www.ipzone.wordpress.com
Making Simple Queries – Cont..
 Eliminating Duplicate values in a column - DISTINCT
mysql> SELECT City FROM Student ;
City
MySQL assumes ALL
Allahabad
keyword, if you are
Mumbai is repeated Delhi not using DISTICT
Jaipur keyword.
Mumbai
Mumbai

mysql> SELECT DISTINCT City FROM Student ;


City
Only Unique Cities
Allahabad
are displayed
Delhi
Jaipur
Mumbai
www.ipzone.wordpress.com
Making Simple Queries – Cont..
 Doing simple calculations
We can also perform simple calculations with SQL Select command. SQL provide
a dummy table named DUAL, which can be used for this purpose.
mysql> SELECT 4*3 ;
We can also extend this idea with a columns of the existing table.
mysql> SELECT Name, Sal *12 FROM EMP ;

 Using Column Aliases


We can give a different name to a column or expression (Alias) in the
output of a query.
Alias for Sal*12
mysql> SELECT Name, Sal*12 AS ‘Annual Salary’ FROM EMP;
mysql> SELECT Name, DOB AS ‘Date of Birth’ FROM Student;
mysql> SELECT 22/7 AS PI FROM Dual;

When Alias name is a single word then single quotes is


not required.
www.ipzone.wordpress.com
Selecting Specific Records – WHERE clause

 WHERE <Condition>
We can select specific records by specifying conditions 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

Name Fname City Class


Amitabh Harivansh Rai Allahabad 12
Sharukh Firoz Delhi 11
Irphan Akbar Jaipur 11
www.ipzone.wordpress.com
Selecting Specific Records – WHERE clause

 Relational Operators
We can use the following Relational operators in 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’;

www.ipzone.wordpress.com
Selecting Specific Rows – WHERE clause
 Specifying Range of Values – BETWEEN Operator
mysql> SELECT * FROM Emp
WHERE Sal BETWEEN 5000 AND 10000 ;
The same query can also be written as -
mysql> SELECT * FROM Emp
WHERE Sal >= 5000 AND Sal<=10000 ;
Other Logical operators also can be applied-
mysql> SELECT * FROM Emp
WHERE NOT Sal BETWEEN 5000 AND 10000 ;

 Specifying List – IN Operator


mysql> SELECT * FROM Emp
WHERE Sal IN (5000, 10000) ;
The same query can also be written as -
mysql> SELECT * FROM Emp
WHERE Sal = 5000 OR Sal =10000 ;

mysql> SELECT * FROM Student


WHERE City IN (‘Mumbai’, ‘Delhi’,’Kanpur’) ;
www.ipzone.wordpress.com
Selecting Specific Rows – WHERE clause

 Pattern Matching – LIKE Operator


A string pattern can be used in SQL using the following wild card
 % Represents a substring in any length
 _ Represents a single character
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%’ ;
www.ipzone.wordpress.com
Selecting Specific Rows – WHERE clause
 Searching NULL Values – IS Operator
mysql> SELECT * FROM Student WHERE City IS NULL ;
The NOT Operator can also be applied -
mysql> SELECT * FROM Student WHERE City IS NOT NULL;

 Ordering Query Result – ORDER BY Clause


A query result can be orders in ascending (A-Z) or descending (Z-A)
order as per any column. Default is Ascending order.
mysql> SELECT * FROM Student ORDER BY City;
To get descending order use DESC key word.
mysql> SELECT * FROM Student ORDER BY City DESC; You can also use
Alias column
mysql> SELECT Name, Fname, City FROM Student with ORDER BY
Where Name LIKE ‘R%’ ORDER BY Class; clause

mysql> SELECT Name, Basic+DA AS ‘PAY’ FROM Student ORDER BY PAY;


www.ipzone.wordpress.com
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>
If value is not available for a column, NULL can be used.
Suppose a table STUDENT has been created as per given structure-
StID NAME FNAME DOB CITY CLASS

The sequence of values


We can insert a record as follows- should match with order
of columns.
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)
You can also
VALUES (‘s3’,’Amitabh’, ’Abhishek’, 10); define order
www.ipzone.wordpress.com of columns.
Inserting Records from Other Table
You can insert all or selected record(s) in the table from
another table by using Select … command in place of Values.
Suppose a table named NEWSTUDENT has been created and
records to be inserted from OLDSTUDENT table having the
same structure of columns.
mysql> INSERT INTO Newstudent VALUES Both tables must
(SELECET * FROM Oldstudent); have same column
structure

mysql>INSERT INTO Newstudent VALUES


(SELECT * FROM Oldstudent WHERE City=‘Mumbai’);
mysql> INSERT INTO Newstudent (StID, Name, Class)
VALUES (Select StID, Name,Class FROM Oldstudent
WHERE Class>=11); You can also select
columns from both
tables.
www.ipzone.wordpress.com
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>]
Caution!!! This command
mysql> DELETE FROM Student ;
will delete all records…

mysql> DELETE FROM Student WHERE City=‘Mumbai’ ;


mysql> DELETE FROM Student WHERE Class >=11 ;
mysql> DELETE FROM Student WHERE Class <9 AND City=‘Delhi’;

 You can recall (Undelete) records by giving ROLLBACK command.


mysql> ROLLBACK ;
 You can issue COMMIT command to record the changes permanently.
mysql> COMMIT;

www.ipzone.wordpress.com
Modifying Records –UPDATE Command
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 Student SET FName= CONACT(‘Mr.’, FName’) ;

mysql> UPDATE Emp SET Sal = Sal+(Sal*10/100);

mysql> UPDATE Emp SET Sal = Sal+(Sal*10/100)


WHERE Sal <=10000;
mysql> UPDATE Emp SET City = ‘Dehradun’
WHERE CITY IS NULL;

www.ipzone.wordpress.com
Working with Tables
 Creating Tables:
CREATE TABLE < Table Name>
(<Col name><data type>[(size)][Constraints], ..…)
 Data types - Commonly used data types are-
INTEGER, DECIMAL(P,D), NUMERIC(P,D), CHAR(n), VARCHAR(n),
DATE etc.

Employee ( EmpID, Ename, Sex, DOB, Pay )

mysql> CREATE TABLE Employee


(EmpID integer,
Ename char(20),
Sex char(1),
Dob Date,
Pay decimal (8,2));
www.ipzone.wordpress.com
Creating Table with Constraints
One of the major responsibility of a DBMS is to maintain the
Integrity of the data i.e. Data being stored in the Database
must be correct and valid.
An Integrity Constraints are condition or checks applicable to a
column or table which ensures the integrity and validity of data.
The following constraints are available in MySQL.

Constraints Description
NOT NULL Ensures that a column cannot have NULL value.
PRIMARY KEY Used to identify a row uniquely.
DEFAULT* Provides a default value for a column, if no value is given.
UNIQUE* Ensures that all values in a column are different.
CHECK* Ensures that value for a column should satisfy certain
condition.
FOREIGN KEY* Used to ensure Referential Integrity of the data.

* Not included in the syllabus (recommended for advanced learning)


www.ipzone.wordpress.com
Implementing Constraints in the Table
 NOT NULL
This constraints specifies that column must not contain NULL value i.e. value
for the column must be given (mandatory)
 PRIMARY KEY
This constraints declare a column as the primary key. Since Primary key
must not have NULL value, so it is used with NOT NULL constraints.
 UNIQUE
This constraints ensures that the value for the column should be Unique i.e. no
two records have the same (duplicate) value.
mysql> CREATE TABLE Student
Generally
(StCode char(3) NOT NULL PRIMARY KEY,
Constraints are
Stname char(20) NOT NULL, defined with
StAdd varchar(40), Column definitions
AdmNo char(5) UNIQUE, i.e. Column level
StAge integer CHECK (StAge>=5) );

UNIQUE  UNIQUE allows NULL values but PRIMERY KEY does not.
v/s  A table may have multiple UNIQUE constraints, but there
PRIMARY KEY must be only one PRIMERY KEY constraints in a table.
www.ipzone.wordpress.com
Implementing Primary Key Constraints

 Defining Primary Key at Column Level:


mysql> CREATE TABLE Student
( StCode char(3) NOT NULL PRIMARY KEY,
Stname char(20) NOT NULL,
StAge int(2) );

 Defining Primary Key at Table Level:


mysql> CREATE TABLE Student
PRIMARY KEY
( StCode char(3) NOT NULL,
Constraint is
Stname char(20) NOT NULL,
defined after all
StAge int(2),
column definitions
PRIMARY KEY (StCode) ); (Table Level).

A Composite (multi-column) Primary key can be defined as only


a Table level whereas Single-column Primary key can be defined
in both way i.e. Column level or Table level.
www.ipzone.wordpress.com
Handling Tables
 Viewing Table Structure:
You can view structure of any table after using database as-
DESC[RIBE] <table name>
mysql> DESC Student;
 Deleting Table:
You can delete an existing table as-
DROP TABLE [IF EXIST] <table name>
mysql> DROP TABLE Student;
 Creating Table from Existing Table:
CREATE TABLE <Table name>
AS (<Select Query>);

mysql> CREATE TABLE Staff


( Select empID, ename, sex From Emp);

mysql> CREATE TABLE Staff It will create identical


( Select * From Emp); table as Emp
www.ipzone.wordpress.com
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 (name, 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.
www.ipzone.wordpress.com
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 Employee MODIFY (Pay DECIMAL (10,2));
 Removing Column & Constraints
ALTER TABLE <Table Name>
DROP <Column name> |<Constraints>
mysql> ALTER TABLE Student DROP TelNo;
mysql> ALTER TABLE Emp DROP JOB, DROP Pay;
www.ipzone.wordpress.com
Objective
In this presentation, you will learn about-
 Introduction to MySQL Functions.
 Types of MySQL Functions
 Numeric Functions
 String Functions
 Date & Time Functions
 Aggregate Functions

www.ipzone.wordpress.com
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:
 Numeric Functions
 String Functions
 Date & Time Function
 Aggregate Functions

 Numeric, String and Date-Time functions are called Single row


functions because they can accept one row and return only one value.
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.
www.ipzone.wordpress.com
Numeric Functions

These functions may accept some numeric values and performs


required operation, returns numeric values as result.
Name Purpose Example
MOD (M, N) Returns remainder of M Select MOD(11,4) ;
divide by N 3
POWER (M, N) Returns MN Select POWER(3,2);
POW (M, N) 9
ROUND (N [,M]) Returns a number rounded Select ROUND(15.193,1);
off up to M place. If M is -1, 15.2
it rounds nearest 10.
Select ROUND(15.193);
If M is not given, then N is 15
rounded to the nearest
Integer. Select ROUND(-1.58);
-2
SQRT (N) Returns square root of N Select SQRT(25);  5

TRUNCATE(N,M) Returns number after Select TRUNCATE(15.79,1)


truncating M decimal place.  15.7
www.ipzone.wordpress.com
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’ ) FROM DUAL;
4
mysql> SELECT Name, LENGTH(Name) FROM Student;
www.ipzone.wordpress.com
String Functions cont…
 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;
www.ipzone.wordpress.com
String Functions cont…

 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
www.ipzone.wordpress.com
String Functions cont…
 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;
www.ipzone.wordpress.com
String Functions cont…
 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
Substr()
mysql> SELECT MIDwww.ipzone.wordpress.com
(Name, 4,3) FROM Student;
Summery of 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
www.ipzone.wordpress.com
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 www.ipzone.wordpress.com
as SYSDATE() changes its time continuously.
Date & Time Functions cont…
 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());
www.ipzone.wordpress.com
Date & Time Functions cont…

 DAYOFMONTH()
Returns day of month of the given date expression.
DAYOFMONTH (Dt)
mysql> SELECT DAYOFMONTH(‘2008-12-31’) ;
 31
mysql> SELECT DAYOFMONTH( CURDATE()) ;
mysql> SELECT DAYOFMONTH( DOB) FROM Student;

 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;
www.ipzone.wordpress.com
Date & Time Functions cont…

 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;

www.ipzone.wordpress.com
Summery of 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

MONTH() Returns the Month/Yearfrom Select MONTH(‘2012-10-02’);


YEAR() given date argument.  10

DAYNAME() Returns the name of the Select DAYNAME(CURDATE());


weekday  SUNDAY

DAYOFMONTH() Returns the day of month Select


(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());

www.ipzone.wordpress.com
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=‘Jaipur’;
 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=‘Jaipur’;
 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’;
www.ipzone.wordpress.com
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’;
www.ipzone.wordpress.com
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 Select MIN(Pay) from Emp;
in the given column.
MAX() Returns the maximum value Select MAX(Pay) from Emp;
in 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;
www.ipzone.wordpress.com

You might also like