11th IP Unit-3 Database Concept and SQL
11th IP Unit-3 Database Concept and SQL
www.ipzone.wordpress.com
What is the Database Management System
(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
Relational Model
R1 R1
E1 E2 E3
E1 E2 E3
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.
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.
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 –
MySQL will display the all records with all columns in the Student table.
* Is used to represent all columns.
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
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
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 (!)
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 ;
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>]
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.
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.
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
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
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.
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
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
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