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

Ch-13 Creating Tables and DML Commands

This document provides a comprehensive guide on creating and managing databases and tables in MySQL, including commands for creating databases, tables, and inserting records. It details various integrity constraints such as NOT NULL, PRIMARY KEY, UNIQUE, DEFAULT, CHECK, and FOREIGN KEY, explaining their purposes and how to implement them. Additionally, it covers modifying table structures, updating records, and deleting records, along with examples of SQL commands for each operation.

Uploaded by

Sanjay Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Ch-13 Creating Tables and DML Commands

This document provides a comprehensive guide on creating and managing databases and tables in MySQL, including commands for creating databases, tables, and inserting records. It details various integrity constraints such as NOT NULL, PRIMARY KEY, UNIQUE, DEFAULT, CHECK, and FOREIGN KEY, explaining their purposes and how to implement them. Additionally, it covers modifying table structures, updating records, and deleting records, along with examples of SQL commands for each operation.

Uploaded by

Sanjay Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter-13

Creating Tables and inserting records


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 or to make any database
current 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
Shows the name of
Student; currently open database
 Viewing Table Structure
S
e
l
e
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 i n t e g e r,
ename char(30),
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);
INSERT INTO Employee VALUES ( 2 , ‘Akbar ’, ‘Dehradun’,20000);
INSERT INTO Employee VALUES ( 3 , ‘Anthony’, ‘Mumbai’,10500);
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. We cannot enter null value.
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.
Integrity Constraints are the rules in real life which are
to be imposed on the data. Besides the cell name, cell length
and the cell data type, there are other parameters that is other
da ta constraints that can be passed to the DBA at cell
creation time. These data constraints are connected to a cell
by the DB A as a flag. Whenever a user attempts to load a
cell with data, DBA will check the data being loaded into the
cell against the data constraint defined at the cell creation
time. If the data bei ng loaded fails to satisfy any of the data
constraint checks fi red by the DBA, the DBA will not load
the data into the cell, reject the entered record and will flash
an error message.
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
Constraints are
char(3) NOT defined with
StAdd varchar(40),NULL Column definitions
char(5) UNIQUE, i.e. Column level
PRIMARY
AdmN integer KEY, CHECK
o
Stname (StAge>=5)
char(20) NOT NULL,
UNIQUEStAge  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.
The constraints can either be placed at the column level or at the table level.
Column Level Constraint- These constraints are defined
along with the colu mn definition. These constraints can be
applied to any one column at a time. If the constraints spans
across multiple columns ,then the table level constraints are
used.
Table Level Constraints- If the data constraint attach ed to a
specific cell in a table references the content of another cell
in the table then the table level constraint is used.
Types Of Constraints
Not Null Constraint – When a column name is defined as not null, then that
column becomes a mandatory column. It implies that the user is enforced to enter
data into that c o lumn.
Principles of Null Values :
1 .Setting the null value is appropriate when the actual value is unknown or a value
would not be m eaningful.
2.A null value would not be equivalent to a value of z ero.
3.A null value would evaluate to null in any expression. Ex-Null multiplied by 10 is null.
CREATE TABLE student
(rollNo varchar(24) NOT NULL,
name varchar(20) NOT NULL, address varchar(30) ,
marks number(5,2));
What is the difference between 0 and Null?
Zero 0 is a value where as NULL represents unknown value.
Unique Key Constraint – The purpose of a un ique ke y is to ensure that
information in the column for each record is unique.
Unique Key as a column constraint :
C R EATE TABLE student (rollNo varchar2(4) UN IQUE ,
name varchar2(20) ,address varchar2(30) , marks
number(5,2));
Uniq ue Key as a table constraint:
CREATE TABLE student
(rollNo varchar2(4) ,name varchar2(20) , address
varchar2(30) ,marks number(5,2) CONSTRAINT roll_key
UNIQUE(rollNo));
Default Constraint – They are used to specify default value for a column.
While inserting record in the default column default keyword is used.
At the time of cell creation a ‘default value’ can be assigned to it.When the user is loading a
' record' with values and leaves this cell empty,th e D BA will automatically load this cell with
the default v alue spec ified. The data type of the default value should m atch the data type
of the column.
CREATE TABLE student
(r ollNo varchar2(4) ,name varchar2(20) ,
address varchar2(30) ,
marks number(5,2) DEFAULT 0);
Check Constraint – It is used when we need to enforce
integrity rules that can be evaluated based on a l ogical
expression. CREATE TABLE student
(rollNo varchar2(4) CHECK (rollNo like ‘C%’),
name varchar2(20) CONSTRAINT chk_nm
CHECK(name = upper(name)),
address varchar2(30) ,
marks number(5,2) CHECK(marks > 40));
Primary Key Constraint – It is used to uniquely iden tify each
row in the table. Primary key values must not be null and mu st be unique across the
column.
Primary Key as a column constraint –
CREATE TABLE student
(rollNo varchar2 (4) PRIMARY KEY,
name varchar2(20) ,
address varchar2(30) ,
marks number(5,2));
Primary Key as a table constraint –
CREATE TABLE student
(rollNo varchar2(4) ,name varchar2(20) ,
address v archar2(30) ,marks number(5,2) PRIMARY
KEY(rollNo));
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 i n t ( 2 ) ) ;
Defining Primary Key at Table Level:

mysql> CREATE TABLE Student


PRIMARY KEY
( StCode char(3) NOT
Constraint is
char(20) NULL, defined after all
Stname i n t ( 2 ) , NOT NULL, column
StAge
PRIMARY KEY (StCode) ) ; definitions (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.
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 table as
( Select * From Emp);
Emp
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

We can insert a record as follows-


mysql> INSERT INTO Student VALUES ( ‘ s 1’ , ’ Ami t a b h ’ , ‘Harivansh’,’1955- 10- 2 5 ’ , ‘Mumbai’,
12);
mysql> INSERT INTO Student VALUES (‘s2’,’Sharukh Khan’, NULL,’1972-5-25’,‘ D e l h i ’ , 10);

mysql> INSERT INTO Student ( StID, FName, Name, You can also define order of
Class) VALUES ( ‘ s3’ , ’ Ami tab h ’ , columns.
’Abhishek’, 10);
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 (SELECET * FROM


Oldstudent);
Both tables must have same column structure

mysql>INSERT INTO Newstudent VALUES


(SELECT * FROM Oldstudent WHERE City=‘Mumbai’);
mysql> INSERT INTO Newstudent ( S t I D , Name, Class)
VALUES (Select StID, Name,Class FROM Oldstudent WHERE Class>=11);

You can also select columns from both tables.


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.


Modifying Table Structure
 Adding new column
ALTER TABLE <Table Name>
ADD <Column>[<data type> <size>][<Constraints>]
mysql> ALTER TABLE Student ADD (TelNo I n t eg er);
mysql> ALTER TABLE Student ADD (Age Integer DEFAUL 10);
 Modifying Existing Column
ALTER TABLE <Table Name>
MODIFY <Column>[<data type> <size>] [<Constraints>] mysql> ALTERTABLE 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;
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 Sal = Sal+(Sal*10/100);
SET
mysql> UPDATE Emp Sal = Sal+(Sal*10/100)
WHERE SET Sal <=10000;
mysql> UPDATE Emp SET City = ‘Dehradun’ WHERE CITY IS NULL;
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>]
mysql> DELETE FROM Student ; Caution!!! This command will delete all the records…

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


mysql> DELETE FROM Student WHERE Class >=11 ;
mysql> DELETE FROM Student WHERE Class <9 AND Ci t y= ‘ Del h i ’ ;

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


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

What is a constraint?
 Column Level

Constraints
Not Null
 Table Constraint
Level Constraints
Unique Key Constraint
Default Constraint
Check Constraint
 Primary Key Constraint
 Foreign Key Constraint
 Defining Constraint in Alter Table Command
What is a Constraint?
Integrity Constraints are the rules which are applied on the table or
column to maintain integrity.
Besides the cell name, cell length and the cell data type, there are other
parameters that is other da ta c onstraints that can be passed to the DBA at
TABLE creation time.
by the DBA, the DBA will not load the data into the cell, reject the entered
record and will flash an error message.
The constraints can either be placed at the column level or at the table level.

Column Level Constraint- These constraints are defined along with the colu mn
definition. These constraints can be applied to any one column at a time. If
the constraints spans across multiple columns ,then the table level
constraints are used.

Table Level Constraints- If the data constraint attach ed to a specific cell in a


table references the content of another cell in the table then the table level
constraint is used.
Unique Key Constraint – The purpose of a un ique ke y is to ensure that
information in the column for each record
is unique.
Unique Key as a column constraint :
CR EATE TABLE student
(rollNo varchar2(4) UN IQUE ,
name varchar2(20) ,address varchar2(30) , marks
number(5,2));
Uniq ue Key as a table constraint:
CREATE TABLE student
(rollNo varchar2(4) ,name varchar2(20) , address
varchar2(30) ,marks number(5,2) CONSTRAINT roll_key
UNIQUE(rollNo));

You might also like