0% found this document useful (0 votes)
26 views90 pages

Class 12 Mysql

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)
26 views90 pages

Class 12 Mysql

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/ 90

SUB: COMPUTER SCIENCE

TOPIC: MySQL
Teacher: PRASAD N My SQL
PGT COMPTUER SCIENCE
dATABASE cONCEPTS
A Database is a collection of DATA/INFORMATION that is
organized so that it can be easily accessed, managed and
updated. In Database ,Data is organized into rows, columns
and tables, and it is indexed to make it easier to find
relevant information.

It works like a container which contains the various object


like Tables, Queries, Reports etc. in organized way.
WHY DO WE NEED DATABASE
● To manage large chunks of data: if size of data increases into
thousands of records, it will simply create a problem to
manage.Database can manage large amount of data.
● Accuracy: Through validation rule in database ,data accuracy
can be maintained.
● Ease of updating data: With the database, we can flexibly update
the data according to our convenience. Moreover, multiple
people can also edit data at same time.
● Security of data: With databases we have security groups and
privileges to restrict access.
● Data integrity: In databases, we can be assured of accuracy and
consistency of data due to the built in integrity checks and
access controls.
Database Management System(DBMS)
❖ A DBMS refers to a software that is responsible
for storing, maintaining and utilizing database in
an efficient way.
❖ A Database along with DBMS software is called
Database System.
❖ Example of DBMS software are Oracle, MS SQL
Server, MS Access, Paradox, DB2 and MySQL
etc.
❖ MySQL is open source and freeware DBMS.
Advantages of Database System
❖ 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 31/31/2000.
Data Model- Way of data representation
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.
RELATIONAL DATABASE
A relational database is a collective set of multiple data sets
organized by tables, records and columns. Relational database
establish a well-defined relationship between database tables.
Tables communicate and share information, which facilitates data
searcheability, organization and reporting.
A Relational database use Structured Query Language (SQL),
which is a standard user application that provides an easy
programming interface for database interaction.
Database Concepts:
Database is logically organized collection of data which is shared by multiple users simultaneously
Columns present in table are known as attribute

Number of attributes in a relation is Degree

Rows present in table are known as tuples

No.of rows (tuples)present in table is called cardinality

Primary key is a key which can identify a record uniquely

When we have more than one key which can identify record uniquely then all the unique keys

are known as candidate key

Alternate key is the candidate key which is not selected as primary key
KEYS IN DATABASE
Key plays an important role in relational database; it is used for identifying unique
rows from table & establishes relationship among tables on need.
Types of keys in DBMS
Primary Key – A primary is a column or set of columns in a table that uniquely
identifies tuples (rows) in that table.
Candidate Key –It is an attribute or a set of attributes or keys participating for Primary
Key, to uniquely identify each record in that table.
Alternate Key – Out of all candidate keys, only one gets selected as primary key,
remaining keys are known as alternate or secondary keys.
Foreign Key – Foreign keys are the columns of a table that points to the primary key of
another table. They act as a cross-reference between tables.
KEYS IN DATABASE
SQL
SQL is an acronym of Structured Query Language.It is a standard
language developed and used for accessing and modifying relational
databases.
The SQL language was originally developed at the IBM research
laboratory in San José, in connection with a project developing a
prototype for a relational database management system called System R
in the early 70s.
SQL is being used by many database management systems. Some of
them are:
MySQL
PostgreSQL
Oracle
SQLite
Microsoft SQL Server
MYSQL
MySQL is currently the most popular open
source database software. It is a multi-user,
multithreaded database management system.
MySQL is especially popular on the web. It is
one of the parts of the very popular LAMP
platform. Linux, Apache, MySQL and PHP or
WIMP platform Windows,Apache,MySQL and
PHP.
MYSQL
MySQL Features:
➔ Open Source & Free of Cost:
It is Open Source and available at free of cost.
➔ Portability:
Small enough in size to instal and run it on any types of Hardware and
OS like Linux,MS Windows or Mac etc.
➔ Security :
Its Databases are secured & protected with password.
➔ Connectivity
Various APIs are developed to connect it with many programming
languages.
➔ Query Language
It supports SQL (Structured Query Language) for handling
database.
Types of SQL Commands
❑ DDL (Data Definition Language)
To create database and table structure-commands like CREATE , ALTER ,
DROP, TRUNCATE etc.
❑ DML (Data Manipulation Language) Record/rows related
operations.commands like SELECT...., INSERT..., DELETE..., UPDATE.... etc.
❑ Transactional control Language
Used to control the transactions.commands like COMMIT, ROLLBACK,
SAVEPOINT etc.
❑ DCL (Data Control Language)
used to manipulate permissions or access rights to the tables.commands like
GRANT , REVOKE etc.
MySql datatypes
numeric
decimal -decimal(<precision>, [<scale>]) [zerofill] For storing
floating-point numbers where precision is critical.
Int - int(<size>) [auto_increment] [unsigned] [zerofill]
A whole number, 4 bytes, with a maximum range of -2,147,483,648 to
2,147,483,647 (unsigned: 0 to 4,294,967, 295)
string
char-char(<size>) [binary]
Fixed length – for storing strings that won't vary much in size.
Range of 0 to 255, stores that amount in bytes
Varchar-varchar(<size>) [binary]
Variable length – for storing strings that will vary in size.
Range of 0 to 255, stores that amount in bytes, plus 1 byte
date
Date-Format: YYYY-MM-DD ,Example: 2006-09-23,Range of years
1000 to 9999
Database Commands in MySql
Getting listings of database and tables
mysql> SHOW DATABASES;

mysql> SHOW TABLES;

Creating a database-

mysql> CREATE database myschool;

Deleting a database mysql> DROP database abc;

to remove table mysql> drop table abc;


After we have created the database we use the USE statement to change the current
mysql> USE myschool;

Creating a table in the database is achieved with CREATE table statement.


mysql> CREATE TABLE student (lastname varchar(15),firstname varchar(15), city
varchar(20), class char(2));

The command DESCRIBE is used to view the structure of a table.


mysql> DESCRIBE student; // desc student;
Database Commands in MySql
To insert new rows into an existing table use the INSERT

command:

mysql>INSERT INTO student values(‘dwivedi’,’freya’,’Udaipur’,’4’);

Note: Similarly we can insert multiple records into the table


With the SELECT command we can retrieve previously inserted rows: mysql>

SELECT * FROM student;

Selecting rows by using the WHERE clause in the SELECT command

mysql> SELECT * FROM student WHERE class=“4";

Selecting specific columns(Projection) by listing their names

mysql> SELECT first_name, class FROM student;

To modify or update entries in the table use the UPDATE command

mysql> UPDATE student SET class=“V" WHERE class=3;


Database Commands in MySql
Deleting selected rows from a table using the DELETE command

mysql> DELETE FROM student WHERE firstname=“amar";

A general form of SELECT is:

SELECT what to select(field name) FROM table(s) WHERE condition that the data

must satisfy;

● Comparison operators are: < ; <= ; = ; != or <> ; >= ; >

● Logical operators are: AND ; OR ; NOT


Comparison operator for special value is NULL

mysql> SELECT * FROM Student WHERE City IS NULL ;

BETWEEN- to access data in specified range

mysql> SELECT * FROM Student WHERE class between 4 and 6;

IN- operator allows us to easily test if the expression in the list of values.

mysql> SELECT * FROM Student WHERE class in (4,5,6);


Alter command:
❑ Add column to an existing table

❑ Delete a column from an existing table

❑ Modify def existing column

❑ Change the name of the existing column


Add column
● alter table <table_name> add <column_name> datatype <size>

Ex: alter table student add city varchar(20)


alter table student add (city varchar(20), gender varchar(5))
Add primary key
Alter table <table_name> ADD primary key(fieldname)
To change column name
Alter table <table_name> CHANGE <fieldname> <newfileldname
datatype(size))
Remove table components
Alter table <tablename> DROP primary key;

Modify column
● alter table <table_name> modify (<column_name> newdatatype

<new size>)
Ex: alter table student add city varchar(20)
alter table student add (city varchar(20), gender varchar(5))
Drop column:
Syntax: alter table <table_name> drop <column>

Ex:
alter table student drop <column> city;

alter table student modity city varchar(50)

alter table student change city cities varchar:


Update:

Update student set gender=‘f’

Update student set marks =50 where sno=1;

Update student set grade=‘a’ where grade is NULL

Update student set grade=‘a’ where marks>80;


Delete command:

Delete from student where rno=1;

Drop table student; # it deletes entire table


Pattern Matching – LIKE Operator
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
mysql> SELECT * FROM Student WHERE Name
LIKE ‘A%’;

mysql> SELECT * FROM Student WHERE Name LIKE


’%Singh%’;

mysql> SELECT Name, City FROM Student WHERE


Class>=8 AND Name LIKE ‘%Kumar%’ ;
Order by clause: Used to sort the query
result by one or more than one column
Select * from student order by name;
Select * from student where marks>55 order by
name;
Select * from student order by sid asc;
Select * from student order by sid desc;
Select * from student order by stream asc, name
asc;
Distinct

Distinct keyword ensures that multiple entries of


the same are ignored.

mysql> select distinct(sid) from std;


How to perform simple calculations

mysql> select 1+6;


mysql> select 4* 3 from dual;
mysql> select curdate()
mysql> select char(70,65,67,69)
Using column alias

mysql> select empid as "Employee Id" from emp;


Some more functions in SQL
curdate()
date()
month()
year()
now()
sysdate()

>>> select date('2020-12-31 01:02:03')


>>> select year('2020-12-31');
>>> select sysdate();
Aggregate functions:
Sum: ● Select sum(marks) from student;
● Select sum(marks) “total marks of student”
from student;

avg: Select avg(marks) from student;


max: Select max(marks) from student;

min: Select min(marks) from student;

count: Select count(marks) from student;


Examples
mysql> select sum(sal) from emp;

mysql> select count(esal) from emp;

mysql> select count(distinct empid) from emp;


Group by clause
Group by clause combines all those records that
have identical values in a particular field.

Note: It will work with aggregate functions


Select stream,count(*) from stm group by stream;
Having clause:
The having clause places conditions on groups in
contrast to where clause that places conditions on
individual rows.

Select stream,count(*) from student group by


stream having count(*)>2;
Constraints
Constraints are rules on table:

★ Primary key
★ Unique
★ Not null
★ Default
★ between
Primary key:
➔ It is used to uniquely identifies each record in
a table
➔ Primary key values must not be NULL

UNIQUE:
➔ Information in the column for each row it
must be unique
➔ Unique key constraint can have NULL values
NOT NULL:
BY DEFAULT, A COLUMN CAN HOLD NULL VALUES.
THE NOT NULL CONSTRAINT ENFORCES A COLUMN
TO NOT ACCEPT NULL VALUES.

DEFAULT constraint:
It is used to assign the default value to a column
CHECK constraint:
It ensures that all the values in a column
satisfies that certain condition
Unique Constraint

mysql>

create table employee(ecode integer not null


unique, ename char(20) not null);
Primary key

mysql>

create table employee1(ecode integer primary


key, ename varchar(30));
Default constraint
mysql>

create table emp4(ecode integer, ename


varchar(20), egrade varchar(3) default '12');

Insert into emp4 values(10,”Sagar”,default);


Check constraint
mysql>

create table emp5(eid int(4), ename varchar(20),


esal integer(4) check(esal between 5000 and
10000));

create table emp5(eid int(4), ename varchar(20),


esal integer(4) check(esal>10000));
Check constraint
mysql>

create table emp5(eid int(4), ename varchar(20),


ecity varchar(20) check(ecity
in(‘Hyderabad,’Secunderabad’,’Tarnaka’)));
Example:

Create table student (


sno int primary key,
admno int unique,
name varchar(30) not null,
gender varchar(3) default ‘M’
marks int check ( marks between 0 and 50)
);
How to add and remove primary key:
Alter table <table_name> add primary key
<column name>

Ex: alter table student add primary key (sno);

Alter table <table_name> drop primary key

Ex: alter table student drop primary key


Foreign key constraint
Persons Table Orders Table
Perso LastName FirstName Age OrderId OrderNumber PersonId
nId
1 5432 3
1 Tendulkar Sachin 55
2 2312 1
2 Rahul Dravid 60
3 352 2
3 Virat Kohli 52

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Foreign key
Create table emp
as given below

create table emp1(trid int(5), location varchar(20),


empno int(3) references emp(empno));
(or)
create table emp2(trid int(5), location varchar(20),
empno int(3), foreign key(empno) references
emp(empno));
Joins in SQL:
equi join and natural join
A join is a query that combines rows from two or
more tables.

Cartesian product:
select * from emp, dept;
Types of Joins:
Natural Join:
join=cross product + condition

Query: find employee name who is working it IT deparment.

select ename from employee where


employee.eno=department.eno;
(or)
Select ename from employee natural join department.
Employee Table:

ENO ENAME EADDRESS


1 AKSHARA NACHARAM
2 SAMANVI TARNAKA
3 VINAY HMT NAGAR
4 RISHI HABSIGUDA

DEPARTMENT TABLE:

D_ID DNAME ENO


D101 IT 1
D102 ACCOUNTS 2
D103 CIVIL 3
D104 TRANSPORT 4
EQUI JOIN:

Student: SNO SNAME ADDRESS


1 MIHESH HYD
2 MUKESH SECBAD
3 MAHESH RR

WING: WID PLACE SNO


10 RR 1
20 HYD 2
30 SECBAD 3

FIND THE STUDENT NAME WHO WORKED IN A WING HAVING ADDRESS SAME AS
THEIR ADDRESS
select sname from student,wing where student.sno=wing.sno and
student.address=wing.place
1. Name the class in SQL for fetching unique values only
2. What is the use of BETWEEN operator
3. Categorize the DDL and DML commands from the following.
SELECT, UPDATE, DROP, DELETE, CREATE, ALTER, INSERT
4. Use of WHERE clause in SQL
5. FUll form of SQL
6. Give example of any two aggregate functions in MySQL.
7. What is the difference between primary key and unique constraint.
8. Which command is used to display list of all databases.
9. Which command is used to display a list of already existing tables?
10. Which command is used to change the data of the table?
11. Which clause is used with aggregate functions?(Group by/ Where)
12. What do you mean by candidate key?
13. Correct the error in the following query.
Select * from book where bname = %math%;
14. Select count(*) from book; return 10 and select count(bname) from book; return 9. What is the reason
for this?
15. Write a query to display details of all employees whose name(e_name) start with alphabet ‘a’ from table
emp.
16. Duplication of record is called ____________
1. To display CNO, CNAME, TRAVEL DATE from the table TRAVEL in descending
order of CNO.
>>> select CNO, CNAME, TRAVEL DATE from travel order by CNO desc

2. To display the CNAME of all customers from the table TRAVEL who are travelling
by vehicle with code Vo1 or Vo2
>>> select CNAME from travel where VCODE=’V01’ or VCODE=’V02’
3. To display the CNO and CNAME of those customers from the table TRAVEL who
travelled between ‘2015-1231’ and ‘2015-05-01’.
>>> select CNO, CNAME from TRAVEL where TRAVELDATE between ‘2015-1231’ and
‘2015-05-01’

4. To display all the details from table TRAVEL for the customers, who have travel
distance more than 120 KM in ascending order of NOP
>>> select * from TRAVEL where KM>120 order by NOP
5. SELECT COUNT (*), VCODE FROM TRAVEL GROUP BY VCODE HAVING
COUNT (*) > 1;

6. SELECT DISTINCT VCODE FROM TRAVEL :

7. SELECT A.VCODE, CNAME, VEHICLETYPE FROM TRAVEL A, VEHICLE B WHERE A.


VCODE = B. VCODE and KM < 90;

8. SELECT CNAME, KM*PERKM FROM TRAVEL A, VEHICLE B WHERE A.VCODE =


B.VCODE AND A. VCODE ‘V05’;
1. Select count(*) city from company group by CITY
2. Select min(price) , max (price) from customer where QTY > 10
3. Select product name,city, price, from company, customer where company.cid=customer.cid and
productname=’mobile’;
1. To display the RCODE and PLACE of all ‘5 Star’ resorts in the alphabetical order of the place from
the table RESORT
2. To display the minimum and maximum rent for each type of resort from the table RESORT
3. To display the details of all resorts which are started after 31-DEC-05 from the table RESORT
4. Display the owner of all 5star resorts from table resort and ownedby.
5. To display the maximum rent
1. Select RCODE, place from resort where type=’5 star’ order by place
2. Select type, max(rent), min(rent) from resort group by type
3. Select * from resort where start date > ‘31-dec-05’
4. Select owner from resort,ownedby where resort.place=ownedby.place and
type=’5star’
5. Select max(rent) from resort
RECAP
REVISED SYLLABUS

SQL COMMANDS (INSERT, SELECT,DESC)

DISTINCT KEYWORD

SIMPLE CALCULATIONS

IN ,NOT IN COMMAND

LIKE (%, _ )

CONSTRAINTS
SQL NOT NULL CONSTRAINT

BY DEFAULT, A COLUMN CAN HOLD NULL VALUES.


THE NOT NULL CONSTRAINT ENFORCES A COLUMN TO NOT ACCEPT NULL VALUES.
CREATE TABLE PERSONS (
ID INT NOT NULL,
LASTNAME VARCHAR(255) NOT NULL,
FIRSTNAME VARCHAR(255) NOT NULL,
);
DEFAULT

◼ SQL DEFAULT Constraint


◼ The DEFAULT constraint is used to provide a default value for a column.

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
City varchar(255) DEFAULT ‘HYD'
);
SQL UNIQUE CONSTRAINT

◼ The UNIQUE constraint ensures that all values in a column are different.
◼ A PRIMARY KEY constraint automatically has a UNIQUE constraint.

CREATE TABLE Persons (


ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
);
SQL PRIMARY KEY CONSTRAINT

◼ The PRIMARY KEY constraint uniquely identifies each record in a table.


◼ Primary keys must contain UNIQUE values, and cannot contain NULL values.
◼ A table can have only ONE primary key
Create table customer (
cid integer not null primary key,
last_name varchar(30),
first_name varchar(20),
);
DEFINING PRIMARY KEY THORUGH ALTER TABLE
COMMAND
◼ We can define a primary key in ALTER table command through keywords
◼ Add primary key<key_field>
Eg:
alter table customer add primary key (cid);
FOREIGN KEY CONSTRAINT

◼ In an RDBMS, whenever two tables are related by a common column, then the related column in the
parent table should be either declared a primary key and the related column in the child table should
have foreign key constrint.
◼ CUSTOMER ORDERS
Column characteristic Column name characteristi
name c
CID Primary key OrderId Primary key

Cname Order date

Marks CUSTOMER_CID

Create table orders ( orderId integer, orderdate date, customer_cid integer, primary key(OrderId), foreign
key(customer_cid) references customer(cid)
INSERT AND ALTER TABLE COMMANDS

◼ Eg: create table customer(cid integer, cname varchar(20), cproduct varchar(30));


◼ insert into customer values(10, ‘Rajith’, ‘Dell’);

Note: for multiple values🡪 insert into customer values(10,’rajith’,’dell’),(20,’srineth’,’hp’);


MODIFYING DATA IN A TABLE

◼ You can modify data in tables using UPDATE command of SQL.


Eg: update customer set cproduct=‘Lenovo’ where cid=10;

Deleting data from tables:


Syntax: delete from <table_name> where <condition>;
Eg; delete from customer; // to remove all contents of items table
delete from customer where cid=10; // it will delete particular record
ALTERING TABLES

◼ The alter table command is used to change definitions of existing tables.


◼ In mySql , alter table command is used:
to add a column
to add an integrity constraing
to redefined a column

Eg: alter table customer add cadd varchar(30);


MODIFY, DROP
To modify existing columns of table, ALTER TABLE command can be used according to following syntax:
alter table <table_name> modify (columnname new datatype (size)
Eg: alter table customer modify lastname(50);

Some times you need to change the name of one column:


Eg: alter table customer change cproduct customerproduct varchar(30);
Drop: It will drop table from the database
Eg: drop table customer;
SQL JOINS
◼ An SQL join is a query that fetches data from two or more tables whose records are joined with one
another based on a condition.
YO U
TH ANK

You might also like