You are on page 1of 94

UNIT:- 1

FUNDAMENTALS
OF
PHP
Lecture:- 1.1

Introduction to PHP

• PHP stands for Hypertext Pre-Processor (Initially known


as Personal Home Page).

• PHP is widely used Open-Source general purpose


scripting language that is especially suited for Web
Development and can be embedded into HTML.

• PHP is Server-Side Scripting language.

• PHP is Loosely Typed language.


 Loosely Typed Language:- In this type, the variable
converts to the correct datatype automatically,
depending on its value.
 Strongly Typed Language:- In this type, we have to
declare(define) the datatype and name of the variable
before using it.

• It was originally created by Danish-Canadian programmer


Ramus Lerdorf in 1994.

• The Script starts with “<?php” and ends with “?>”. These
tags are called “Canonical PHP tags”.

• Every command ends with semi-colon (;).


• Example:-

<!DOCTYPE html>
<html>
<head>
<title>Learn Vern</title>
</head>
<body>
<?php
echo (“Welcome to Learn Vern!”);
?>
</body>
</html>

• PHP Frameworks:-
• PHP CMS (Content Management System):-
Lecture:- 1.2

Understanding SDLC Process

• The SDLC methodology focuses on the following phases of


Software Development

1. Requirement Gathering
2. Analysis and SRS (Software Requirements
Specification)
3. Designing
4. Implementation
5. Testing and Integration
6. Maintenance

Lecture:- 1.4

Client-Server Architecture

• Basically, it is a computer network architecture where man


clients request and receive some service(s) from
centralized server.

• Client:- a piece of hardware/software or application that


takes the input and send request to the server.

• Server:- a piece of hardware/software that receives and


process requests from clients.
UNIT:- 2

DBMS
And
MySQL
Lecture:- 2.1

What is DATA?

• DATA is any sort of information which is stored in


computer memory.

• This information can later be used for a website, an


application or any other client to store for future purpose.

Lecture:- 2.4

What is DATABASE?

• Database (DB) are organized, they have structure, and all


the data they store it fits into that structure.

• More specifically, a Database is an electronic system that


allows data to be stored, easily accessed, manipulated and
updated.

• Database are quite similar to spreadsheets as they are


mostly made up of tables which contains rows and
columns like a spreadsheet. A database needs to be hosted
or created on some special database platform, some of the
famous Database platforms are:-

 Microsoft Access
 SQLite
 MySQL
 PostgreSQL
Lecture:- 2.3

What is Database Management System(DBMS)?

• A database management system is a software used to


perform different operations, like addition, access,
updating, and deleting of the data, like adding of name in
the database for an online retail store as a customer. A
database management system acts as the backbone of a
database.

Database VS Database Management System(DBMS)

• While database can provide the data to the website and


have a meaningful way to access data, it still cannot
understand the language and method which a website may
use to fetch the data, i.e., it cannot understands the
command on its own.
• To tackle this problem, we bring in the concept of
Database Management System
• A DBMS understand the command and the queries which
define what data is required by the Application or Website
and thus use the meaningful method of accessing the
database to retrieve the information.

Application
or DBMS Database
Website
• It is said that a DBMS act as connecting bridge between the
database and the user.
• DBMS actually understand the queries and help database
to understand the requirements.
• The basic difference between Database and DBMS is that a
database store the data and provide a method to access it
while a DBMS actually converts the queries into a
meaningful command to invoke the method used to access
the data

Types of Database

• Relational Database
• Hierarchical Database
• Network Database
• Object-oriented Database
• NoSQL Database
Relational Database

• The first thing to know is that database which we deal the


most, like SQL, is based upon Relational Databases.

• They store data in the form of tables which are related to


each other.

Hierarchical Database

• The Hierarchical databases are actually databases which


follow a tree-like structure.
Network Database

• Network Databases are similar to Hierarchical ones, the


only difference is one child is connected to many parents.

Object-oriented Database
Lecture:- 2.4

SQL (Structured Query Language)

• SQL is a database language which we use to perform


certain operations on the existing database and also to
create a database.

Types of SQL Queries

• DDL(Data Definition Language)


 It is used to define structure od database and tables.
o Create
o Drop
o Alter
o Truncate

• DML(Data Manipulation Language)


 It is used for inserting/storing, modifying and
deleting the data stored in the database.
o Insert
o Update
o Delete

• DQL(Data Query Language)


 It is used to retrieving the data from the database.
o Select
• TCL(Transaction Control Language) or DTL (Data
Transaction Language)
 It deals with the transaction within the database.
o Commit
o Rollback
o Save-point

• DCL(Data Control Language)


 It is used for providing security to the database
objects (like procedures. Views. Tables, etc.)
 It allows us to control access to data within the
database.
o Grant
o Revoke

Lecture:- 2.5

DDL(Data Definition Language)

• CREATE • DROP
• ALTER • TRUNCATE

DML(Data Manipulation Language)

• INSERT

• UPDATE
• DELETE

DCL(Data Control Language)

• GRANT

• REVOKE
TCL(Transaction Control Language) or DTL (Data
Transaction Language)

• COMMIT

• ROLLBACK

• SAVEPOINT
DQL(Data Query Language)

• SELECT

Lecture:- 2.5

SQL Data Types

• There are 4 types SQL Data Types. They are:-


 Numeric Data Types
 String Data Types
 Date Data Types
 Miscellaneous Data Types
Numeric Data Types

String Data Types

• String is the collection of character.


CHAR vs. VARCHAR

BINARY and VARBINARY


BLOB and TEXT

DATE Data Types

TIMESTAMP vs. DATETIME


Miscellaneous Data Types

Lecture:- 2.6

SQL CONSTRAINTS

• In SQL we create a table, to restrict the data on the table


or column we use Constraints. SQL constraints are used to
specify rules for the data in a table.
• Constraints are used to limit the type of data that can go
into a table. This ensures the accuracy and reliability of
the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
• Constraints can be column level or table level. Column
level constraints apply to a column, and table level
constraints apply to the whole table.
• The following constraints are commonly used in SQL:-

 NOT NULL
o Ensures that a column cannot have a NULL value

 UNIQUE
o Ensures that all values in a column are different

 PRIMARY KEY
o A primary key is a field which can uniquely identify
each row in a table. And this constraint is used to
specify a field in a table as primary key. It is
combination of NOT NULL and UNIQUE.

 DEFAULT
o Sets a default value for a column if no value is
specified

 FOREIGN KEY
o A Foreign key is a field which can uniquely identify
each row in a another table. And this constraint is
used to specify a field as Foreign key.

 CHECK
o Ensures that the values in a column satisfies a specific
condition

 CREATE INDEX
o Used to create and retrieve data from the database
very quickly
Lecture:- 2.7

CREATE, DROP and SHOW Database

• To create a new database using SQL Command


 “CREATE DATABASE dbname;”.

• To delete a database using SQL Command


 “DROP DATABASE dbname;”.

• We could apply conditions “IF EXISTS” or “IF NOT


EXISTS” to above commands in case if database is already
exists or not.

Lecture:- 2.8

CREATE Table

• The MySQL CREATE TABLE command is used to create a


new table into the database. A table creation command
requires three things:
1. Name of the table.
2. Name of Fields.
3. Definitions for each field.

• SYNTAX:-
 CREATE TABLE table_name (col1_name
col1_datatype, col2_name col2_datatype, ....);
Make structure of table “Products”

Field
prod_id prod_code name quantity Price
Name
DECIMAL(10,
Datatype INT CHAR(4) VARCHAR(50) INT
2)

101 MARK Blue Marker 500 10.55

102 MARK Red Marker 1500 8.33

DATA 103 PENC Pencil 2B 1458 5.25

104 MARK Black Marker 300 15.0

105 PENC Pencil 2H 2540 7.80

SQL Query to create above Table

CREATE TABLE IF NOT EXISTS Products


(prod_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
prod_code CHAR(4) NOT NULL,
name VARCHAR(50) NOT NULL,
quantity INT UNSIGNED NOT NULL DEFAULT 0,
price DECIMAL(10,2) UNSIGNED NOT NULL DEFAULT
99.9,
PRIMARY KEY (prod_id));
utf8mb4_general_ci

In this “ci” means Case Insensative.


Lecture:- 2.9

SQL INSERT Statement

• MySQL INSERT statement is used to “insert data” in


MySQL table within the database. We can insert single or
multiple records using a single query in MySQL.

• Syntax:-
 The SQL INSERT INTO command is used to insert
data in MySQL table. Following is a generic syntax:

INSERT INTO table_name (field1, field2, …., fieldN)


VALUES (value1, value2,…, valueN);

SQL Query to insert data in table Products

• INSERT INTO Products(prod_id, prod_code, name,


quantity, Price) VALUES (101, “MARK”, “Blue Marker”,
500, 10.55);

OR

• INSERT INTO Products VALUES (101, ‘MARK’, ‘Blue


Marker’, 500, 10.55);

 We must have to use single quotation ( ‘ ’ ) or double


quotation ( “ “ ) in case of STRING.
SQL Query to insert data in table Products

• INSERT INTO Products VALUES (NULL, ‘MARK’, ‘Red


Marker’, 1500, 8.33);

These Options are visible because we set PRIMARY KEY on


“prod_id” column.

SQL Query to insert data in table Products

• INSERT INTO Products VALUES


(NULL, 'PENC', 'Pencil 2B', 1458, 5.25),
(NULL, "MARK", 'Black Marker', 300, 15.0);

• INSERT INTO Products (prod_code, name, quantity, Price)


VALUES ("PENC", "Pencil 2H", 2540, 7.8);
SQL Query to insert data in table Products

• INSERT INTO products(`prod_code`, name) VALUES


("PENC", "Pencil 4H");
New Row Details:-

Column
Values Reason
heading

prod_id 106 AUTO_INCREMENT

prod_code PENC INSERT INTO statement

name Pencil 4H INSERT INTO statement

quantity 0 DEFAULT Value is 0

price 99.90 DEFAULT Value is 99.9


SQL SELECT Statement
• MySQL SELECT statement is used to “fetch data from the
one or more tables” in MySQL.

• Syntax for Specified Fields:-

SELECT expressions FROM tables [WHERE conditions];

• Syntax for All Fields:-

SELECT * FROM tables [WHERE conditions];

SQL Query to select data in table Products

• SELECT * FROM `products`


This will show all the data from table “products”
SQL Query to select specific data in table Products(only
when we have 1 table)

• SELECT prod_id,
prod_code,
name
FROM `products`;

This will show specific fields data from table “products”


i.e. prod_code, prod_id and name fields data.

SQL Query to select specific data in table Products(in


case of multiple table)
• SELECT • (table_name.field_
products.prod_id, heading)
products.prod_code,
products.name
FROM `products`;
Comparison Operators
• For numbers(INT, DECIMAL, FLOAT), we can use
Comparison Operators

‘=‘ Equal to

‘<>’ or ‘!=’ Not equal to

‘>’ Greater than

‘<’ Less than

‘>=’ Greater than or equal to

‘<=’ Less than or equal to

SQL Query to select specific data with condition in table


Products
• SELECT
products.prod_id,
products.prod_code,
products.name
FROM `products`
WHERE
products.prod_id <= 103;

• Specific fields data upon a condition product id <= 103


• SELECT
products.prod_id,
products.prod_code,
products.name
FROM `products`
WHERE
products.name = ‘Blue Marker’;

• Specific fields data upon a condition that name must be


Blue Marker.
• SELECT
products.prod_id,
products.prod_code,
products.name
FROM `products`
WHERE
products.name <> ‘Blue Marker’;

• Specific fields data upon a condition that its name must


not be Blue Marker.

String Pattern Matching

• For Strings, in addition to full matching using operators ‘=’


and ‘<>’, we can perform pattern matching using
operators LIKE (or NOT LIKE) with wildcard characters.

• The wildcard ‘_’ matches any single character whereas,


‘%’ matches any number of characters (including zero).
• Examples:-

 LIKE ‘abc%’ matches strings beginning with ‘abc’;

 LIKE ‘% abc’ matches strings ending with ‘abc’;

 LIKE ‘% abc%’ matches strings containing with ‘abc’;

 LIKE ‘___’ matches strings containing exactly 3


characters;

 LIKE ‘a__%’ matches strings starts with ‘a’ and


contains at least 3 characters;

 LIKE 'a%b‘ matches strings starts with ‘a’ and ends


with ‘b’;

 LIKE 'a_b%‘ matches strings begin with ‘a’ followed


by any character and its third character is ‘b’.

Symbol Description Example


h[oa]t finds hot
Represents any single
[] and hat, but not
character within the brackets
hit
h[^oa]t finds hit,
Represents any character not
^ but not hot and
in the brackets
hat
Represents any single
c[a-b]t finds cat
- character within the specified
and cbt
range
• SELECT * FROM `products` WHERE products.name
LIKE '%marker%';

• name fields data of table products upon a condition that


its name must contain the word Marker.

• SELECT * FROM `products` WHERE products.name


NOT LIKE 'r_D%';

• name fields data of table products upon a condition that


its name must NOT contain the word which begin with ‘r’
second character can be anything and third character
must be ‘d’ followed by any number of characters.
Lecture:- 2.10
ARITHMETIC Operators

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

Modulus
%
(Remainder)
LOGICAL Operators
• AND • OR • NOT

Checking more than one conditions using LOGICAL


Operators

• SELECT * FROM `products` WHERE products.name


NOT LIKE 'r_D%' AND prod_code = 'mark';

• name fields data of table products upon the conditions


that its name must NOT contain the word which begin
with ‘r’ second character can be anything and third
character must be ‘d’ followed by any number of
characters and it must be a MARKER.
Lecture:- 2.11
IN and NOT IN Conditions
• The IN condition is used to reduce the use of multiple
OR in a SELECT, INSERT, UPDATE and DELETE
statements
• Syntax:-

Expression IN (val1, val2, val3, …., valN);


Example:-
• The following SQL statement selects all customers that are
located in "Germany", "France" or "UK":

• Using IN:-
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

• Using OR:-
SELECT * FROM Customers
WHERE Country = 'Germany‘ OR Country = 'France‘
OR Country = 'UK');
• SELECT * FROM `products` WHERE products.name IN
(‘Blue Marker’, ‘Red Marker’, ‘Black Marker’);

• It will show the date of the row whose name is among any
of the Blue Marker, Red Marker, Black Marker

• SELECT * FROM `products` WHERE products.name


NOT IN (‘Blue Marker’, ‘Red Marker’, ‘Black Marker’);

• It will show the date of the row whose name is among any
of the Blue Marker, Red Marker, Black Marker
Lecture:- 2.12
NULL and NOT NULL Conditions
• NULL is a special value, which represents “no value”,
”missing value” or “unknown value”.

• To check if a column contains NULL by using IS NULL or


IS NOT NULL.

• It is not possible to check NULL Value using comparison


operators like “=”, “<>” or “<”.

• Syntax:-

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

• Example:-

• SELECT * FROM `products` WHERE products.name IS


NULL;

• It will show the date of the row whose whether there is


any NULL value in name column.
• SELECT * FROM `products` WHERE products.name IS
NOT NULL;

• It will show the date of the row whose whether there is


NOT any NULL value in name column.

Lecture:- 2.13
ORDER BY Clause

• You can order the rows selected using ORDER BY clause.

• In default it will arrange in ASCENDING order.

• Syntax:-

SELECT … FROM table_name WHERE condition


ORDER BY column1 ASC|DESC, column2 ASC|DESC, …
• SELECT * FROM `products` WHERE products.name
LIKE "_e%" ORDER BY products.prod_code ASC;

• It will select the date whose second letter in name column


is “e” and sort the selected in ASCENDING order
according to prod_code.

• SELECT * FROM `products` WHERE products.name


LIKE "_e%" ORDER BY products.quantity ASC,
products.Price DESC;

• It will select the date whose second letter in name column


is “e” and sort the selected in ASCENDING order
according to quantity and price in DESCENDING order
but it will give priority to the first one i.e. quantity.
• SELECT * FROM `products` WHERE products.name
LIKE "_e%" ORDER BY products.Price;

• If ASC|DESC is not mentioned in that case it will be sorted


in ASCENDING order.
LIMIT Clause
• A SELECT query on a large database may produce many
rows. LIMIT clause is used to limit the number of rows
displayed.
• Syntax:-

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

• SELECT * FROM `products` LIMIT 2;

• SELECT * FROM `products` WHERE products.prod_id >


102 LIMIT 3;
LIMIT Clause
• LIMIT can be used to skip the rows also.

• Syntax:-

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number1, number2;

• Number1:- number of rows to be skipped


• Number2:- number of rows to be shown

• SELECT * FROM `products` LIMIT 3,3;

• SELECT * FROM `products` LIMIT 3,2;


Lecture:- 2.14
AS - Alias

• Keyword AS is used to define an alias for an identifier


(such as column name, table name). The alias will be used
in displaying name only it won’t save in database. It can
also be used as reference.

• Syntax:-

SELECT column_name AS alias_name


FROM table_name AS alias_name;

SELECT prod_id AS 'ID',


Define alias which is
prod_code AS 'Code', to be used as display
name AS 'Description', names
Price AS 'Unit Price‘
FROM `products`
ORDER BY ID DESC; Use alias as reference
CONCAT() - Function

• The CONCAT() function adds two or more expressions or


columns together

• Syntax:-

CONCAT(expression1, expression2, expression3, …);

SELECT prod_id AS 'ID',


CONCAT(prod_code, ‘-’, name) AS ‘Product
Description', Price
FROM `products`
ORDER BY ID DESC;

• Using UI how to change column from “NOT NULL” to


“NULL”
SELECT * FROM `products`

INSERT INTO products VALUES(NULL, "Eraser", 1500,


5.25);

OR

INSERT INTO products VALUES(107, NULL, "Eraser",


1500, 5.25);
SELECT * FROM `products`

SELECT prod_id AS 'ID',


CONCAT(prod_code, ‘-’, name) AS ‘Product
Description', quantity, Price
FROM `products`
ORDER BY ID;
DISTINCT Clause

• DISTINCT clause is used to remove duplicate records


from the table and fetch only the unique records. The
DISTINCT clause is only used with the SELECT statement

• Syntax:-

SELECT DISTINCT expressions


FROM table
WHERE conditions;

• In case of one expression in the DISTINCT clause, the


query will return the unique values for that expression.

• In case of more than one expression in the DISTINCT


clause, the query will retrieve unique combinations for
the expressions listed.

• DISTINCT clause doesn’t ignore NULL values.

INSERT INTO products VALUES(“ERAS”, "Eraser",


1700, 10.55);
SELECT DISTINCT price, name
FROM products;

• In above query it will take the combination of both price


and name. In table products the combination of both
price and name is different either name is different or
price.

SELECT DISTINCT price FROM products;


SELECT DISTINCT name FROM products;

SELECT DISTINCT prod_code FROM products;

• Here DISTINCT Clause consider NULL as a unique value.


GROUP BY Clause

• The GROUP BY clause allows to collapse multiple records


with a common value into groups.

• Syntax:-

SELECT expressions1
FROM table
GROUP BY expression2;

SELECT * FROM products GROUP BY prod_code;

SELECT price FROM products GROUP BY prod_code;


AGGREGATE FUNCTIONS

Function Description

AVG() Returns the Average Value

SUM() Returns the SUM

MIN() Returns the Smallest Value

MAX() Returns the Largest Value

COUNT() Returns the Number of Rows

FIRST() Returns the First Value

LAST() Returns the Last Value

HAVING
• HAVING is similar to WHERE, but it can operate on
GROUP BY aggregate functions, whereas WHERE
operates only on columns.
• Syntax:-

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
SELECT prod_code AS ‘Product Code’, COUNT(*) AS
‘Count’, CAST(AVG(price) AS INT) AS ‘Average’ FROM
products;

• Columns Count and Average are created with above


query just to show data, they will not save in database.

• Product code will be the first code in prod_code field.


• Count will give the total number of rows in that table.
• Average will be the average value of all Price field.

SELECT prod_code AS ‘Product Code’, COUNT(*) AS


‘Count’, CAST(AVG(price) AS INT) AS ‘Average’ FROM
products GROUP BY prod_code;

SELECT prod_code AS `Product Code`, COUNT(*) AS


`Count`, CAST(AVG(Price) AS INT) AS `Average` FROM
products GROUP BY prod_code HAVING Count>=3;
Lecture:- 2.15
UPDATE Query

• UPDATE statement is used to update data of the table


within the database.

• It is used to modify the data of the table. It will modify


data not the structure.

• Syntax:-

UPDATE table_name
SET field1 = new_value1,
field2 = new_value2
[WHERE Clause]

• If we don’t use WHERE clause then it will make amends


in whole field. WHERE is used to set conditions to change
a particular record.

SELECT * FROM `products`;

INSERT INTO products VALUES(109, NULL, 'Sharpner',


1000, 7.12);
UPDATE products SET products.prod_code = 'ERAS',
products.name = 'Gum Eraser'
WHERE products.prod_id = 107;

• If we don’t use WHERE clause then the


prod_code will be ERAS
name will be Gum Eraser
Of every row in that particular field
UPDATE products SET products.Price = Price + 5;

DELETE Query

• DELETE is used to delete rows from a table.

• Syntax:-

DELETE FROM table_name


WHERE (Conditions);

DELETE FROM products


WHERE `products`.`prod_id` = 109;
Lecture:- 2.15
ALTER Query

• ALTER is used to change the structure of the table.

• Syntax:-

i. To add single field

ALTER table_name
ADD new_column_name column_definition
[FIRST| AFTER column_name];

ii. To add single field

ALTER table_name
ADD new_column_name column_definition
[FIRST| AFTER column_name],
ADD new_column_name column_definition
[FIRST| AFTER column_name];

• column_definition consist of column datatype,


constraint, default value, etc.

ALTER TABLE products


ADD supplier_id INT UNSIGNED
NOT NULL
DEFAULT 0
AFTER prod_id;
ALTER TABLE products
ADD supplier_name VARCHAR(225) NULL,
ADD supplier_contact CHAR(9) NULL;

DESCRIBE Command

• DESCRIBE or DESC both are equivalent. The DESC is the


short form of DESCRIBE command and used to display
the information/structure of a table like column names
and constraints on column name.
DESCRIBE `products`;

MODIFY

• used to modify column definition of the table.

• Syntax:-

ALTER table_name
MODIFY column_name column_definition
[FIRST| AFTER column_name];

1. ALTER TABLE `products`


MODIFY supplier_name VARCHAR(100);

2. DESCRIBE `products`;
DESCRIBE `products`;

CHANGE COLUMN

• used to modify the name and definition of column.

• Syntax:-

ALTER table_name
CHANGE COLUMN old_name new_name
column_definition
[FIRST| AFTER column_name];

1. ALTER TABLE `products`


CHANGE COLUMN supplier_contact supplier_mobile
VARCHAR(10);

2. SELECT * FROM `products`


DESCRIBE `products`;

DROP COLUMN

• used to drop/delete column.

• Syntax:-

ALTER TABLE table_name


DROP column_name;

1. ALTER TABLE `products` DROP supplier_mobile;

2. SELECT * FROM `products`;


Lecture:- 2.16
RENAME TO

• used to change the name of the table.

• Syntax:-

ALTER table_name
RENAME TO new_table_name;

1. ALTER TABLE `products` RENAME TO


Products_Master;

2. SELECT* FROM Products_Master;

TRUNCATE TABLE

• used to remove the data of the table without changing


it structure.

• Syntax:-

TRUNCATE table_name;
Lecture:- 2.17
Foreign Key

• It is a key used to link two tables.

• The table with the Foreign Key Constraint (child table)


is connected to another table (parent table).

• The connection is between the child table’s Foreign Key


Constraint and the parent table’s Primary Key.

• Foreign Key Constraints are used to help maintain


consistency between the tables. If we delete any data from
the parent table then child table data will also be deleted
but vice versa is not possible.

• Also help to prevent entering inaccurate data in the


child table by requiring a parent table record exists for
every record that is entered in the child table.

• Syntax:-

CREATE TABLE tablename(


…..
…..
CONSTRAINT constraintName
FOREIGN KEY(columnName)
REFERENCES parentTableName (columnName)
);
1. Create a table and insert given data using QUERY.

2. Table Name:- Suppliers

sup_id name phone

INT VARCHAR(100) CHAR(10)

1001 Jain Agency 1234567890

1002 Meet Corporation 9012345678

1003 ABC Traders 7890123456

1004 Shah Company 2345678901

• In product table, to know the supplier of product we


create a separate table of suppliers and the primary
key of supplier table i.e. sup_id will be assign as an
foreign key in Products_Master table (child table)

CREATE TABLE Suppliers


(sup_id INT UNSIGNED NOT NULL
AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
phone CHAR(10) NOT NULL,
PRIMARY KEY (sup_id));

INSERT INTO suppliers VALUES (1001, ‘Jain Agency’,


1234567890), (1002, ‘Meet Corporation’,
9012345678), (‘ABC Traders’, 7890123456), (‘Shah
Company’, 2345678901);
Foreign Key

• It is a key used to link two tables.

• The table with the Foreign Key Constraint (child table)


is connected to another table (parent table).

• The connection is between the child table’s Foreign Key


Constraint and the parent table’s Primary Key.

• Foreign Key Constraints are used to help maintain


consistency between the tables. If we delete any data from
the parent table then child table data will also be deleted
but vice versa is not possible.

• Also help to prevent entering inaccurate data in the


child table by requiring a parent table record exists for
every record that is entered in the child table.

• Syntax:-

CREATE TABLE tablename(


…..
…..
CONSTRAINT constraintName
FOREIGN KEY(columnName)
REFERENCES parentTableName (columnName)
);
1. CREATE TABLE IF NOT EXISTS Products
(prod_id INT UNSIGNED NOT NULL
AUTO_INCREMENT,
prod_code CHAR(4) NOT NULL,
name VARCHAR(50) NOT NULL,
quantity INT UNSIGNED NOT NULL DEFAULT 0,
price DECIMAL(10,2) UNSIGNED NOT NULL
DEFAULT 99.9,
PRIMARY KEY (prod_id));

2. ALTER TABLE `products`


ADD products.supplier_id INT UNSIGNED NOT
NULL AFTER price;

3. UPDATE `products` SET products.supplier_id = 1001;

4. ALTER TABLE `products`


ADD FOREIGN KEY (supplier_id)
REFERENCES suppliers (sup_id);
UPDATE `products`
SET `supplier_id` = '1003'
WHERE `products`.`prod_id` = 102;

Lecture:- 2.18

MySQL Joins

• What are Joins?

o A relational database consists of multiple related


tables linking together using common columns which
are known as foreign key columns.

o A join is a method of linking data between one


(self-join) or more tables based on values of the
common columns between the tables.

• Types of Joins

1. Inner Join 4. Full Join


2. Left Join 5. Cross Join
3. Right Join
• Inner Join

• INNER JOIN returns records that have matching values in


both tables.

• Syntax:-

SELECT column_names
FROM table 1(INNER)
JOIN table2
ON table1.columnName = table2.columnName
WHERE condition;

• JOIN or INNER JOIN are same, the INNER keyword is


optional as all joins are considered to be inner joins unless
otherwise specified.

column_names table1 table2

LEFT table or the table in


Table1 column RIGHT table or the source table
which we have import
names whose data we have to import.
data

CHILD Table CHILD Table Parent Table


1. INSERT INTO products(`prod_code`, name, quantity,
supplier_id) VALUES ("PENC", "Pencil 4H", 250,
1004);
2. INSERT INTO products(`products`.`prod_code`, name,
quantity, supplier_id) VALUES ("PENC", "Pencil 4H",
250, 1004);
3. INSERT INTO products(`products`.`prod_code`, name,
quantity, supplier_id) VALUES ("PENC", "Pencil 4H",
250, 1004);
4. DELETE FROM `products` WHERE
`products`.`prod_id` = 108;
5. DELETE FROM `products` WHERE
`products`.`prod_id` = 109;

• SELECT *
FROM `products`
INNER JOIN `suppliers`
ON products.supplier_id = suppliers.sup_id;
• Left Join

• LEFT JOIN or the LEFT OUTER JOIN returns all records


from the left table, and the matched records from the right
table.

• The LEFT JOIN selects all data from the left table whether
there are matching rows exist in the right table or not. In
case there is no matching rows from the right table found
NULLs are used for columns of the row from the right
table in the final result set.

• Syntax:-

SELECT column_names
FROM table 1
LEFT JOIN table2
ON table1.columnName = table2.columnName
WHERE condition;
• SELECT *
FROM `products`
LEFT JOIN `suppliers`
ON products.supplier_id = suppliers.sup_id;

• If any Foreign Key is NULL, in that case every value of


Parent table will become NULL for that particular row.

• Right Join

• RIGHT JOIN or the RIGHT OUTER JOIN clauses select all


rows from the right table and matches rows in the left
table. If a row from the right table does not have matching
rows from the left table, the column of the left table will
have NULL in the final result set.
• Syntax:-

SELECT column_names
FROM table 1
RIGHT JOIN table2
ON table1.columnName = table2.columnName
WHERE condition;

• SELECT *
FROM `products`
RIGHT JOIN `suppliers`
ON products.supplier_id = suppliers.sup_id;

• If any foreign key is NULL in left table, in that case every


value of child table will become NULL for that
particular row.

• Full Join
• FULL JOIN or FULL OUTER JOIN returns all the records
which either have a match in the let or the right table.

• MySQL doesn’t support the FULL OUTER JOIN syntax.

• To get data of FULL OUTER JOIN we have to:-

o Combined the data of LEFT JOIN and RIGHT JOIN


query using UNION ALL operator and eliminate the
repeated data using condition in WHERE clause.

• SELECT *
FROM `products`
RIGHT JOIN `suppliers`
ON products.supplier_id = suppliers.sup_id

UNION ALL

SELECT *
FROM `products`
RIGHT JOIN `suppliers`
ON products.supplier_id = suppliers.sup_id
WHERE products.prod_id
IS NULL;
Lecture:- 2.19

MySQL Views

• VIEWS are virtual table that do not store any data of their
own but display data stored in other tables.

• Advantage of View:-

o Views are a way to limit the data presented.

o Complex data across more than one table can be


combined into a single View. This can make life easier
for business analyst and programmer.

• Views are managed by the system. When data in the


related tables are changed, added, or updated, the Views
is updated by the system.

• A VIEW is created by SELECT Statement. SELECT


statements to take data from the source table to make a
VIEW.

• Syntax:-

• CREATE [OR RELPLACE] VIEW view_name AS


SELECT columns
FROM table
WHERE conditions;
CREATE OR REPLACE VIEW products_view AS
SELECT products.prod_id, products.prod_code,
products.name AS 'Product Name', products.quantity,
products.price, suppliers.sup_id, suppliers.name
AS 'Supplier Name'
FROM products
LEFT JOIN suppliers
ON products.supplier_id = suppliers.sup_id;

MySQL Views

• The ALTER VIEW statement is used to modify or update


of the existing VIEW without dropping it.

• Syntax:-

• ALTER VIEW view_name AS


SELECT columns
FROM table
WHERE conditions;

MySQL DROP Views

• The ALTER VIEW statement is used to drop the VIEW.

• Syntax:-
DROP VIEW IF EXISTS view_name;
Lecture:- 2.20

MySQL Functions

• Functions are a statement or a group of statements to use


that to reuse statements without writing we just have call
the function. Function returns something.

• A stored is special kind stored program that returns a


single value.

• Stored Functions are used to encapsulate common


formulas or business rules that are reusable among SQL
statements or stored programs.

• CREATE FUNCTION statement is used to create a stored


function.

• Syntax:-

DELIMITER //
CREATE FUNCTION function_name(para1, para2,….)
RETURNS return_datatype
[NOT] DETERMINISTIC
BEGIN
Statements
END //
CREATE TABLE IF NOT EXISTS Students
(id INT UNSIGNED NOT NULL AUTO_INCREMENT,
fname VARCHAR(50) NOT NULL,
lname VARCHAR(50) NOT NULL,
class CHAR(4) NOT NULL,
age INT NOT NULL,
marks INT NOT NULL,
PRIMARY KEY(id));

INSERT INTO Students


VALUES (1, “Meet”, “Shah”, “CE”, 22, 55),
(2, “Shubham”, “Gupta”, “EC”, 26, 85),
(3, “Jigar”, “Darji”, “EE”, 22, 65),
(4, “Keval”, “Gajjar”, “EC”, 32, 70),
(5, “Parth”, “Mehta”, “CE”, 23, 20);
DELIMITER //
CREATE FUNCTION Marksfunction(marks INT)
RETURNS VARCHAR(50)
BEGIN
DECLARE LEVEL VARCHAR(50);
IF marks < 20 THEN SET LEVEL = 'Poor Performance';
ELSEIF (marks > 20 AND marks < 60) THEN SET
LEVEL = 'Moderate';
ELSEIF (marks > 60) THEN SET LEVEL = "Excellent";
END IF;
RETURN(LEVEL);
END

SELECT
CONCAT(fname, ' ', lname) AS 'Name',
class, age, marks,
marksfunction(marks) AS 'Performance'
FROM students;
Lecture:- 2.21

MySQL Procedure

What is MySQL Stored Procedure?

• A procedure (often called a stored procedure) is a


collection of pre-compiled SQL statements stored inside
the database. It is a subroutine or a subprogram in the
regular computing language. A procedure always contains
a name, parameter lists, and SQL statements.

• A procedure is called a recursive stored procedure when it


calls itself. Most database systems support recursive
stored procedures. But, it is not supported well in MySQL.

• We can call a function inside the procedure and also


Procedure can return a NULL.

Creating a Procedure

• In MySQL, a procedure can also be created. A procedure


can return one or more than one value through
parameters or also may not return at all. The procedure
can be used in SQL queries.

• It is similar to function, we can use procedures as SELECT,


INSERT, UPDATE, DELETE data or any other queries to
perform operations without fire same query many times.

• You have to only use functions or parameterized functions


to fire queries
• It is not appropriate way to use PROCEDURE many times
in server because it causes memory wastage.

• If we have created Procedures then it is stored in cached


memory then it occupies the space and it causes bad while
performing the actions on database on server.

• Syntax:-

DELIMITER //
CREATE PROCEDURE procedure_name
(parameter datatype, para2 datatype)
BEGIN
Declaration_section
Executable_section
END //

DELIMITER //
CREATE PROCEDURE view_products()
BEGIN
SELECT * FROM products;
END //
• To EXECUTE Procedure

CALL view_products;

DELIMITER //
CREATE PROCEDURE insert_products (IN
p_prod_code CHAR(4), IN p_name VARCHAR(50), IN
p_quantity INT(10), IN p_price DECIMAL(10,2))
BEGIN
INSERT INTO
products(prod_code,name,quantity,price) VALUES
(p_prod_code,p_name,p_quantity,p_price);
END//
ALTER TABLE `products` CHANGE `supplier_id`
`supplier_id` INT(10) UNSIGNED NULL;

• To EXECUTE Procedure

CALL insert_products ('PEN','Ink Pen',50,100);

SELECT * FROM `products`;

DROP PROCEDURE

DROP PROCEDURE [IF EXISTS] procedure_name;


Difference between Stored Procedure and Functions

STORED PROCEDURE FUNCTION

Supports Input and Output


Supports only Input Parameters
parameters

There is no provision to Call


We can Call Functions from a SELECT
Procedures from SELECT, HAVING
statements.
and WHERE statements.

Transactions can be used in Stored


No Transactions are allowed.
Procedures.

Need not return any value. Must return a result or value.

All the Database Operations like


SELECT, INSERT, UPDATE and Only SELECT is allowed.
DELETE can be performed.

Stored procedures can call functions


Functions cannot call a Store Procedure.
as needed.
Lecture:- 2.22

MySQL Trigger

• In MySQL, a Trigger is a stored program invoked


automatically in response to an event such as INSERT,
UPDATE, or DELETE that occurs in the associated table.
For Example, we can define a trigger that is invoked
automatically before a new row is inserted into a table.

• MySQL supports triggers that are invoked in response to


the INSERT, UPDATE or DELETE event.

• A MySQL trigger is a special type of stored procedure.

• It is special because it is not called directly like a stored


procedure.

• The main difference between a Trigger and a Stored


Procedure is that a trigger is called automatically when a
data modification event is made against a table whereas a
stored procedure must be called explicitly.

• In MySQL, trigger can also be created. There are 6 type of


triggers.

• After INSERT • Before UPDATE


• Before INSERT • After DELETE
• After UPDATE • Before DELETE
• Syntax:-

DELIMITER //
CREATE TRIGGER trigger_name
{BEFORE | AFTER}
{INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW trigger_body;

END //

1. CREATE TABLE IF NOT EXISTS Marks


(id INT UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(50) NOT NULL,
m1 INT UNSIGNED NOT NULL,
m2 INT UNSIGNED NOT NULL,
m3 INT UNSIGNED NOT NULL,
total INT UNSIGNED NOT NULL,
PRIMARY KEY(id));

2. INSERT INTO Marks (id, Name, m1, m2, m3, total)


VALUES (1, “Meet”, 50, 30, 20, 20),
(2, “Parth”, 70, 80, 60, 60);
3. DELIMITER //
CREATE TRIGGER marks_trigger
BEFORE INSERT ON Marks
FOR EACH ROW
BEGIN SET
new.total = new.m1 + new.m2 + new.m3;
END //

4. INSERT INTO Marks VALUES (NULL, “Test”, 70, 75, 74,


90);
Lecture:- 2.23

Normalization

• Normalization is a database design technique that


reduces data redundancy and eliminates undesirable
characteristics like Insertion, Update and Deletion
Anomalies.

• Normalization rules divides larger tables into smaller


tables and links them using relationships

• The purpose of Normalization in SQL is to eliminate


redundant (repetitive) data and ensure data is stored
logically.

Forms of Database Normalization

1. 1NF (First Normal Form)


2. 2NF (Second Normal Form)
3. 3NF (Third Normal Form)
4. BCNF (Boyce-Codd Normal Form)
5. 4NF (Fourth Normal Form)
6. 5NF (Fifth Normal Form)
7. 6NF (Sixth Normal Form)
Normalization

• Normalization is a database design technique that


reduces data redundancy and eliminates undesirable
characteristics like Insertion, Update and Deletion
Anomalies.

• Normalization rules divides larger tables into smaller


tables and links them using relationships

• The purpose of Normalization in SQL is to eliminate


redundant (repetitive) data and ensure data is stored
logically.

Forms of Database Normalization

1. 1NF (First Normal Form)


2. 2NF (Second Normal Form)
3. 3NF (Third Normal Form)
4. BCNF (Boyce-Codd Normal Form)
5. 4NF (Fourth Normal Form)
6. 5NF (Fifth Normal Form)
7. 6NF (Sixth Normal Form)
ASSIGNMENT – DBMS and MySQL
ASSIGNMENT – DBMS and MySQL

You might also like