DBMS Unit 3
DBMS Unit 3
DBMS Unit 3
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
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 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:
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:
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;
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:
DESC student;
SHOW TABLES;
SQL - ALTER TABLE
Add/Drop Column
Syntax:
ALTER TABLE tablename (ADD/MODIFY/DROP column_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.
Unique Constraint
Check Constraint
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:
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.
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
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
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
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:
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:
SID FID
101 1
101 2
102 3
103 4
104 1
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