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

13-MySQL Basics cs 12

Uploaded by

studyornomoney7
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)
29 views

13-MySQL Basics cs 12

Uploaded by

studyornomoney7
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/ 47

Revised as

Computer Science per


CBSE
Curriculum
Class XII (CBSE Board) 2020-21

UNIT-3: Database Management


Chapter: 13
Working with MySQL

Visit www.ip4you.blogspot.com for more….

Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.)


Kendriya Vidyalaya Khanapara, Guwahati (Assam)
e-mail : [email protected]
Expected Learning Outcome
In this presentation you will learn about
commands of MySQL Database Application.
 Introduction and features of MySQL?
 SQL and MySQL
 Type of Commands in MySQL
 MySQL elements
 Data types in MySQL
 Working with DML commands
 Working with MySQL Functions
 Working with DDL commands
Introduction to MySQL
 MySQL is an open source, free and powerful
Relational Database Management System (DBMS)
that uses SQL.
 It was developed by Michael Widenius (“Monty”) and
Axmark. It was named after Monty’s daughter My.
The logo of MySQL– the dolphin, is named as
Sakila.
 It is widely used RDBMS product and is alternative
to many of the commercial RDBMS.
 MySQL was originally created and distributed by
MySQL AB, a Sweden based company but now it is
distributed by Oracle Corporation.
 The latest version of MySQL is MySQL 8.0
 It can be freely downloaded from www.mysql.org
SQL & MySQL
SQL (Structured Query Language) is widely used Query
language that enables you to create and manage a
relational database. SQL offers set of commands that are
recognized by all the RDBMSs and has become a standard
language for database handling.
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 (American National Standard
Institute) in 1986 by the name of SQL. The latest ISO
version was released in 2008 as SQL:2008
In order to access data stored in the MySQL database, all
program and user must use SQL commands.
SQL is a Standard Query language whereas MySQL is a RDBMS Software
based on SQL.
Introduction to MySQL
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 S/w group.
 Portability:
It can be installed and run on any types of Hardware and OS like
Linux, MS Windows or Mac etc.
 Security :
It offers security and authorization feature to keep database secure.
 Connectivity
It may connect various types of client using different protocols and
Programming Languages like Python, Java etc.
 Query Language
It uses SQL (Structured Query Language) as query language, which
is standardized by ANSI.
Types of SQL Commands
MySQL Commands

DDL DML TCL DCL


CREATE SELECT COMMIT GRANT

ALTER INSERT ROLLBACK REVOKE

DELETE SAVEPOINT
DROP

UPDATE DDL: Database & Table level


DML: Record level
TCL: Transaction level
DDL & DML are basic categories
DCL: Security & Privacy level
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.
Elements of MySQL
MySQL uses various keywords, operators and symbols as a
part of a command. The major elements are-
 Literals –
Literals are constant values which may be numbers, strings and
date etc. String, Date and Time literals must be enclosed in single
or double quotes.
Example : 5, 45.67, ‘Amitabh’ , ‘New Delhi’, “2020-03-10” etc.
 Operators -
Operators are special words or symbols to perform any operation on
its operands.
Example : S+,-,/,*, <,>, =, NOT , IS, BETWEEN etc.
 NULL - Null is a special word represents empty or missing
information . It is not 0 or space.
 Comment – Comments are non executable remarks.
Example : # This is single line comment
/* This is multiline comment */
Use - Command used to open database
Data types in MySQL
 Numeric Data Types:
 INTEGER / INT – up to 11 digit number without decimal.
 SMALLINT – up to 5 digit number without decimal.
 FLOAT (M,D) / DECIMAL(M,D) / NUMERIC(M,D)
Stores Real numbers upto M digits with D decimal places.
e.g. Float (9,2) can store 1234567.89
 Date & Time Data Types:
 DATE - Stores date in YYYY-MM-DD format.
 TIME - Stores time in HH:MM:SS format.
 String or Text Data Type:
 CHAR(Size) :
A fixed length string up to 255 characters. (default is 1)
 VARCHAR(Size) :A variable length string up to 65535 characters.
 VARCHAR2(Size) : Same as Varchar datatype.
(VARCHAR2 is not available in MySQL, it is available in Oracle only)
Char, Varchar, Date and Time values should be enclosed with single (‘ ‘) or
double ( “”) quotes in MySQL.
Database Handling commands in MySQL

 Creating a Database.
The following command will create School database in MySQL.
mysql> CREATE DATABASE School;
 Opening a database
To open an existing database, following command is used.
mysql> USE school ;
 Getting listings of database and tables
mysql> SHOW DATABASES;
mysql> SHOW TABLES;
 Deleting a Database and Table
mysql> DROP DATABASE School;
mysql> DROP TABLE Student;
 Viewing Table Structure
Select database();
mysql> DESCRIBE Student; Shows the name of
currently open database
Working with MySQL Tips: Remember
N-D-S-C
N-Name, D- Data type,
 Creating Simple Tables: S- Size, C- Constraints
CREATE TABLE < Table Name>
(<Col name1><data type>[(size)] [Constraints],….);
Data types- INTEGER, NUMERIC(P,D), CHAR(n), VARCHAR(n), DATE etc.
mysql> CREATE TABLE Emp (empID integer,ename char(30),
city char(25), pay decimal(10,2));

All commands
in MySQL
are ended
with ;

Emp
empID ename city pay
Making Simple Queries Using SELECT
The SELECT command of SQL, empowers you to make a
request (queries) to retrieve stored records from the table.
The syntax of SQL is given below-
Syntax Notation: <> User given values [ ] optional clause
SELECT < [Distinct | ALL] *| column name(s)>
FROM <table(s)> [WHERE <condition> ]
[ORDER BY <column(s)> [ASC | DESC] ] ;
[GROUP BY <column(s)> [HAVING <condition>] ] ;
Consider the table Student having some records as –
StID Name Fname DOB City Class
S1 Amitabh Harivansh Rai 1948-11-10 Allahabad 12
S2 Sharukh Firoz 1970-05-10 Delhi 11
S3 Irphan Akbar 1970-10-05 Jaipur 11
S4 Salman Salim Javed 1972-04-10 Mumbai 10
S5 Abhishek Amitabh 1975-03-12 Mumbai 10
Making Simple Queries – Cont..
 Selecting all columns
If you want to view all columns of the student table, then you
should give the following command- * represents
mysql> SELECT * FROM Student ; all columns.

MySQL will display the all records with all columns in the Student table.

StID Name Fname DOB City Class


S1 Amitabh Harivansh Rai 1948-11-10 Allahabad 12
S2 Sharukh Firoz 1970-05-10 Delhi 11
S3 Irphan Akbar 1970-10-05 Jaipur 11
S4 Salman Salim Javed 1972-04-10 Mumbai 10
S5 Abhishek Amitabh 1975-03-12 Mumbai 10
Making Simple Queries – Cont..
 Selecting specific 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 ;


Note that MySQL
City Name gives result as
Allahabad Amitabh per order of
Delhi Sharukh columns given in
Jaipur Irphan
the Select
command
Mumbai Salman
Mumbai Abhishek
Making Simple Queries – Cont..
 Eliminating Duplicate values in a column -
DISTINCT
mysql> SELECT City FROM Student ;

City Mumbai is repeated


Allahabad
Delhi
Jaipur
Mumbai
Mumbai

mysql> SELECT DISTINCT City FROM Student ;

City
Only Unique Cities
Allahabad
are displayed
Delhi
Jaipur
Mumbai
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 also be used.
mysql> SELECT 4*3 ; OR SELECT 4*3 FROM DUAL;

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 ‘ ‘ is not required.


Selecting Specific Rows – WHERE clause
 WHERE <Condition>
We can select specific records by specifying condition with
WHERE clause.
mysql> SELECT * FROM Student WHERE City=‘Mumbai’;
StID Name Fname DOB City Class
S4 Salman Salim Javed 1972-04-10 Mumbai 10
S5 Abhishek Amitabh 1975-03-12 Mumbai 10

mysql> SELECT Name, Fname, City from Student


WHERE Class >10; Condition
uses
columns
Name Fname City Class
and
Amitabh Harivansh Rai Allahabad 12 operators
Sharukh Firoz Delhi 11
Irphan Akbar Jaipur 11
Selecting Specific Rows – WHERE clause

 Relational Operators
We can use the following Relational operators while making
condition.
=, > , < , >=, <=, <>, IS , LIKE, IN, BETWEEN
 Logical Operators
We can use the following Logical Operators to connect two
conditions.
OR , AND , NOT (!)
mysql> SELECT Name, City from Student
WHERE City <> ‘Mumbai’ AND Class>10;

mysql> SELECT * FROM Emp


WHERE Sal >10000 OR Job =‘Manager’;

mysql> SELECT * FROM Student


WHERE NOT Grade=‘A’;
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’) ;
Selecting Specific Rows – WHERE clause

 Pattern Matching – LIKE Operator


A string pattern can be used in SQL using the following wild cards
 % Represents a substring in any length
 _ Represents a single character at used 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%’ ;
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;

Never compare NULL using = operator… City= NULL

 Ordering Query Result – ORDER BY Clause


A query result can be arranged in ascending (A-Z) or descending
(Z-A) order as per any column. Default is Ascending order.
mysql> SELECT * FROM Student ORDER BY City;

ASC is used for Ascending and DESC is used for descending order.

mysql> SELECT * FROM Student ORDER BY City DESC;


mysql> SELECT Name, Fname, City FROM Student
Where Name LIKE ‘R%’ ORDER BY Class;
Grouping Records in a Query- GROUP BY Clause

 Some time it is required to apply a Select query in a group


of records instead of whole table.
 You can group records by using GROUP BY <column>
clause with Select command. A group column is chosen
which have non-distinct (repeating) values like City, Job etc.
 Generally, the following Aggregate Functions are applied on
groups.
Name Purpose
SUM() Returns the sum of given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given
column.
Aggregate Functions & Group
An Aggregate function may applied on a column with DISTINCT
or ALL keyword. If nothing is given ALL is assumed.
 Using SUM (<Column>)
This function returns the sum of values in given column or
expression.
mysql> Select Sum(Sal) from EMP;
mysql> Select Sum(DISTINCT Sal) from EMP;
mysql> Select Sum (Sal) from EMP where City=‘Kanpur’;
mysql> Select Sum (Sal) from EMP Group By City;
mysql> Select Job, Sum(Sal) from EMP Group By Job;
 Using MIN (<column>)
This functions returns the Minimum value in the given column.
mysql> Select Min(Sal) from EMP;
mysql> Select Min(Sal) from EMP Group By City;
mysql> Select Job, Min(Sal) from EMP Group By Job;
Aggregate Functions & Group

 Using MAX (<Column>)


This function returns the Maximum value in given column.
mysql> Select Max(Sal) from EMP;
mysql> Select Max(Sal) from EMP where City=‘Kanpur’;
mysql> Select Max(Sal) from EMP Group By City;
 Using AVG (<column>)
This functions returns the Average value in the given column.
mysql> Select AVG(Sal) from EMP;
mysql> Select AVG(Sal) from EMP Group By City;
 Using COUNT (<*|column>)
This functions returns the number of rows in the given column.
mysql> Select Count (*) from EMP;
mysql> Select Count(Sal) from EMP Group By City;
mysql> Select Count(*), Sum(Sal) from EMP Group By Job;
Aggregate Functions & Conditions

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


<condition> clause is used to apply a condition on a group.
mysql> Select Job, Sum(Pay) from EMP
Group By Job HAVING Sum(Pay)>=8000; ‘Having’ is
mysql> Select Job, Sum(Pay) from EMP used with
Group By
Group By Job HAVING Avg(Pay)>=7000;
Clause only.
mysql> Select Job, Sum(Pay) from EMP
Group By Job HAVING Count(*)>=5;
mysql> Select Job, Min(Pay),Max(Pay), Avg(Pay) from EMP
Group By Job HAVING Sum(Pay)>=8000;
mysql> Select Job, Sum(Pay) from EMP Where City=‘Dehradun’
Group By Job HAVING Count(*)>=5;

Where clause works in respect of whole table but Having works


on Group only. If Where and Having both are used then Where
will be executed first.
Aggregate Functions & NULL Values
Consider a table Emp having following records as-

Emp
Code Name Sal
Aggregate function
ignores NULL values i.e.
E1 Ram Kumar NULL NULL values does not
E2 Suchitra 4500 play any role in
E3 Yogendra NULL calculations.
E4 Sushil Kr 3500
E5 Lovely 4000

mysql> Select Sum(Sal) from EMP;  12000


mysql> Select Min(Sal) from EMP;  3500
mysql> Select Max(Sal) from EMP;  4500
mysql> Select Count(Sal) from EMP;  3
mysql> Select Avg(Sal) from EMP;  4000
mysql> Select Count(*) from EMP;  5
Working with Functions

 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 library functions in Python,
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.

Name Purpose Example


MOD (M, N) Returns remainder of M divide Select MOD(11,4) ;
by N 3
POWER (M, N) Returns MN Select POWER(3,2);
POW (M, N) 9
ROUND (N [,M]) Returns a number rounded off Select ROUND(15.193,1);
up to M place. If M is -1, it 15.2
rounds nearest 10. Select ROUND(15.193);
If M is not given, the N is 15
rounded to the nearest Integer.
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
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
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/Year from 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());


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;
Inserting Records in a Table
You can insert record in the table by using by using the
following DML command.
INSERT INTO <Table Name> [<Column list>]
VALUES <list of values>
Suppose a table named STUDENT has been created with the
following structure.
StID NAME FNAME DOB CITY CLASS

We can insert a record as follows-


mysql> INSERT INTO Student VALUES
(‘s1’,’Amitabh’, ‘Harivansh’,’1955-10-25’, ‘Mumbai’, 12);
mysql> INSERT INTO Student VALUES
(‘s2’,’Sharukh Khan’, NULL,’1972-5-25’, ‘Delhi’, 10);
mysql> INSERT INTO Student (StID, FName, Name, Class)
VALUES (‘s3’,’Amitabh’, ’Abhishek’, 10);
For missing or unknown values, we can use NULL
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. Both tables must
have same structure
mysql> INSERT INTO Newstudent VALUES
i.e. same types of
(SELECET * FROM Oldstudent); columns in same
order
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); If tables are in
different structure, we
can specify columns.
Deleting Records from the Table
You can delete all or selected record(s) from the table by using
the following DML command.

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

This command will


mysql> DELETE FROM 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, if Auto commit is off. Give
mysql> ROLLBACK ; SET AUTOCOMMIT=0
 You can issue COMMIT command to record To disable Auto save
the changes permanently. feature in MySQL
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.

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;
Creating Tables 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 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 Most of the constraints are applied with
 DEFAULT Column definition which are called Column-
Level (in-line Constraints) ,but some of
 CHECK
them may be applied at column Level as
 FOREIGN KEY well as Table-Level (Out-line
constraints) i.e. after defining all the
columns. Ex.- Primary Key & 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

Defining Primary Key at Column Level:


mysql> CREATE TABLE Student
( StCode char(3) NOT NULL PRIMARY KEY,
Stname char(20) NOT NULL,
………………………..
);

Defining Primary Key at Table Level:


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

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.
Implementing Constraints in the Table

mysql> CREATE TABLE Student


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

StSex char(1) DEFAULT ‘M’,


StAge integer CHECK (StAge>=5) );

CREATE TABLE EMP ( Code char(3) NOT NULL, Table level


Name char(20) NOT NULL, constraints are
defined after all
City varchar(40), column definitions.
Pay Decimal(10,2),
PRIMARY KEY (Code) );
Implementing Foreign Key Constraints
 A Foreign key is non-key column in a table whose value is
derived from the Primary key of some other table.
 Each time when record is inserted or updated in the table,
the other table is referenced. This constraints is also called
Referential Integrity Constraints.
 This constraints requires two tables in which Reference table
(having Primary key) called Parent table and table having
Foreign key is called Child table.

EMPLOYEE DEPARTMENT Primary


EmpID DeptNo key
Name DeptName
Foreign
City Head
Key
Sal Location
DeptNo Parent Table
Child Table
Implementing Foreign Key Cont..
Parent
CREATE TABLE Department table
( DeptNo char(2) NOT NULL PRIMARY KEY,
DeptName char(10) NOT NULL,
Head char(30) );

Child Table in
CREATE TABLE Employee
which Foreign
( EmpNo char(3) NOT NULL PRIMARY KEY, key is defined.
Name char(30) NOT NULL,
City char(20),
Sal decimal(8,2), Parent table and column
to be referenced..
DeptNo char(2),
FOREGIN KEY (DeptNo) REFERENCES Departmet (DeptNo));

 A Table may have multiple Foreign keys.


 Foregn key may have repeated values i.e. Non-Key Column
Modifying Table Constraints
 Adding new column and Constraints
ALTER TABLE <Table Name>
ADD <Column>[<data type> <size>][<Constraints>]
mysql> ALTER TABLE Student ADD (TelNo Integer);
mysql> ALTER TABLE Student ADD (Age Integer CHECK (Age>=5));
mysql> ALTER TABLE Emp ADD Sal Number(8,2) DEFAULT 5000 ;
mysql> ALTER TABLE Emp ADD PRIMARY KEY (EmpID);
mysql> ALTER TABLE Emp ADD PRIMARY KEY (Name,DOB);

 Modifying Existing Column and Constraints


ALTER TABLE <Table Name>
MODIFY <Column>[<data type> <size>] [<Constraints>]
mysql> ALTER TABLE Student MODIFY Name VARCHAR(40);
mysql> ALTER TABLE Emp MODIFY (Sal DEFAULT 4000 );
mysql> ALTER TABLE Emp MODIFY (EmpName NOT NULL);
Modifying Table Constrains cont..
 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;

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);
Viewing & Disabling Constraints
 To View the Constraints
The following command will show all the details like
columns definitions and constraints of EMP table.
mysql> SHOW CREATE TABLE EMP;
Alternatively you can use DESCribe command:
mysql> DESC EMP;

 Enabling / Disabling Foreign Key Constraint


 You may enable or disable Foreign key constraints by
setting the value of FOREIGN_KEY_CHECKS variable.
 You can’t disable Primary key, however it can be
dropped (deleted) by Alter Table… command.
 To Disabling Foreign Key Constraint
mysql> SET FOREIGN_KEY_CHECKS = 0;
 To Enable Foreign Key Constraint
mysql> SET FOREIGN_KEY_CHECKS = 1;
Modifying Table Structure
You can alter (modify) the structure of existing table by the
using ALTER TABLE…. Command of MySQL.
You can do the following with the help of ALTER TABLE..
Command.
 Add a new Column or Constraints
 Modifying existing column (data type, size etc.)
 Delete an existing column or Constraints
 Changing Column Name

ALTER TABLE <Table Name>


ADD|MODIFY|DROP|CHANGE <Column Definition(s)>

You can add/Delete/Modify multiple columns with single ALTER


Command.
Modifying Table Structure cont..
 Adding new column
ALTER TABLE <Table Name>
ADD <Column>[<data type> <size>][<Constraints>]
mysql> ALTER TABLE Student ADD (TelNo Integer);
mysql> ALTER TABLE Student ADD (Age Integer DEFAUL 10);
 Modifying Existing Column
ALTER TABLE <Table Name>
MODIFY <Column>[<data type> <size>] [<Constraints>]
mysql> ALTER TABLE Student MODIFY Name VARCHAR(40);
mysql> ALTER TABLE EMP CHANGE ENAME, EMPNAME CHAR(40);
 Removing Column & Constraints
ALTER TABLE <Table Name> Renaming
DROP <Column name> <Constraints> Column by
mysql> ALTER TABLE Student DROP TelNo; using
CHANGE
mysql> ALTER TABLE Emp DROP JOB, DROP Pay;
Summery..
MySQL command are divided in DDL,DML,TCL and DCL category.
You can create table with various Integrity constraints.
Aggregate functions are also called Column level functions.
The commonly used MySQL commands are-

Command Description
CREATE Used to create database and tables with contratins
D ALTER Used to add, delete, modify columns in the existing
D
table i.e. modifies table structure.
L
DROP Used to delete table and database
SELECT Used to access/display stored records in the tables
D INSERT Used to insert new record in the table
M
DELETE Used to delete existing records from the table
L
UPDATE Used to modify values of records.

You might also like