0% found this document useful (0 votes)
15 views53 pages

0507241547318213

The document provides a comprehensive guide on creating and managing databases and tables using SQL commands, including creating, altering, and deleting databases and tables. It explains data integrity, constraints, and the use of foreign keys to maintain relationships between tables. Additionally, it covers SQL operations such as INSERT, UPDATE, DELETE, and creating views for data retrieval.

Uploaded by

Arjun Ramesh
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)
15 views53 pages

0507241547318213

The document provides a comprehensive guide on creating and managing databases and tables using SQL commands, including creating, altering, and deleting databases and tables. It explains data integrity, constraints, and the use of foreign keys to maintain relationships between tables. Additionally, it covers SQL operations such as INSERT, UPDATE, DELETE, and creating views for data retrieval.

Uploaded by

Arjun Ramesh
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/ 53

CREATING and USING DATABASE

CREATE DATABASE <DATABASE NAME>


CREATE DATABASE School;

TO SEE LIST OF DATABASES:


SHOW DATABASES;

TO OPEN ANY DATABASE TO WORK


USE DATABASENAME
USE School ;

DROP DATABASE <DATABASE NAME>


DROP DATABASE School;
CREATING TABLE
Syntax:-
Create Table TableName(ColumnName datatype(size),
ColumnName datatype(size),…..);

Example:-

Create Table Employee(empno int, name varchar(20), dept


varchar(20), salary int);

Create table Student(roll int, name varchar(20), stream


varchar(20), per int);
Drop table==Deleting table

Drop table <table name>;

Drop table School;


---------------------------------------------
Deletes the data inside the table

Truncate table <table name>;

Truncate table School;


SQl Alter table

Add
Modify
Delete(Drop)
Rename
the columns in an existing tables
ALTER TABLE - ADD
Column
ALTER TABLE table_name
ADD column_name datatype;

Example:

ALTER TABLE Customers


ADD Email varchar(255);
ALTER - DROP Column

ALTER TABLE table_name


DROP COLUMN column_name;

Example:

ALTER TABLE Customers


ADD Email varchar(255);
ALTER - RENAME COLUMN
ALTER TABLE table_name
RENAME COLUMN old_name to
new_name;

Example:

ALTER TABLE EMP


RENAME COLUMN EMAID to EMAILID
ALTER TABLE - ALTER/MODIFY DATATYPE

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

Example:

ALTER TABLE Persons


ALTER COLUMN DateOfBirth
year;
What is data integrity?
Data integrity is the assurance that digital
information is uncorrupted and can only be
accessed or modified by those authorized
to do so.
Data integrity describes data that's kept
complete, accurate, consistent and safe
throughout its entire lifecycle in the
following ways:
•Complete. Data is maintained in its full form and no data
elements are filtered, truncated or lost.
•Accurate. Data isn't altered or aggregated in any way that
affects data analytics.
•Consistent. Data remains unchanged regardless of how, or
how often, it's accessed and no matter how long it's stored.
•Safe. Data is maintained in a secure manner and can only be
accessed and used by authorized applications or individuals.
◾A constraints refers to condition
or limitation we apply on any
column so that only correct
information will be entered in
table.
◾MySQL allows to apply
constraint by two methods
 At the time of table creation
 After table creation
◾ PRIMARY KEY : ensures unique value in any
column also forces data entry mandatory.
Only one primary key can be applied in one
table

◾ UNIQUE : also allows unique value in any


column but it allows NULL values and can be
applied to n times

◾ NOT NULL : it will make data entry


mandatory for applied column i.e. NULL
will not be allowed
◾ CHECK : allows to specify range of values that can
be entered in applied column like salary must be
greater than 2000, marks must be greater than 0
or dept must be in given list of values etc.
◾ Note: in mysql the database engine will
ignore the Check constraints.
◾ FOREIGN KEY: allows to establish relationship
between 2 tables. Foreign key column will be
dependent on PRIMARY KEY column of another
table and allows to enter only those values in
foreign key whose corresponding value exists in
PRIMARY KEY

◾ DEFAULT : it allows to specify any value


which will be automatically inserted in
applied column if we not specify applied
column at the time of data entry using
INSERT
CREATING TABLE
Syntax:-
Create Table TableName
(
ColuName datatype(size) <colu constraint>,
ColuName datatype(size) ,
);
Example:-

Create Table Employee(


empno int primary key,
name varchar(20) not null,
dept varchar(20),
salary int );

Create table Student(roll int, name varchar(20), stream


varchar(20), per int);
◾ Column level constraint is
With column
given with column definition
definition
Ex:
create table visitor(vid int primary key,
vname varchar(20));

◾ Table level constraints are given after all column


definition.
Ex:
create table visitor(vid int,
vname varchar(20),
primary key(vid));

After column
definition
EmpCode Ename Gender Grade GrossSal
1101 Brain M A 9000
1102 Calvin M B 8000
1103 Tom M A 9000
1104 Jerry F E 3000
CREATE TABLE EmpNoCons
(
Empcode int ,
Ename varchar(12),
Gender char(1) ,
Grade char(1) ,
GrossSal int
);
EmpCode Ename Gender Grade GrossSal
1101 Brain M A 9000
1102 Calvin M B 8000
1103 Tom M A 9000
1104 Jerry F E 3000

Apply constraints to the table:


1. EmpCode primary key
2. Ename and Gender - NOT EMPTY
3. GRADE – DEFAULT – E
4. GROSS SAL - Check > 3000
Apply constraints to the table:
1. EmpCode primary key
2. Ename and Gender - NOT EMPTY
3. GRADE – DEFAULT – E
4. GROSS SAL - DEFAULT - 3000

Example:-
CREATE TABLE EMP (
Empcode int Primary key,
Ename varchar(12) not null,
Gender char(1) not null,
Grade char(1) Default ‘E’,
GrossSal int check GrossSal>3000
);
Comparison before and after constraints:
SQL DELETE Statement
The DELETE statement is used to
delete existing records in a table.
DELETE FROM table_name WHERE
condition;
DELETE FROM studetails WHERE adno=101;
DELETE FROM studetails WHERE name =‘anu’;

Delete All Records


DELETE FROM table_name;

delete all rows in a table without


deleting the table.
SQL UPDATE Statement
to modify the existing records in a
table.
UPDATE table_name
SET column1 = value1, column2 = value2,
...
WHERE condition;

UPDATE studetails SET Name = 'Alma',


City= ‘coimbatore‘ WHERE Adno=101;
UPDATE Multiple Records
the WHERE clause that determines
how many records will be updated.

UPDATE Customers
SET ContactName='Julie'
WHERE Country=‘India';
SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new
records in a table
1. Specify both the column names and the
values to be inserted:

2. If you are adding values for all the columns of the


table, you do not need to specify the column names in
the SQL query. However, make sure the order of the
values is in the same order as the columns in the
table.

3, Insert Data Only in Specified Columns

4. To insert multiple rows in one statement.


MySQL INSERT INTO SELECT Statement
1.Copy all columns from one table to
another table:

INSERT INTO table2


SELECT * FROM table1
WHERE condition;

2.Copy only some columns from one table


into another table:

INSERT INTO table2 (column1, column2,)


SELECT column1, column2, FROM table1
WHERE condition;
FULL COPY:
create table dup as select * from studetails;
Selected Column copy
create table dup1 as select Adno,name from studetails;
Selected Record Copy
create table dup2 as select Adno,name
from studetails where adno=101;
SQL FOREIGN KEY
Constraint
The FOREIGN KEY constraint is used
to prevent actions that would
destroy links between tables.
A FOREIGN KEY is a field (or
collection of fields) in one table,
that refers to the PRIMARY KEY in
another table.
The table with the foreign key is
called the child table, and the table
with the primary key is called the
referenced or parent table.
Ad.No Name Contact Age
101 Karthi 9097875643 12
102 Shiju 9097875642 13
103 Ohja 9097875641 12

BookID BookNumber Ad.No


1 77895 101
2 44678 102
3 22456 103
4 24562 101
SQL FOREIGN KEY on CREATE TABLE
create table StuDetails(
AdNo int primary key,
Name varchar(15),
Age int not null);
create table StuDetails(
AdNo int,
Name varchar(15),
age int not null,
primary key(AdNo) );

Parent Table
SQL FOREIGN KEY on CREATE TABLE
CREATE TABLE Lib
(
BookID int NOT NULL,
BookNumber int NOT NULL,
AdNo int,
PRIMARY KEY (BookID),
FOREIGN KEY (AdNo)
REFERENCES StuDetails(AdNo)
);
create table Lib(BID int,bno int not null, Adno
int,primary key(BID), foreign key(Adno) ref
erences s111(Adno));

Child Table
insert into StuDetails values
(101,'Kaira',13),
(102,'Galina',14);
insert into lib values
(111,1234,101),
(112,1235,102),
Will throw an error
(113,1236,103); as 103 not in parent
◾ MySQL allows us to give names to
constraints to that when error occurs due to
constraint violation then this name will
appears to help us in identifying for which
column this error occurs.
Ex:
create table training (empno int, traName varchar(20),
startdate date, enddate date,
constraint myfkey
foreign key(empno) references ABCLtd(empno));
UNIQUE Constraint on CREATE TABLE
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID) UNIQUE constraint
);

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
DROP UNIQUE Constraint
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

ALTER TABLE Persons


DROP INDEX UC_Person;
create table abc( create table abcd(
eno int,
eno int primary key,
name varchar(12) not null,
name varchar(12) not null,
dept varchar(12) default 'sales' ,
dept varchar(12) default'sales', salary int,
salary int); constraint abcconst
primary key(eno),
unique (name)
);

desc abc
check PRIMARY KEY is by inserting duplicate eno

Inserting NULL value in name column


Inserting values for table leaving dept to check default
functionality.
create table train( eno int, traName varchar(20),

constraint fkeyTrain foreign key(eno)


references abc(eno)); Inserted
successfully
because
insert into train values(1,'basketball'); matching eno
is in ABC

Insert unsuccessful
as matching eno is
not found in ABC
◾ Note: after foreign key is applied, we cannot
delete any record or update primary key value
in master table because its related records
will be in foreign key table

◾ 2 main options available while applying


foreign key:
1. ON DELETE CASCADE : it means if any
record from master table is deleted its
related records in foreign key table will also
be deleted
2. ON UPDATE CASCADE: it means if primary
key value in master table is changed then it
will be automatically reflected in foreign key
table
◾ MySQL allows us to get the structure of table like
list of columns, data type, size and key information
of table using DESC / DESCRIBE command
◾ Example
◾ALTERTABLE command allows us to
perform the following operations:

 Adding new column in existing table


 Dropping existing column from table
 Modifying column definition in table
 Changing the name of column
 Adding or dropping constraint
after table creation.
After new column is added, if
you select record it will display
NULL in that column for
previous record, we have to
update it using UPDATE
command
ALTERTABLE ABCLtd drop
designation;
I N P L A C E O F “ F I R S T ” W E C A N A L S O U S E “A F T E R C O L U M N N A M E ”

TO SET DEPTNO AFTER ENAME


A LT E R T A B L E E M P M O D I F Y D E P T N O I N T A F T E R E N A M E
In this way
we can add
any
constraint
While dropping Primary Key, if
it is connected with child table,
use the following commands

ALTER TABLE EMP DROP


PRIMARY KEY CASCADE
MySQL VIEW Statement

A view is a virtual table based on the


result-set of an SQL statement.
A view contains rows and columns, just like a
real table. The fields in a view are fields from
one or more real tables in the database.

A view doesn’t store data on the disk


like a table. View defines a customized
query that retrieves data from one or
more tables, and represents the data as
if it was coming from a single source.
A view is created with the CREATE VIEW statement.

CREATE VIEW Syntax

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

A view always shows up-to-


date data! The database
engine recreates the view,
every time a user queries it.
CREATE VIEW stuview as
SELECT Bname,Authorname from
booksdetail;

Creating View from a single table


CREATE VIEW sview as SELECT
Bname,Authorname,emp.salary
from booksdetail,emp;
Creating View from multiple tables

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy