Handbook MYSQL
Handbook MYSQL
A database is an organized collection of interrelated data stored together to serve applications. It work like a
container which may contains the various database objects.
Most of the databases stores data in the form of Relations (also called Tables). Such Database are known as
Relational Database.
A Software used to manage Relational database is called RDBMS (Relational Database Management System
Some Commonly used RDBMS software are- Oracle, MySQL, MS SQL Server, SyBase and Ingress etc.
Database 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.
Data Model
Data model describes ‘How data is organized or stored’ in the database. It may be-
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.
RDBMS TERMINOLOGY
Relation (Table)
A Relation or Table is Two-Dimensional (Matrix) like structure arranged in Rows and Columns. It has
the following properties-
Column homogeneous - All items in a column are of same data type.
Each column assigned a unique name and must have atomic (indivisible) value.
All rows of a relation are distinct i.e. no two identical rows (records) can exist in the Relation.
Ordering or Rows (Records) or Columns (fields) are immaterial.
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:
Column of a table is called Attribute or Field. Degree
: Number of columns (attributes) in a table.
Cardinality : Number of Records in a table.
CONCEPT OF KEYS
In a Relation, each record must be unique i.e. no two identical records are allowed in the Database. A
column or combination of column which identifies a record called Key of the Table. A key attribute must
have unique (non-repeatable ) value.
Primary Key
A set of one or more column that can uniquely identify a record in the relation is called Primary Key.
Candidate Key
A Column or group of columns which can be used as primary key are called Candidate keys, as they are
candidate to become as Primary key.
Alternate Key
A Candidate Key that is not a Primary key is called Alternate key.
Foreign Key
A non-key column whose values are derived from the primary key of some other table is called Foreign key.
INTRODUCTION TO SQL
MySQL is an Open Source, Fast and Reliable Relational Database Management System (RDBMS) . It 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 free of cost. It is part of LAMP (Linux, Apache, MySQL, PHP/ Perl/
Python) Open Source 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 privilege and password system for authorization.
Connectivity
It may connect various types of client using different protocols and Programming Languages .
Query Language
It uses SQL (Structured Query Language) as query language, which is standardized by ANSI.
Creating a Database.
The following command will create School database in MySQL. mysql> CREATE DATABASE college;
Opening a database
To open an existing database, following command is used. mysql> USE college ;
CREATING TABLES
CREATING SIMPLE TABLES:
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));
Creating Table from Existing Table:
CREATE TABLE <Table name> [AS] (<Select Query>);
CREATE TABLE Staff ( Select empID, ename, pay From Emp);
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
Name City
Amitabh Allahabad
Sharukh Delhi
Irphan Jaipur
Salman Mumbai
Abhishek Mumbai
City
Allahabad
Delhi
Jaipur
Mumbai
Mumbai
MYSQL>SELECT DISTINCT city from student;
City
Allahabad
Delhi
Jaipur
Mumbai
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;
WHERE clause(Operator)
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;
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.
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 (SELECET * FROM Oldstudent);
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 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 Student ;
delete all records…
mysql> DELETE FROM Student WHERE City=‘Mumbai’ ; mysql> DELETE FROM Student WHERE Class
>=11 ;
• You can recall (Undelete) records by giving ROLLBACK command.
mysql> ROLLBACK ;
• You can issue COMMIT command to record the changes permanently.
mysql> COMMIT;
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.
Sal+(Sal*10/100);
What is Function?
• A function is a special types of command that performs some operation and returns a single value as a
result.
• It is similar to method or function in JAVA, which can be called by giving some argument.
Types of Functions:
Numeric Functions
String Functions
Date & Time Function
Aggregate Functions
Numeric Functions
These functions may accept some numeric values and performing required operation, returns numeric values as
result
String functions
Name Purpose Example
CONCAT(str1,str2) Returns concatenated string i.e. str1+str2. 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)Removes Leading/Trailing/both spaces from Select TRIM(‘ ABC ‘);
TRIM(str) given string. ‘ABC’
LEFT(str, N) RIGHT(str,N) Returns the (N) characters from left/right from Select LEFT(‘Computer’,4);
the given string. Comp
SUBSTR(str,P,[N]) / MID Returns the substring for given position(P) and Select SUBSTR(‘Computer’,3,2);
(str,P,N) length (N). If M is (- ve) then backward position mp
counted.
INSTR(str1,str2) Returns the index of first occurrence of str2 in Select INSTR(‘Common’, ’m’);
str1. 3
LENGTH(str) Returns the length of given string Select LENGTH(‘Common’);
6
Aggregate function:
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 Columnor 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)>
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 MODIFY (Sal 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;
More On Database & SQL– Advanced Concepts
Integrity 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 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
PRIMARY KEY
UNIQUE *
DEFAULT *
CHECK *
FOREIGN KEY *
Type of Constraints
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.
UNIQUE v/s PRIMARY KEY
UNIQUE allows NULL values but PRIMERY KEY does not.
Multiple column may have UNIQUE constraints, but there is only one PRIMERY KEY constraints in a table.
Implementing Primary Key Constraints
mysql> ALTER TABLE Student DROP TelNo; mysql> ALTER TABLE Emp DROP JOB, DROP
Pay;
mysql> ALTER TABLE Student DROP PRIMARY KEY;
Changing Column Name of Existing Column
ALTER TABLE <Table Name> CHANGE <Old name><New Definition> mysql> ALTER TABLE
Student
CHANGE Name Stname Char(40);
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 ByJob;
Using MIN (<column>)
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
The Natural Join is much similar to Equi Join i.e. records are joined on the equality condition of Joining Column except
that the common column appears one time.
Consider the following table R and S having C as Join column.
How to Join ?
MySQL offers different ways by which you may join two or more tables.
Method 1 : Using Multiple table with FROM clause
The simplest way to implement JOIN operation, is the use of multiple table with FROM clause followed with
Joining condition in WHERE clause.
Select * From EMP, DEPT
Where Emp.DeptNo = Dept.DeptNo ;
If common column are differently spelled then no need to use Qualified name.
Method 2: Using JOIN keyword
MySQL offers JOIN keyword, which can be used to implement all type of Join operation.
Select * From EMP JOIN DEPT ON Emp.DeptNo=Dept.DeptNo ;
Using Multiple Table with FROM clause
Ex. Find out the name of Employees working in same city from where they belongs (hometown) .
Select Ename From EMP JOIN DEPT ON Emp.DeptNo = Dept.DeptNo WHERE City=Location;
Nested Query (A query within another query)
Sometimes it is required to join two sub-queries to solve a problem related to the single or multiple table. Nested query
contains multiple query in which inner query evaluated first.
The general form to write Nested query is-
Select …. From <Table>
Where <Column1> <Operator>
(Select Column1 From <Table> [Where <Condition>])
Ex. Find out the name of Employees working in Production Deptt.
Select Ename From EMP
Where DeptNo = (Select DeptNo From DEPT Where
DName=‘Production’);
Ex. Find out the name of Employees who are getting more pay than ‘Ankit’.
Select Ename From EMP
Where Pay >= (Select Pay From EMP Where Ename=‘Ankit’ );
Union of Tables
Sometimes it is required to combine all records of two tables without having duplicate records. The combining
records of two tables is called UNION of tables.
UNION Operation is similar to UNION of Set Theory.
E.g. If set A= {a,c,m,p,q} and Set B= {b,m,q,t,s} Then AUB= {a,c,m,p,q,b,t,s}
[All members of Set A and Set B are taken without repeating] Select …. From <Table1>[Where <Condition>]
UNION [ALL]
Select …. From <Table2> [Where <Condition>];
Ex. Select Ename From PROJECT1 UNION
Select Ename From PROJECT2 ;
)