0% found this document useful (0 votes)
166 views41 pages

Chapter 5 - MySQL Revision Tour

The document discusses the MySQL relational database management system. It covers topics like the relational data model, SQL, common MySQL data types, accessing and creating tables in MySQL, and inserting data into tables.

Uploaded by

Anjana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
166 views41 pages

Chapter 5 - MySQL Revision Tour

The document discusses the MySQL relational database management system. It covers topics like the relational data model, SQL, common MySQL data types, accessing and creating tables in MySQL, and inserting data into tables.

Uploaded by

Anjana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

MySQL SQL Revision Tour

Chapter - 5
5.1 Introduction

The collection of data, usually referred to as the database, contains
information about one particular enterprise.

A database system is basically a computer based record keeping
system.

A typical file-processing system has a number of major limitations and
disadvantages, such as data redundancy(duplication of data), data
inconsistency, unsharable, unstandarized ,insecure,incorrect etc.

A database management system is solution to all these problems as it
provides a centealized control of the data.

Various advantages od database systems are:
1. Database system reduce data redundancu to a jarge extent.
2. Database systems control data inconsistency to a large extent.
3. Database facilitate sharing of data.
4. Database enforce standards.
5. Centralized database can ensure data security.
6. Integrity can be maintained through databases.
5.2 Relational Data Model

In relational data model, the data is organized into tables(i.e. Rows and columns).
These tables are called relations.

A row in a table represent a relationship among a set of values.

Since a table is a collection of such relationship, it is generally refrred to using the
mathmatical term relation, from which the relational data model derives its name.
Different terms used in relational model.

Relation a table storing logically related data


Domain This is a pool of values from which the actual values appearing in a given column are
drwan
Tuple A row of a relation is generally referred to as tuple.
Attribute A column of a relation is generally referred to as an attribute.
Degree This refres to the number of attributes in a relation
Cardinality This refers to the number of tuples in a relation.
View It is virtual table that does not really exist but derived from one or more base tables.
Primary Key Set of one or more attributes that can uniquely identify tuples within the relation.
Candidate Key All attribute combinations inside a relation that can serve as promary key are
candidate keys as these are candidated for primary key position/
Alternate Key A candidate key that is no primary key, is called an alternate key.
Foeign Key A non-key attribute, whose values are derived from the primary key of some other
table, is known as foreign key in its current table.
Referential Integrity

A referential integrity is a system of rules that a DBMS uses to ensure that
relationships between records in related tables are valid, and that users don't
accidentally delete or change related data.

We can set referential integrity when all of the following conditions are met:
➢ The matching field from the primary table is a primary key or has a
unique index.
➢ The related fields have the same data type.
➢ Both table belongs to the same database.


When referential integrity s enforced, you must observe the following rules:
➢ You cant enter a value in the foreign key field of the related table that
doesn't exist.
➢ You can't delete a record from a primary table if matching records
exist in a related table.
➢ You can't change a primary key value in the primary table,if that
record has related records.


5.3 MySQL – A Popular Relational Database Management System

MySQL is a freely available open source Relational Database Management
System(RDBMS) that uses Structure Query Language(SQL).

In a MySQL database, information is stored iin Tables.

A single MySQL database can contain many tables at once and store thousands
of individuals records.

MySQL provides you with a rich set of features that support a secure
enviroment for storing, maintaining and accessing data

MySQL is a fast, reliable, scalable alternative to many of the commercial
RDBMSs available today.
MySQL Database System
MySQL database system refers to the combination of a MySQL server instance
and a MySQL database. MySQL operates using client/server architecture in
which the server runs on the machine containing the databases and client
connect to the server over a network.

The server(MySQL server) : listen for client request coming in over the
network and accesses database contents accordning to those request to the
client

Clients are programs that connect to the database server and issue queries in
a pre-specified format.
5.3.1 MySQL and SQL

In order to access data within the MySQL database, all programs and
users must use, Structure Query Language(SQL).

SQL is the set of commands that is recognised by nearly all RDBMSs.

The Structure Query Language(SQL) is a language that enables you to
create and operate on relational databases , which are sets of related
information stored in tables.
Classification of SQL Statements
SQL provides many different types of commands used for different
purposes.SQL command can be mainly divided into following categories.
Data Definition Language(DDL) Commands : Allow you to perform tasks
to data definition e,g
1. creating , altering and dropping
2. granting and revoking privileges and roles.
3. maintenance commands
Data Manipulation Language (DML) Commands : Commands that allow
you to perform data manipulation e.g.

Retrieval,

Insertion,

deletion

and modification of data stored in a database.

Transaction Control Language (TCL) Commands : Commands that allow


you to manage and control the transaction ( a transaction is one complete unit
of work involving many steps) e.g

making changes to database, permanent

undoing changes to database, permanent

creating savepoints

setting properties for current transaction
.
5.3.2 Common MySQL Data Types
Data types are means to identify the type of data and associated operations
for handling.

Difference between Char and Varchar

Char Varchar
As the name suggests, CHAR stands for As the name suggests, VARCHAR stands
characters. for varible characters.
CHAR in MySQL stores characters of fixed VARCHAR in MySQL stores characters of
length. variable size.
CHAR in MySQL is used when the length of VARCHAR in MySQL is used when the
data is known so that we declare the field length of data is unkown.
with the same length.
CHAR in MySQL can store data up to 255 VARCHAR in MySQL can store data up to
characters. 65,535 characters.
CHAR pads values with spaces to reach VARCHAR does not pad values, it stores
the defined length, even if the data is only the actual data without adding extra
shorter. spaces.
CHAR takes 1 byte for each character VARCHAR takes 1 byte for each character
and some extra bytes for holding length
information
Better performance than VARCHAR. Performance is not good as compared to
CHAR.
5.4 Accessing Database in MySQL


Before you start writing SQL commands or making
queries upon the data in tables of a database you
need to open the database for use.

For this after lgging into MySQL you need to issue a
command
use<database name>
e.g
mysql> use inventory;
5.5 Creating Tables in MySQL

Tables are defined with the CREATE TABLE command. When a table is
created, its columns are named, data type and sizes are supplied for
each column.Each table must have at least one column.

The syntax of CREATE TABLE command is:
CREATE TABLE <table-name>
(<column name> <data type> [ ( <size> )],
(<column name> <data type> [ ( <size> )....];


To create an employee table whose schema is as follows :
employee(ecode, ename, gender , grade, gross )
the SQL command will be
CREATE TABLE employee
( ecode integer ,
ename char(20) ,
gender char(1) ,
grade char(2) ,
grade char(2) ,
gross decimal ) ;
5.6 Inserting Data into Table
INSERT command of SQL is used to add rows (tuples) to
table( relations). In its simples form, INSERT takes the following
syntax:
INSERT INTO <table name> [ <column list> ]
VALUES ( <value>, <value> ... );
e.g.
INSERT INTO employee
VALUES(1001, 'Ravi' , 'M' , 'E4' , 4670.00 );

Data can be added only to some columns in a row by specifying the


columns and their data. e.g. NOTE
INSERT INTO employee ( ecode , ename, gender ) In an INSERT statement, only those
VALUES(2014, 'Manjui' , 'F' ); columns cen be omitted that have
eitherdefault value defined or they
allow NULL values
Inserting NULL values
To insert value NULL in a specified column, you can type NULL without quotes
e.g. INSERT INTO EMP (empno , ename , job , extra-detail , deptno)
VALUES( 8100, 'YASH' , 'ANALYST' ,NULL , 20 );
Inserting Dates
Dates are by default entered in 'YYYY-MM-DD' format.
5.7 Making Simple Queries through Select Command

The SELECT statement is used to pull information from the table.The
general form of the statement is:

SELECT what_to_select
FROM which_table
WHERE condition_to_satisfy;

5.7 Selecting All Data



The Simplest form of SELECT retrieves everything from a table. You
just need to specify astrisk in the select statement.
e.g.
mysql>SELECT * FROM pet;
5.7.1 Selecting Particular Rows

We can select particular rows from a table by specifying filtering condition
through WHERE clause of the SELECT statement e.g.
1. Select all pets with gender as male (“m”)
mysql>SELECT * FROM pet
WHERE gender = “m”
2. Select all pets that were born on or after Jan 1, 2019.
mysql > SELECT * FROM pet
– WHERE birth>= '2019-1-1';
3. Select all female dogs.
mysql>SELECT * FROM pet
– WHERE species = 'dog' AND gender = 'f';
4. Select all snakes or birds.
mysql>SELECT * FROM pet
– WHERE species = 'snake' OR species = 'bird'
5. Select all male cats.
Mysql > SELECT * FROM pet
– WHERE species = 'cat' AND gender = 'm'
5.7.3 Selecting Particular Columns

We can select particular columns by specifying
column-names(i.e. Attributes) in the select-list of
the SELECT command e.g.

1. Display names and birth-dates of all pets


mysql>SELECT name, birth FROM pet;

2. Display owners of pets born after Dec 2018.


mysql > SELECT owner FROM pet
WHERE birth > '2018-12-31';
5.7.4 Eliminating Redundant Data (with keyword DISTINCT)


The DISTINCT keyword eliminates duplicate rows from the result
of a SELECT statement.
1. Display names of all pet-owners (non-redundant).
mysql>SELECT DISTINCT owner FROM pet;

2. Display distinct species of pets from table pet.


mysql>SELECT DISTINCT(species) FROM pet;
5.7.5 Selecting From All the Rows – All Keyboard

If in place of keyword DISTINCT , you give keyword ALL
then the result retains the duplicate output rows.

It is just the same aswhen you specify neither DISTINCT
nor ALL.

ALL is essentially a clarifier rather than a function
argument.
mysql>SELECT ALL citymy FROM suppliers;
5.7.6 Viewing Structure of a Table

If you want to know the structure of a table, you can use Describe
or Desc command as per following syntax:

DESCRIBE | DESC <table name>;

e.g.

mysql>DESC pet;

The following command will display the structure of table


pet.
5.7.7 Performing Simple Calculation

To perform simple calculation, you can write the
expression/formula to be calculated next to
keyword SELECT,
e.g.
1. To calculate 3.14159*6*6;
mysql>SELECT 3.14159*6*6;
2. To obtain current system data
mysql>SELECT curdate();
5.7.8 Using Column Aliases

SQL aliases are used to give a table, or a column in a table , a
temporary name.

Aliases are often used to make column names more
readable.

An alias only exists for the duration of that query.

An alias is created with the AS keyword.

e.g.
SELECT CustomerID AS ID
FROM Customers;
5.7.9 Condition Based on a Range

The BETWEEN operator defines a range of values that the
column values must fall in to make the condition true.

The range includes both lower value and the upper value.

For example, to list the items whose QOH falls between 30 to 50
(both inclusive), the command would be :

SELECT icode , descp, QOH


FROM items
WHERE QOH BETWEEN 30 AND 50;
5.7.10 Condition Based on a List

To specify a list of values, IN operator is used.

The IN operator selects values that match any value in a
given list of value.

For example, to display a list of members from 'DELHI'
'MUMBAI','CHENNAI', or 'BANGLORE' cities, you may give.
SELECT * FROM members
WHERE city IN ('DELHI' 'MUMBAI','CHENNAI', 'BANGLORE');


The NOT IN operator finds rows that do not match in the
list.So if you write
SELECT * FROM members
WHERE city NOT IN ('DELHI' 'MUMBAI','CHENNAI');

it will list members not from the cities mentioned in the list.
5.7.11 Condition Based on Pattern Matches

SQL also includes a string-matching operator, LIKE for
comparisons on character string using patterns. Patterns are
described using two special wildcard characters:
– Percent (%) : The % character matches any substring.
– Underscore ( _ ): The _ character matches any character.

The LIKE keyword is used to select rows containing columns
that match a wildcard pattern.example
1. TO list members which are in areas with pin codes starting
with 13, the command is :
SELECT firstname, lastname, city
FROM members
WHERE pin LIKE '13%';

2. To list names of pets who have names ending with 'y', the
command would be:
SELECT name FROM emp WHERE name LIKE '%y';
5.7.12 Searching for NULL

The NULL value in a column can be searched for in a
table using IS NULL in the WHERE clause.

Relational operators like =,< > etc can't be used with
NULL.

For example , to list details of all employees whose
department contain NULL we may use the following
command
SELECT empno, empname, job
FROM emp WHERE DeptNO IS NULL;

Non- NULL values in a table can be listed IS NOT


NULL.
5.8.Creating Tables with SQL Constraints

While creating tables, we may need to apply conditions on
columns e.g. This column must not be blank or NULL for any
record.

To apply conditions on columns, SQL constraints are used.

A Constraints is a condition or check applicable on a field or
set of fields.
Common types of constraints that are applied on table
columns include the following:
5.8.1A SQL NOT NULL constraints

By default , a column can hold NULL. But of you dont want to
allow NULL values in a column, than you may use NOT NULL
constraint on the specifying column. For example

CREATE TABLE Customer


( SID integer NOT NULL,
Last_Name varchar (30) NOT NULL,
First_Name varchar (30) ) ;

Column SID and Last_name cannot include NULL,while


First_Name can include NULL
5.8.1B SQL DEFAULT constraints

The DEFAULT consraints provides a default value to a column
when the INSERT INTO statement does not provide a specific
value.For example
CREATE TABLE Student
( SID integer Unique,
Last_Name varchar (30) ,
First_Name varchar (30) ,
Score DEFAULT 80);

and execute the following SQL statement


INSERT INTO Student(SID , Last_Name, First_Name)
VALUES ( '10' , 'Qureshi' , 'Zeeshan')

Output Will be
5.8.1C SQL UNIQUE constraints

The UNIQUE constraints ensure that all values in a column are
distinct.In other words, no two rows can hold the same value for
a column with UNIQUE constraints. For example

CREATE TABLE Customer


( SID integer Unique,
Last_Name varchar (30) ,
First_Name varchar (30) ) ;

column SID has a unique constraint , and hence cannot include


duplicate values.

INSERT INTO Cutomer


VALUES( '3' , 'Cyrus' ,'Grace' );
This will give an error because the value 3 already exists
5.8.1D SQL CHECK constraints


The CHECK constraints ensure that all values in a column satisfy
certain conditions.

Once defined, the database will only insert a new row or update
an existing row if the new value satisfied the CHECK constraint.

The CHECK constraint is used to ensure data quality. For example
CREATE TABLE Customer
( SID integer CHECK( SID > 0 ),
Last_Name varchar (30) ,
First_Name varchar (30) ) ;
5.8.1E PRIMARY KEY constraints

A primary key is used to uniquely identify each row in a table.

It can either be part of the actual record itself, or it can be an artificial field.

A primary key can consist of one or more fields on a table.When multiple
fields are used as a primary key, they are called a composite key.
Primary Key can be specified either when the table is created or by changing
the existing table structure.

Defining Primary Key through Create Table Command

CREATE TABLE Customer


CREATE TABLE Customer
( SID integer not null ,
( SID integer not null PRIMARY KEY,
OR Last_Name varchar (30) ,
Last_Name varchar (30) ,
First_Name varchar (30)
First_Name varchar (30) ) ;
PRIMARY KEY ( SID )) ;
The latter way is useful if you want to specify a composite primary key
(i.e. Having a group of fields) e.g.

CREATE TABLE Customer


( Branch integer not null;
SID integer not null ,
Last_Name varchar (30) ,
First_Name varchar (30)
PRIMARY KEY (Branch , SID )) ;


Defining Primary Key through Alter Table Command
ALTER TABLE Cutomer
ADD PRIMARY KEY (SID );
5.8.1F Foreign KEY constraints

In an RDBMS, tables reference one another through common fields and
to ensure validity of references, referential integrity is enforced.

Referential integrity is a system of rules that a DBMS uses to ensure
that relationship between records in related tables are valid and that
users don't accidentally delete or change related data.

Just like primary key, Foreign key can also be created in two ways :
through CREATE TABLE and ALTER TABLE commands.
CREATE TABLE ORDERS
( Order_ID integer,
Order_Date date,
Cutomer_SID integer,
Amount double,
Primary Key (Order_ID),
Foreign Key ( Customer_SID ) reference CUSTOMER( SID ) ) ;

The above code will designate Cutomer_SID field of ORDERS table as foreign
key referencing SID field of CUTOMER table.

Defining Foreign Key through Alter Table

ALTER TABLE ORDERS


ADD FOREIGN KEY ( cutomer_sid ) REFERENCE CUSTOMER (SID);
5.8.2 Applying Table Constraints

When a constraints is to be applied on a group of columns of the
table, it is called table constraint.

The table constraints appear in the end of table definition.

For instance, if you want combination of icode nd descp of table
items to be unique, you may write it as follows:
CREATE TABLE items
( icode char( 5) NOT NULL,
descp char(20 ) NOT NULL,
ROL integer,
CHECK (ROL< QOH ),
UNIQUE (icode, descp) );


The above statement ensure that the combination of icode and desc in
each row must be unique.

A constraint applied on one column (e.g as you define not null with a
column definition) is known as column constrains.
5.9 Viewing a Table Structure

The DESC (DESCRIBE) command is use to view an already
created/existing table's structure.
You can use DESC command as follows:
DESC <tablename>;

For example,
DESC empl;
Or DESCRIBE empl;
5.10 Inserting Data into another Table

INSERT command can also be used to take or derive values from
one table and place them in another by using it with a query.To
do this,simply replace the VALUES clause with an appropriate
query as shown in the following example:

INSERT INTO branch1


SELECT * FROM branch2
WHERE gross > 7000.00;


It will extract all those rows from branch2 that have gross more
than 7000.00 and insert this produced result into the table
brach1. But for above command to work , table namely branch1
must be an existing table of the database.
5.11 Modifying Data in Tables

We can modify data in tables using UPDATE command of SQL.

The UPDATE command specifies the rows to be changed using the
WHERE clause, and the new data using the SET keyword.

The new data can be a specified constant, an expression or data from
other tables.

For example , to change the recorder level ROL of all items to 250, you
would write
UPDATE items
SET ROL = 250;


To update the ROL and QOH for items having icode less than 1040
UPDATE items
SET ROL = 400 , QOH = 700
WHERE icode < 1040


To doule the gross pay of employees of grade 'E3' and 'E4'
UPDATE employee
SET gross = gross *2
WHERE (grade = 'E3' OR grade = 'E4' );
5.12 Deleting Data From Tables

DELETE command is used to delete some data from tables.

The DELETE command removes rows from a table.This removes the entire
rows, not individual field values.

The DELETE statement takes the following general form:
DELETE FROM <tablename>
[ WHERE <predicate> ] ;


For instance, to remove the tuples from employee table that have gross
(salary) less than 2200.00, the command will be

DELETE FROM employee


WHERE gross <2200.00;

If you specify no condition with WHERE, then all the rows of the table will be
deleted e.g.

To remove all the contents of items table, we use the command:
DELETE FROM items;
5.13 Altering Tables

The ALTER TABLE command is used to chanage definitions of existing tables.

In general, ALTER TABLE command is used:
– To add a column
– To add an integrity constraint
– To redefine a column(datatype, size, default value).

To add a new column tel_number of type integer in table Empl the command
will be-
ALTER TABLE Empl
ADD ( tel_number integer ) ;


To modify column job of table Empl to have new width of 30 character ,
commad will be-
ALTER TABLE Empl
MODIFY (Job char(30));


Sometimes you may need to change the name of your columns.For this you
can use CHANGE clause of ALTER TABLE command
ALTER TABLE Customers
CHANGE First_Name FirstName VARCHAR(20);
5.14 Dropping Tables

The DROP TABLE command of SQL lets you drop a table from the
database.


The syntax for using a DROP TABLE command is:
DROP TABLE ( IF EXISTS ) <table name>


That is , to drop a table items, you need to write:
DROP Table items;

You might also like