Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DBMS Unit 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 106

DBMS: Database Management System

For B.Tech (CSE) II Year I Semester

Lecture by

K Chandrasena Chary
Associate Professor & TPO
Department of CSE,
Sree Chaitanya Institute of
Technological Sciences,
Karimnagar, Telangana

Mobile:9885744643
Mail: chandu518@gmail.com
Syllabus
Syllabus
UNIT – III Course Overview:
 INTRODUCTION TO SQL
 DDL , DML, DCL & TCL Statements
 Nested Queries
 Triggers

 SCHEMA REFINEMENT
 Functional Dependencies
 Normalization Concept
 1NF, 2NF,3NF,BCNF,4NF,5NF
Query Language - Query languages are used to read, update and store data in a
database. There are several such languages that can be used for this purpose; one of
them is SQL (Structured Query Language).
Types of Query Language

Types of DBMS languages:


INTRODUCTION TO SQL
 SQL is used to make a request to retrieve data from a Database.

 The DBMS processes the SQL request, retrieves the requested data from the Database,
and returns it.

 This process of requesting data from a Database and receiving back the results is
called a Database Query and hence the name Structured Query Language.

 SQL is a language that all commercial RDBMS implementations understand.

 SQL is a non-procedural language


 We would be discussing SQL with respect to Oracle & Mysql syntax
Structured Query Language (SQL)

SQL Request

DBMS
Data Database

01000101
11001010
01001011
Computer System
Structured Query Language (SQL)
1979 Oracle Corporation introduces the first commercial RDBMS
1982 ANSI (American National Standards Institute) forms SQL Standards
Committee
1983 IBM (International Business Machine) announces DB2 (a Database)
1986 ANSI (American National Standards Institute) SQL1 standard is approved
1987 ISO (International Organization for Standardization) SQL1 standard is
approved
1992 ANSI (American National Standards Institute) SQL2 standard is approved
2000 Microsoft Corporation introduces SQL Server 2000, aimed at enterprise
applications
2004 SQL: 2003 standard is published
Structured Query Language (SQL)

TCL

DDL
DML DCL
Data Definition Language (DDL)
DDL is used for specifying the database schema. It is used for creating tables, schema,
indexes, constraints etc. in database. The following are the operations that we can
perform on database using DDL:

To create the database instance – CREATE


To alter the structure of database – ALTER
To drop database instances – DROP
To delete tables in a database instance – TRUNCATE
To rename database instances – RENAME
To drop objects from database such as tables – DROP
To Comment on the data dictionary – Comment
Data Manipulation Language (DML)
DML is used for accessing and manipulating data in a database. The following
operations on database comes under DML:

To read records from table(s) – SELECT


To insert record(s) into the table(s) – INSERT
Update the data in table(s) – UPDATE
Delete all the records from the table – DELETE
Data Control language (DCL)
DCL is used for granting and revoking user access on a database –
To grant access to user – GRANT
To revoke access from user – REVOKE

Transaction Control Language(TCL)


The changes in the database that we made using DML commands are either
performed or roll backed using TCL.

To persist the changes made by DML commands in database – COMMIT


To rollback the changes made to the database – ROLLBACK
Data types
• Number
• Char
• Varchar2
• Long
• Date
SQL supports various data types

Integers & Decimal numbers--- NUMBER, INTEGER .


Number is an oracle data type. Integer is an ANSI data type. Integer is equivalent of
NUMBER(38). The syntax for NUMBER is NUMBER(P,S) p is the precision and s is
the scale. P can range from 1 to 38 and s from -84 to 127

Floating point numbers---- FLOAT


Data types
Fixed length character strings---- CHAR [<size>]
The CHAR data type is fixed length, with the maximum size of the column specified in
parentheses. Specifying the size is optional, and the default size is 1 byte. The maximum
allowed size in a CHAR data type column is 2000 bytes.

Variable length character strings --- VARCHAR2(<size>)


A maximum size for the column should be defined. Unlike CHAR columns,
VARCHAR2 columns are not blank-padded with trailing spaces if the column value is
shorter than its maximum specified length. The range is values allowed for size is from 1
to 4000 bytes.
Data types
Dates-----DATE
The DATE data type stores date and time information. You can store the dates from
January 1, 4712 BC to December 31, 9999 AD.

LONG---- LONG columns can store up to 2GB of data. There can be only one LONG
column in the table definition.

NULL
• Missing/unknown/inapplicable data represented as a NULL value
• NULL is not a data value. It is just an indicator that the value is unknown
Operators
Arithmetic operators: +, -, *, /
Logical operators: AND, OR, NOT
Relational operators: =, <=, >=, < >, < , >

The Arithmetic operators are used to calculate something like given in the example
below:
Select * from employee where sal * 1.1 > 1000 ;
The logical operators are used to combine conditions like:
Select * from employee where (sal > 1000 AND age > 25);
The above two examples also illustrate the use of relational operators.
SQL-Data Definition Language
DDL Commands are
• CREATE
• ALTER
• DROP
• TRUNCATE
SQL - CREATE DATABASE
Syntax:

CREATE DATABASE databasename;

The CREATE DATABASE statement is used to create a new SQL database. i.e it creates the instance
Of the database schema in Database.
Example:
CREATE DATABASE college;
Once a database is created,
we can check it in the list of databases
with the following SQL command:
SHOW DATABASES
SQL – USE DATABASE
Syntax:

USE databasename

USE databasename. The USE statement tells MySQL to use the named database as the default
(current) database for subsequent statements. This statement requires some privilege for
the database or some object within it.
Example:
USE college;
SQL – DROP & BACKUP DATABASE
DROP DATABASE Statement - Statement is used to drop an existing SQL
database.
Syntax:
DROP DATABASE databasename;
Example:
DROP DATABASE college;

BACKUP DATABASE Statement - Statement is used in SQL Server to create a


full back up of an existing SQL database.
Syntax:
BACKUP DATABASE databasename TO DISK = 'filepath';
SQL - CREATE TABLE
Syntax:

CREATE TABLE tablename


(
column_name data_ type
constraints, …
);
Used to create a table by defining its structure, the data type and name of the various columns, the
relationships with columns of other tables etc. Table names are used to identify each table and can be
30 characters long. The only special characters allowed in the table name are the dollar sign($), the
underscore (_), and the pound sign (#).

Use DESCRIBE or DESC (SQL *Plus) command to list all of the columns in the table, along with their
data type, size, nullity, and order.
The syntax is DESCRIBE <table name>
SQL - CREATE TABLE
Example:

CREATE TABLE student(sno int(5), sname varchar(20),


branch varchar(10));

DESC student;

SHOW TABLES;
SQL - ALTER TABLE
Add/Drop Column
Syntax:
ALTER TABLE tablename (ADD/MODIFY/DROP column_name)

ALTER TABLE student add(mobile numeric(10));

ALTER TABLE student modify sno numeric(5);

ALTER TABLE student drop mobile;


SQL - DROP TABLE
DROP TABLE - The DROP TABLE statement is used to drop an existing table in a
database.
 Deletes table structure
Cannot be recovered
 Use with caution
Syntax
DROP TABLE table_name;
Ex:
DROP TABLE student;
SQL - TRUNCATE TABLE
 TRUNCATE TABLE - Statement is used to delete the data inside a table,
but not the table itself.
Syntax
 TRUNCATE TABLE table_name;

Example
TRUNCATE TABLE student;
SQL Create Constraints
• Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER
TABLE statement.

• Constraints can be Column level or Table level. Column level constraints


apply to a column, and Table level constraints apply to the whole table.
Syntax
CREATE TABLE table_name (column1 datatype constraint, column2
datatype constraint, column3 datatype constraint, .... );
Types Of Constraints
Primary Key Constraint

Foreign Key Constraint

Unique Constraint

Check Constraint

Not Null Constraint


SQL NOT NULL Constraints
By default, a column can hold NULL values. The NOT
NULL constraint enforces a column to NOT accept NULL
values.
Example:
CREATE TABLE student1(sno numeric(5) NOT NULL, sname varchar(20),
branch varchar(10) );
INSERT INTO student1 VALUES(NULL,'chary',NULL); // Error
SQL UNIQUE Constraints
The UNIQUE constraint ensures that all values in a column are different. Both
the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns. A PRIMARY KEY constraint automatically has
a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but
only one PRIMARY KEY constraint per table.
Example:
CREATE TABLE student1(sno numeric(5) UNIQUE, sname varchar(20),
branch varchar(10) NOT NULL);
INSERT INTO student1 VALUES(1,'chary','CSE');
INSERT INTO student1 VALUES(1,'chary','CSE');//Error
SQL PRIMARY KEY Constraints
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; and in the table, this primary key can consist of single or multiple
columns (fields)

Example:
CREATE TABLE student1(sno numeric(5) PRIMARY KEY, sname
varchar(20), branch varchar(10));
INSERT INTO student1 VALUES(1,'chary','CSE');
INSERT INTO student1 VALUES(1,'chary','CSE');//Error
SQL CHECK Constraints
The CHECK constraint is used to limit the value range that can be placed in a
column. If you define a CHECK constraint on a column it will allow only
certain values for this column.

Example:
CREATE TABLE student1(sno numeric(5) PRIMARY KEY, sname
varchar(20), branch varchar(10), CHECK (SNO>100));
INSERT INTO student1 VALUES(100,'chary','CSE');
INSERT INTO student1 VALUES(1,'chary','CSE');//Error
SQL DEFAULT Constraints
The DEFAULT constraint is used to set a default value for a column. The
default value will be added to all new records, if no other value is specified
Example:
CREATE TABLE student1(sno numeric(5), sname varchar(20), branch
varchar(10) DEFAULT 'CSE');
INSERT INTO student1(SNO,SNAME)VALUES(112,'chary');
INSERT INTO student1(SNO,SNAME)VALUES(100,'chary');
O/P: 112charyCSE
100charyCSE
SQL FOREIGN KEY Constraints
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
Example:
CREATE TABLE DEPT(deptid numeric(4) primary key, dname varchar(10));
CREATE TABLE EMP1(eid numeric(4) primary key, ename varchar(10), deptid
numeric(4), foreign key(deptid) references DEPT(deptid));
INSERT INTO DEPT values(10,'sales');
INSERT INTO DEPT values(20,’admin');
INSERT INTO EMP1 values(1,'a‘,10);
INSERT INTO EMP1 values(2,'a‘,30);//Error
DELETE from DEPT where deptid=10;//Error
SQL-Data Manipulation Language
DML Commands are
• INSERT
• SELECT
• UPDATE
• DELETE
SQL - INSERT INTO
The INSERT INTO statement is used to insert new records in a table
Syntax
It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:


INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, ...);
Example:
INSERT INTO student1(sno,sname) values(2,'sena');
2. If you are adding values for all the columns of the table.(Must follow order of the columns
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example:
INSERT INTO student1 values(1,'sena','cse');
SQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ... FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from.
If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Example
SELECT CustomerName, City FROM Customers
SELECT * FROM Customers;
SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different)
values. Inside a table, a column often contains many duplicate values; and
sometimes you only want to list the different (distinct) values.
Syntax
SELECT DISTINCT column1, column2, ... FROM table_name;
Example:
SELECT DISTINCT sname FROM student1;
SQL WHERE Clause
The WHERE clause is used to filter records. It is used to extract only those
records that fulfill a specified condition.
WHERE Syntax
SELECT column1, column2, ... FROM table_name WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also
used in UPDATE, DELETE, etc.!
Example:
SELECT * FROM student1 WHERE branch='cse';
SQL AND, OR and NOT Operators
The SQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
AND Syntax
SELECT column1, column2, ... FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ... FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, …FROM table_name WHERE NOT condition;
SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ... FROM table_name ORDER BY column1,
column2, ... ASC|DESC;
Example:
SELECT * FROM student1 ORDER BY sname;
SELECT * FROM student1 ORDER BY sname DESC;
SELECT * FROM student1 ORDER BY sname, branch;
SELECT * FROM student1 ORDER BY sname ASC, branch DESC;
SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name SET column1 = value1, column2 = value2, …WHERE condition;

Example
UPDATE student SET branch = ’cse', WHERE sno = 1;

Note: While using UPDATE command, don’t forget to use WHERE condition. If we
omit, all the records will get updated.
SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;

Example
DELETE FROM student WHERE sno = 1;
Note: While using DELETE command, don’t forget to use WHERE condition. If we
omit, all the records will get deleted.
Delete All Records
DELETE FROM table_name;
Difference Between Delete and Truncate

DELETE TRUNCATE
Data can be recovered Data cannot be recovered.

DML statement DDL statement

DELETE does not release the memory TRUNCATE releases the memory
occupied by the records of the table occupied by the records of the table
SQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name) FROM table_name WHERE condition;
MAX() Syntax
SELECT MAX(column_name) FROM table_name WHERE condition;
Example:
SELECT MIN(sal) FROM emp
SELECT MAX(sal) FROM emp
SQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified
criterion.
COUNT() Syntax
SELECT COUNT(column_name)FROM table_name WHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name) FROM table_name WHERE condition;
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name) FROM table_name WHERE condition;
SQL IN Operator
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s) FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Example:
SELECT * FROM student1 WHERE branch IN (‘cse', ’ece’)
SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s) FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example
SELECT * FROM emp WHERE deptid BETWEEN 10 AND 50;
SQL 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.
Alias Column Syntax
SELECT column_name AS alias_name FROM table_name;
Example
SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers;
Alias Table Syntax
SELECT column_name(s) FROM table_name AS alias_name;
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName FROM Customers AS c, rders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;
SQL Joins
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Different Types of SQL JOINs
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from
the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records
from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both tables.
INNER JOIN Syntax
SELECT column_name(s) FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT Orders.OrderID, Customers.CustomerName FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
SQL LEFT OUTER JOIN Keyword
The LEFT OUTER JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the right side,
if there is no match.
LEFT JOIN Syntax
SELECT column_name(s) FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table (table1). The result is 0 records from the left side, if
there is no match.
RIGHT JOIN Syntax
SELECT column_name(s) FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders RIGHT JOIN Employees ON Orders.EmployeeID =
Employees.EmployeeID ORDER BY Orders.OrderID;
SQL FULL OUTER Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Example
SELECT Customers.CustomerName, Orders.OrderID FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL UNION Operator
The UNION operator is used to combine the result-set of two or
more SELECT statements.
Every SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;
UNION ALL Syntax
The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows,
like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.
GROUP BY Syntax
SELECT column_name(s) FROM table_name WHERE condition
GROUP BY column_name(s) ORDER BY column_name(s);
Example
SELECT COUNT(CustomerID), Country FROM Customers
GROUP BY Country;
SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword cannot
be used with aggregate functions.
HAVING Syntax
SELECT column_name(s) FROM table_name WHERE condition
GROUP BY column_name(s)
HAVING condition ORDER BY column_name(s);
Example
SELECT COUNT(CustomerID), Country FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
Summary of basic DDL and DML
Create , Alter and Drop are the DDL commands

Update, Insert into, Delete from, are the basic DML commands
that add or remove data from tables

Selectstatement in its various flavours is used to retrieve


information from the table

Aggregate functions work on all the rows of the table taken as


a group (based on some condition optionally)
Nested Queries or Sub Queries
If a SQL statement contains another SQL statement then the SQL
statement which is inside another SQL statement is called Subquery. It
is also known as Nested query. The SQL Statement which contains the
other SQL statement is called Parent Statement.
Nested Subquery
If a Subquery contains another subquery, then the subquery inside
another subquery is called nested subquery.
Correlated Query –
In Correlated Query, Outer query executes first and for every Outer
query row Inner query is executed. Hence, Inner query uses values from
Outer query.
Subquery
When a query is included inside another query, the Outer query is known as Main Query,
and Inner query is known as Subquery.
Nested Query:
In Nested Query, Inner query runs first, and only once. Outer query is executed with
result from Inner query. Hence, Inner query is used in execution of Outer query.
A sub query is a select query that is contained inside another query. The inner select
query is usually used to determine the results of the outer select query.
Important Rules for Sub Queries:
• We can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause,
FROM clause.
• Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with
expression operator.
• It could be equality operator or comparison operator such as =, >, =, <= and Like operator.
• The subquery generally executes first, and its output is used to complete the query condition
for the main or outer query.
• Subquery must be enclosed in parentheses.
• Subqueries are on the right side of the comparison operator.
Syntax:
SELECT column_name FROM table_name WHERE column_name expression operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );
SQL EXISTS Operator

The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s) FROM table_name WHERE
EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example
SELECT SupplierName FROM Suppliers WHERE
EXISTS
(SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
SQL ANY and ALL Operators
The ANY and ALL operators allow you to perform a comparison between a single column
value and a range of other values.
The ANY operator:
• Returns a boolean value as a result
• Returns TRUE if ANY of the subquery values meet the condition
ANY means that the condition will be true if the operation is true for any of the values in
the range.
ANY Syntax
SELECT column_name(s) FROM table_name WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
SQL ANY and ALL Operators
The ALL operator:
returns a boolean value as a result
returns TRUE if ALL of the subquery values meet the condition
is used with SELECT, WHERE and HAVING statements
ALL means that the condition will be true only if the operation is true for all values in the
range.
ALL Syntax With SELECT
SELECT ALL column_name(s) FROM table_name WHERE condition;
ALL Syntax With WHERE or HAVING
SELECT column_name(s) FROM table_name WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
SQL-Creating new user in Database
Syntax:
CREATE USER ‘uername' IDENTIFIED BY ‘password';
Example:
CREATE USER 'sena' IDENTIFIED BY 'sena';
SQL-Data Control Language
DCL Commands are
• GRANT-gives user’s access privileges to the database.
• REVOKE-withdraw user’s access privileges given by using the

GRANT command.
How To Grant Different User Permissions
Here is a short list of other common possible permissions that users can enjoy.
ALL PRIVILEGES- allow a MySQL user full access to a designated database (or if no database
is selected, global access across the system)
CREATE- allows them to create new tables or databases
DROP- allows them to them to delete tables or databases
DELETE- allows them to delete rows from tables
INSERT- allows them to insert rows into tables
SELECT- allows them to use the SELECT command to read through databases
UPDATE- allow them to update table rows
GRANT OPTION- allows them to grant or remove other users’ privileges
To provide a specific user with a permission, you can use this framework:
GRANT type_of_permission ON database_name.table_name TO 'username'@'localhost';
GRANT select ON mysql.temp TO 'sena';
GRANT type_of_permission ON database_name.table_name TO 'username'@'localhost';
If you want to give them access to any database or to any table, make sure to put an asterisk
(*) in the place of the database name or table name.
GRANT type_of_permission ON *.* TO 'username'@'localhost';
Each time you update or change a permission be sure to use the Flush Privileges command.
FLUSH PRIVILEGES;
If you need to revoke a permission, the structure is almost identical to granting it:
REVOKE type_of_permission ON database_name.table_name FROM
'username'@'localhost';
Note that when revoking permissions, the syntax requires that you use FROM, instead
of TO as we used when granting permissions.
You can review a user’s current permissions by running the following:
SHOW GRANTS FOR 'username'@'localhost';
Just as you can delete databases with DROP, you can use DROP to delete a user altogether:
SQL-Transaction Control Language
TCL Commands are
COMMIT– Commits a Transaction.
ROLLBACK - Rollbacks a transaction in case of any error occurs.
SAVEPOINT–sets a save point within a transaction.
SET TRANSACTION–specify characteristics for the transaction.
SQL Views
• CREATE VIEW Statement

• UPDATE VIEW Statement

• DROP VIEW Statement


SQL CREATE View
CREATE VIEW Statement
In SQL, 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. You can add SQL statements and functions to a view
and present the data as if the data were coming from one single table. 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;
Note: A view always shows up-to-date data! The database engine recreates the view, every
time a user queries it.
CREATE VIEW emp1 AS SELECT * FROM emp WHERE sal>5000;
CREATE VIEW emp6 AS SELECT deptid from emp UNION SELECT deptid from DEPT;
SQL Updating View
A view can be updated with the CREATE OR REPLACE VIEW statement.
CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ...
FROM table_name WHERE condition;

Example:
CREATE OR REPLACE VIEW emp1 AS SELECT eno,ename FROM emp WHERE
sal>5000;
SQL Drop View
A view is deleted with the DROP VIEW statement.
DROP VIEW Syntax
DROP VIEW view_name;
Example:
DROP VIEW EMP1;
What is Functional Dependency?
Functional Dependency (FD) is a constraint that determines the relation of one
attribute to another attribute in a Database Management System (DBMS).
• Functional Dependency helps to maintain the quality of data in the database.
• It plays a important role to find the difference between good and bad database
design.
• A functional dependency is denoted by an arrow " →".
• The functional dependency of X on Y is represented by X → Y.
Syntax:
Functional Dependency on any given table can be explained as,
X→Y
Here, the left side of the arrow is identified as a Determinant(X), while the right side of
the arrow is identified as a Dependent(Y).
Example Database - Employee
Employee number Employee Name Salary City
1 Rajesh 50000 Karimnagar
2 Raju 38000 Warangal
3 Raju 25000 Karimnagar
4 Rajesh 32000 Warangal
5 Krishna 25000 Hyderabad

In this example, if we know the value of Employee number, we can obtain


Employee Name, city, salary, etc. By this, we can say that the city, Employee Name,
and salary are functionally depended on Employee number
Functional Dependencies
A functional dependency is a relationship between two attributes. Typically, between
the PK and other non-key attributes within the table. For any relation R, attribute Y is
functionally dependent on attribute X (usually the PK), if for every valid instance of X,
that value of X uniquely determines the value of Y.
Definition: Let R be the relational schema and X, Y be the set of attributes over R.
T1, T2 be any tuples of R.
X→ Y exists in relation R only
If T1.X=T2.X
then
T1.Y=T2.Y
If the Condition is true, then the dependency will exits. If the condition fails, then the
dependency is not there.
Types of Functional dependencies in DBMS:
Trivial functional dependency
Non-Trivial functional dependency
Multivalued functional dependency
Transitive functional dependency
1. Trivial Functional Dependency
In Trivial Functional Dependency, a dependent is always a subset of the determinant.
i.e. If X → Y and Y is the subset of X, then it is called trivial functional dependency
For example,
Here, {roll_no, name} → name is a trivial functional dependency, since the
dependent name is a subset of determinant set {roll_no, name}

Similarly, roll_no → roll_no is also an example of trivial functional dependency.


2. Non-trivial Functional Dependency
In Non-trivial functional dependency, the dependent is strictly not a subset of the
determinant.
i.e. If X → Y and Y is not a subset of X, then it is called Non-trivial functional
dependency.
For example
Here, roll_no → name is a non-trivial functional dependency, since the
dependent name is not a subset of determinant roll_no
Similarly, {roll_no, name} → age is also a non-trivial functional dependency,
since age is not a subset of {roll_no, name}
3. Multivalued Functional Dependency
In Multivalued functional dependency, entities of the dependent set are not
dependent on each other.
i.e. If a → {b, c} and there exists no functional dependency between b and c, then it is
called a Multivalued functional dependency.
For example
Here, roll_no → {name, age} is a Multivalued functional dependency, since the
dependents name & age are not dependent
on each other
(i.e. name → age or age → name doesn’t exist !)
4. Transitive Functional Dependency
In transitive functional dependency, dependent is indirectly dependent on determinant.
i.e. If a → b & b → c, then according to axiom of transitivity, a → c. This is
a transitive functional dependency
For example
Here, enrol_no → dept and dept → building_no,
Hence, according to the axiom of transitivity, enrol_no → building_no is a valid
functional dependency. This is an indirect functional dependency, hence called
Transitive functional dependency.
5. Single Valued Functional Dependency
The database is a collection of related information in which one information depends
on another information. The information is either single-valued or multi-valued. For
example, the name of the person or his / her date of birth is single-valued facts.
However, the qualification of a person is a Multivalued fact.
A simple example of single value functional dependency is when A is the primary key
of an entity (e.g. SID), and B is some single-valued attribute of the entity (e.g. SName)
Then A->B always holds FD.
6. Fully Functional Dependency
In a relation R, an attribute Q is said to be fully functional dependent on attribute P, if
it is functionally dependent on P and not functionally dependent on any proper subset
of P.
If AD->C, is a functionally dependency, then we cannot remove A or D, i.e C is fully
functionally dependent on AD. If we remove A or D, then it is not fully functionally
dependency.
Example: {ENO, ENAME}->SAL
7. Partial Functional Dependency
A Functional Dependency in which one or more non-key attributes are functionally
depending on the part of the primary key is called partial functional dependency.
If, AD->C then, A->C, D->C
Example: {ENO, DEPTID}->DNAME, ENO->DNAME, DEPTID->DNAME
Q. For the below Relation R(A,B,C) identify all the Functional & Non-Functional
Dependency between attributes and also find the trivial and non-trivial dependencies.
The dependencies are
A->B
A->C
A->BC
B->A
B->C
B->AC
C->A
C->B
C->AB
AB->C
AC->B
BC->A
Normalization
Normalization is a process of organizing the data in Database to
avoid Data Redundancy. Redundancy in relation may cause Insertion
Anomaly, Update Anomaly & Deletion Anomaly.
Normalization is a systematic approach of decomposing tables to
eliminate data redundancy(repetition) and undesirable characteristics
like Insertion, Update and Deletion Anomalies.
Normalization is used for mainly two purposes,
• Eliminating redundant(useless) data.
• Ensuring data dependencies make sense i.e data is logically stored.
Problems Without Normalization
If a table is not properly normalized and have data redundancy then it is difficult to
handle and update the database, without facing data loss. Insertion, Update and
Deletion Anomalies are very frequent if database is not Normalized.
ENO ENAME DEPTID DNAME DEPT_HOD
101 Rajesh 10 Admin Mr. Vijary
102 Raju 20 Accounts Mr. Santhosh
103 Raju 30 Store Mr. Akash
104 Rajesh 20 Accounts Mr. Santhosh
105 Krishna 30 Store Mr. Akash

Employee Address is repeated for employee who is working for two departments – Data Redundancy
Insertion Anomaly
Updation Anomaly
Deletion Anomaly
ENO ENAME DEPTID DNAME DEPT_HOD
101 Rajesh 10 Admin Mr. Vijary
102 Raju 20 Accounts Mr. Santhosh
103 Raju 30 Store Mr. Akash
104 Rajesh 20 Accounts Mr. Santhosh
105 Krishna 30 Store Mr. Akash
Types of Normal Forms
• First Normal Form
• Second Normal Form
• Third Normal Form
• BCNF
• Fourth Normal Form
1. First Normal Form (1NF)
For a table to be in the First Normal Form, it should follow the following 4 rules:
1. It should only have single(atomic) valued attributes/columns.
2. Values stored in a column should be of the same domain
3. All the columns in a table should have unique names.
4. And the order in which data is stored, does not matter.
1. First Normal Form (1NF)
For a table to be in the First Normal Form, it should follow the following 4 rules:
1. It should only have single(atomic) valued attributes/columns.
2. Values stored in a column should be of the same domain
3. All the columns in a table should have unique names.
4. And the order in which data is stored, does not matter.
Example- Before Normalization Example- After 1st Normalization
HTNO NAME SUBJECT HTNO NAME SUBJECT
501 Rajesh OS, CN
501 Rajesh OS, CN 501 Rajesh CN
502 Ramesh Java
502 Ramesh Java
503 Srinivas C
503 Srinivas C, C++ 503 Srinivas C++
Example 2:
2. Second Normal Form (2NF)
For a table to be in the Second Normal Form, it must satisfy two conditions:

1. For a table to be in the Second Normal form, it should be in the First


Normal form and it should not have Partial Dependency.
2. Partial Dependency exists, when for a composite primary key, any
attribute in the table depends only on a part of the primary key and
not on the complete primary key.
3. To remove Partial dependency, we can divide the table, remove the
attribute which is causing partial dependency, and move it to some
other table where it fits in well.
EMP TABLE
ENO ENAME DEPTID DNAME DEPT_HOD

101 Rajesh 10 Admin Mr. Vijay

102 Raju 20 Accounts Mr. Santhosh

103 Raju 30 Store Mr. Akash

104 Rajesh 20 Accounts Mr. Santhosh

105 Krishna 30 Store Mr. Akash

EMP TABLE DEPT TABLE


ENO ENAME DEPTID DEPTID DNAME DEPT_HOD

101 Rajesh 10 10 Admin Mr. Vijay

102 Raju 20 20 Accounts Mr. Santhosh

103 Raju 30 30 Store Mr. Akash

104 Rajesh 20

105 Krishna 30
3. Third Normal Form (3NF)
For a table to be in the Third Normal Form, it must satisfy two conditions:

For a table to be in the Third Normal form, it should be in the Second


Normal form and it should not have Transitive Dependency.
1. It is in 2 NF
2. No Transitive Dependency for Non-Prime Attribute i.e. (NPA->NPA)

Advantage of removing Transitive Dependency


3. Amount of data duplication is reduced.
4. Data integrity achieved.
DEPT TABLE

DEPTID DNAME DEPT_HOD DEPT_LOC

10 Admin Mr. Vijay 1st Floor

20 Accounts Mr. Santhosh 2nd Floor

30 Store Mr. Akash 3rd Floor


4. Boyce-Codd Normal Form (BCNF)
For a table to be in the BCNF, it must satisfy two conditions:
For a table to satisfy the Boyce-Codd Normal Form, it should satisfy the
following two conditions:
1. It should be in the Third Normal Form.
2. And, for any dependency A → B, A should be a super key.

It means, that for a dependency A → B, A cannot be a non-prime


attribute, if B is a prime attribute.
SID SUBJECT FACULTY

101 Java Mr.Ajay

101 C++ Mr.Vinary

102 Java Mr.Jain

103 C# Mr. Krishna

104 Java Mr.Ajay

SID FID
101 1
101 2
102 3
103 4
104 1

FID FACULTY SUBJECT


1 Mr.Ajay Java
2 Mr.Vinary C++
3 Mr.Jain Java
4 Mr. Krishna C#
1 Mr.Ajay Java
4. Fourth Normal Form (4NF)
For a table to be in the 4NF, it must satisfy two conditions:
For a table to satisfy the Fourth Normal Form, it should satisfy the
following two conditions:
1. It should be in the BCNF.
2. And, the table should not have any Multi-valued dependency
What is Multi-valued Dependency?
A table is said to have multi-valued dependency, if the following conditions are true,
For a dependency A → B,
1. if for a single value of A, multiple value of B exists, then the table may have
multi-valued dependency.
2. Also, a table should have at-least 3 columns for it to have a multi-valued
dependency.
3. And, for a relation R(A,B,C), if there is a multi-valued dependency between, A
and B, then B and C should be independent of each other.

If all these conditions are true for any relation(table), it is said to have multi-valued
dependency.
5. Fifth Normal Form (5NF) or PJNF(ProjectJoinNF)
For a table to be in the 5NF, it must satisfy two conditions:
For a table to satisfy the Fifth Normal Form, it should satisfy the following
two conditions:
1. It should be in the 4NF.
2. It should not have Join dependency
Wish You All The Best

Prepared by K. Chandrasena chary, Dept. of CSE, SCIT, KNR.

You might also like