0% found this document useful (0 votes)
50 views141 pages

DBMS Lab

The document outlines the syllabus for the BCSE302P Database Systems Lab course, detailing course objectives, outcomes, and assessment methodologies. It provides an overview of SQL, including its rules, data definition language (DDL), data types, and key specifications. Additionally, it covers SQL commands and clauses for creating databases and tables, filtering data, and using constraints.

Uploaded by

Izhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views141 pages

DBMS Lab

The document outlines the syllabus for the BCSE302P Database Systems Lab course, detailing course objectives, outcomes, and assessment methodologies. It provides an overview of SQL, including its rules, data definition language (DDL), data types, and key specifications. Additionally, it covers SQL commands and clauses for creating databases and tables, filtering data, and using constraints.

Uploaded by

Izhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 141

School of Computer Science and Engineering (SCOPE)

BCSE302P – Database Systems Lab


Syllabus

BCSE302L – DATABASE SYSTEMS 2


Course Objectives

BCSE302L – DATABASE SYSTEMS 3


Course Outcomes

BCSE302L – DATABASE SYSTEMS 4


Assessment Methodologies

BCSE302L – DATABASE SYSTEMS 5


SQL - Structured Query Language
•SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS).
•It is a standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables.
•All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use
SQL as their standard database language.
•SQL allows users to query the database in a number of ways, using English-
like statements.

BCSE302L – DATABASE SYSTEMS 6


SQL - Rules
SQL follows the following rules:
•Structure query language is not case sensitive. Generally, keywords of SQL
are written in uppercase.
•Statements of SQL are dependent on text lines. We can use a single SQL
statement on one or multiple text line.
•Using the SQL statements, you can perform most of the actions in a
database.
•SQL depends on tuple relational calculus and relational algebra.

BCSE302L – DATABASE SYSTEMS 7


SQL process

BCSE302L – DATABASE SYSTEMS 8


Data Definition Language(DDL)
To understand the SQL Data Definition Language
◦ Create
◦ Insert
◦ Delete
◦ Drop
◦ Truncate
◦ Alter

BCSE302L – DATABASE SYSTEMS 9


Creating a Database
To initialize a new database:
Syntax:
CREATE DATABASE database_name

There are numerous arguments that go along with this


command but are database specific
Only some databases require database to be created and
space to be allocated prior to creation of tables.
Some databases provide graphical user interfaces to create
databases and allocate space.
◦ Access only allows database to be created using User Interface

BCSE302L – DATABASE SYSTEMS 10


Creating a Table
Syntax
CREATE TABLE table_name
(Column_name datatype[(size)],
Column_name datatype[(size)],
)

Example desc books;


CREATE TABLE books
(ISBN char(20),
Title char(50),
AuthorID Integer,
Price float);

Creates a table with four columns

BCSE302L – DATABASE SYSTEMS 11


Example
CREATE TABLE books
(ISBN varchar(20),
Title varchar(50),
AuthorID number,
Price float);
Creates a table with four columns

BCSE302L – DATABASE SYSTEMS 12


desc books;

BCSE302L – DATABASE SYSTEMS 13


Data Types
Following broad categories of data types exist in most databases:
◦ String Data
◦ Numeric Data
◦ Temporal Data
◦ Large Objects

BCSE302L – DATABASE SYSTEMS 14


String Data
Fixed Length:
Occupies the same length of space in memory no matter
how much data is stored in them.
Syntax:
char(n) where n is the length of the String
e.g. name char(50)

If the variable stored for name is ‘Sanjay’ the extra 43 fields


are padded with blanks

BCSE302L – DATABASE SYSTEMS 15


String Data
Variable Length string is specified with maximum length of
characters possible in the string, however, the allocation is
sized to the size of the data stored in memory.
Syntax:
Varchar(n) – n is the maximum length of data possible for the type

There may be a restriction in the maximum length of the


data that you can specify in the declaration which will vary
according to the database.
All character data has to be enclosed in single quotes during
specification.

BCSE302L – DATABASE SYSTEMS 16


Numeric Data Types
Store all the data related to purely numeric data.
Some numeric data may also be stored as a character field e.g. zip
codes
Common Numeric Types:
◦ Decimal Floating point number
◦ Float Floating point number
◦ Integer(size) Integer of specified length
◦ Money A number which contains exactly two digits after the decimal point
◦ Number A standard number field that can hold a floating point data

Note: Different databases name their numeric fields differently and may not
support all numeric types. They may also support additional numeric
types.

BCSE302L – DATABASE SYSTEMS 17


Temporal Data Types
These represent the dates and time:
Three basic types are supported:
◦ Dates
◦ Times
◦ Date-Time Combinations

BCSE302L – DATABASE SYSTEMS 18


Large Data Objects
These are used for storing data objects
like files and images:
There are two types:
◦ Character Large Objects (clobs)
◦ Binary Large Objects (blobs)

BCSE302L – DATABASE SYSTEMS 19


Specifying Keys- Introduction
Unique keyword is used to specify keys.
◦ This ensures that duplicate rows are not created in the database.

Both Primary keys and Candidate Keys can be specified in the database.
Once a set of columns has been declared unique any data entered that duplicates the
data in these columns is rejected.
Specifying a single column as unique:
Example
CREATE TABLE Studios
(studio_id Number,
name char(20),
city varchar(50),
state char(2),
UNIQUE (name))

Here the name column has been declared as a candidate key

BCSE302L – DATABASE SYSTEMS 20


Specifying Keys- Multiple
Columns
Specifying multiple columns as unique:
Example:
CREATE TABLE Studios
(studio_id Number,
name char(20),
city varchar(50),
state char(2),
UNIQUE (name),
UNIQUE(city, state))

Here both name & city/state combination are declared as


candidate keys

BCSE302L – DATABASE SYSTEMS 21


Specifying Keys- Primary Key
Specifying multiple columns as unique:
To specify the Primary Key the Primary Key clause is used

Example:
CREATE TABLE Studios
(studio_id Number,
name char(20),
city varchar(50),
state char(2),
PRIMARY KEY (studio_id),
UNIQUE (name),
UNIQUE(city, state)
)

BCSE302L – DATABASE SYSTEMS 22


Specifying Keys- Single and MultiColumn
Keys
Single column keys can be defined at the column level instead of at the
table level at the end of the field descriptions.
MultiColumn keys still need to be defined separately at the table level

CREATE TABLE Studios


(studio_id Number PRIMARY KEY,
name char(20) UNIQUE,
city varchar(50),
state char(2),
Unique(city, state))

Note: Some databases require the use of Unique Index for specification of
keys.

BCSE302L – DATABASE SYSTEMS 23


Specifying Keys- Foreign Keys
References clause is used to create a relationship between a set of
columns in one table and a candidate key in the table that is being
referenced.

Example:

CREATE TABLE Movies


(movie_title varchar(40),
studio_id Number REFERENCES Studios(studio_id))

Creates a relationship from the Movies table to the Studios table

BCSE302L – DATABASE SYSTEMS 24


Constraints- Disallowing Null
Values
Disallowing Null Values:
◦ Null values entered into a column means that the data in not known.
◦ These can cause problems in Querying the database.
◦ Specifying Primary Key automatically prevents null being entered in columns which
specify the primary key

Not Null clause is used in preventing null values from being entered in a
column.

Example:
CREATE TABLE Studios
( studio_id number PRIMARY KEY,
name char(20) NOT NULL,
city varchar(50) NOT NULL,
state char(2) NOT NULL)

Null clause can be used to explicitly allow null values in a column also

BCSE302L – DATABASE SYSTEMS 25


Constraints- Value Constraints
Value Constraints:
◦ Allows value inserted in the column to be checked condition in the column constraint.
Check clause is used to create a constraint in SQL
Example:
CREATE TABLE Movies
(movie_title varchar(40) PRIMARY KEY,
studio_id Number,
budget Number check (budget > 50000)
)

Table level constraints can also be defined using the Constraint keyword
Example:
CREATE TABLE Movies
(movie_title varchar(40) PRIMARY KEY,
studio_id Number,
budget Number check (budget > 50000),
release_date Date,
CONSTRAINT release_date_constraint Check (release_date between ’01-Jan-1980’ and ’31-dec-1989))
Such constraints can be activated and deactivated as required.

BCSE302L – DATABASE SYSTEMS 26


Constraints- Default Value
Default Value:
◦ A default value can be inserted in any column by using the Default keyword.

Example:
CREATE TABLE Movies (
movie_title varchar(40) NOT NULL,
release_date date DEFAULT sysdate NULL,
genre varchar(20) DEFAULT ‘Comedy’ Check genere In
(‘Comedy’, ‘Horror’, ‘Drama’)
)

Table level constraints can also be defined using the Constraint


keyword
release_date defaults to the current date, however Null value is enabled in the
column which will need to be added explicitly when data is added.
Note: Any valid expression can be used while specifying constraints

BCSE302L – DATABASE SYSTEMS 27


SELECT statement Clause

Filters data
Sorts in an WHERE
ORDER BY with help of
order Clause
Clause conditions

Filters data
GROUP BY Groups the
like WHERE
data with
Clause but used with HAVING
same rows Clause
GROUP BY

BCSE302L – DATABASE SYSTEMS 28


Order by
Used to return the rows in ascending or descending order of the data.
To ensure a specific sort order
ORDER BY allows sorting by one or more columns

SELECT column-names
FROM table-name
ORDER BY column-
names
BCSE302L – DATABASE SYSTEMS 29
Order by
List all suppliers by their company name
in alphabetical order
By default ,it
sorts in
ascending
order

SELECT *
FROM supplier
ORDER BY CompanyName;

BCSE302L – DATABASE SYSTEMS 30


Order by
Get a list of all suppliers in
reverse alphabetical order

SELECT *
FROM supplier
ORDER BY CompanyName DESC ;
DESC denotes descending

BCSE302L – DATABASE SYSTEMS 31


WHERE Clause

SQL WHERE clause filters for rows that meet certain criteria.
It is a way to limit the rows to the ones you're interested in
WHERE is followed by a condition that returns either true or false
Syntax

BCSE302L – DATABASE SYSTEMS 32


WHERE Clause - Examples
List all customers in Sweden

SELECT *
FROM Customer
WHERE Country = 'Sweden’;

BCSE302L – DATABASE SYSTEMS 33


WHERE Clause - Examples

BCSE302L – DATABASE SYSTEMS 34


Operators allowed in The WHERE Clause
conditions
Operators List:
• > Greater than operator
• < Less than operator
• = Equal operator
• >= Greater than or equal
• <= Less than or equal
• <> Not equal.
• IN To specify the set of values
• BETWEEN To specify the range of values
• LIKE To specify the pattern
BCSE302L – DATABASE SYSTEMS 35
WHERE Clause - Examples
Fetch the employee details where employee age is greater than 23 and
salary is greater than 5000
SELECT *
FROM Employees WHERE
EMP_SALARY > 5000 AND EMP_AGE > 23;

BCSE302L – DATABASE SYSTEMS 36


WHERE Clause - Examples
Fetch the employee names, where either employee age is
less than 20 or salary is less than 5000
SELECT EMP_NAME
FROM Employees WHERE
EMP_SALARY < 5000 OR EMP_AGE < 20;

BCSE302L – DATABASE SYSTEMS 37


SQL WHERE BETWEEN
• WHERE BETWEEN returns values that fall within a given range.
• WHERE BETWEEN is a shorthand for >= AND <=.
• BETWEEN operator is inclusive: begin and end values are included.

BCSE302L – DATABASE SYSTEMS 38


SQL WHERE BETWEEN
List all products between $10 and
$20
SELECT ProductName
FROM Product
WHERE UnitPrice BETWEEN 10 AND 20
ORDER BY UnitPrice;

BCSE302L – DATABASE SYSTEMS 39


SQL WHERE BETWEEN
List all products not between $10 and $100
sorted by price

SELECT ProductName
FROM Product
WHERE UnitPrice NOT BETWEEN 10 AND 100
ORDER BY UnitPrice;

BCSE302L – DATABASE SYSTEMS 40


SQL WHERE IN Clause
• WHERE IN returns values that matches values in a list or subquery.
• WHERE IN is shorthand for multiple OR conditions.

BCSE302L – DATABASE SYSTEMS 41


SQL WHERE IN Clause
List all suppliers from the USA, UK, OR Japan

SELECT CompanyName
FROM Supplier
WHERE Country IN ('USA', 'UK',
'Japan’);

BCSE302L – DATABASE SYSTEMS 42


SQL WHERE IN Clause
List all products that are not exactly $10, $20, $30,
$40, or $50

SELECT ProductName
FROM Product
WHERE UnitPrice NOT IN (10,20,30,40,50);

BCSE302L – DATABASE SYSTEMS 43


SQL WHERE LIKE Statement
• Use WHERE LIKE when only a fragment of a text value is known.
• WHERE LIKE determines if a character string matches a pattern.
• WHERE LIKE supports two wildcard match options: % and _.

Value:
• % (percent) matches any string with zero
or more characters.
• _ (underscore) matches any single
character.

BCSE302L – DATABASE SYSTEMS 44


SQL WHERE LIKE Statement

BCSE302L – DATABASE SYSTEMS 45


SQL WHERE LIKE Statement
List all products with names that start
with 'Ca'
SELECT ProductName
FROM Product
WHERE ProductName LIKE ‘Ca%’;

BCSE302L – DATABASE SYSTEMS 46


Set operations
 The SQL Set operation is used to combine the two or more SQL SELECT
statements.
 Types of Set Operation
 Union
 UnionAll
 Intersect
 Minus

BCSE302L – DATABASE SYSTEMS 47


Set operations
1. Union
•The SQL Union operation is used to combine the result
of two or more SQL SELECT queries.
•In the union operation, all the number of datatype and
columns must be same in both the tables on which
UNION operation is being applied.
•The union operation eliminates the duplicate rows from
its resultset.

BCSE302L – DATABASE SYSTEMS 48


Set operations
2. Union All
Union All operation is equal to the Union operation. It returns the set without
removing duplication and sorting the data.

BCSE302L – DATABASE SYSTEMS 49


Set operations
3. Intersect
•It is used to combine two SELECT statements. The Intersect operation returns
the common rows from both the SELECT statements.
•In the Intersect operation, the number of datatype and columns must be the
same.
•It has no duplicates and it arranges the data in ascending order by default.

BCSE302L – DATABASE SYSTEMS 50


Set operations
4. Minus
•It combines the result of two SELECT statements. Minus operator is used to
display the rows which are present in the first query but absent in the second
query.
•It has no duplicates and data arranged in ascending order by default.

BCSE302L – DATABASE SYSTEMS 51


SQL IS NULL Clause
 NULL is a special value that signifies 'no value'.
 Comparing a column to NULL using the = operator is undefined.
 Instead, use WHERE IS NULL or WHERE IS NOT NULL.

BCSE302L – DATABASE SYSTEMS 52


SQL IS NULL Clause
List all suppliers that have no fax
number

SELECT CompanyName
FROM Supplier
WHERE Fax is NULL;

BCSE302L – DATABASE SYSTEMS 53


SQL IS NULL Clause
List all suppliers that do have a fax number

SELECT CompanyName
FROM Supplier
WHERE Fax is NOT NULL;

BCSE302L – DATABASE SYSTEMS 54


SQL
Aggregate
Functions
Aggregate Functions
Allows you to perform a calculation on a set of values to return a single
scalar value
Often use aggregate functions with the GROUP BY and HAVING clauses
of the SELECT statement.
Used to summarize the data
Most used functions are:
Avg
Count
Min
Max
Sum

BCSE302L – DATABASE SYSTEMS 56


Avg
calculates the average of a set of values.

SELECT AVG(column_name
) Syntax
FROM table_name
WHERE condition;

Example

BCSE302L – DATABASE SYSTEMS 57


Sum
calculates the sum of values.

SELECT sum(column_name
) Syntax
FROM table_name
WHERE condition;

Example

BCSE302L – DATABASE SYSTEMS 58


Count
counts rows in a specified table or view.

SELECT count(column_name
) Syntax
FROM table_name
WHERE condition;

Example

BCSE302L – DATABASE SYSTEMS 59


Max
returns the largest value of the selected column.

SELECT max(column_name
) Syntax
FROM table_name
WHERE condition;

Example

BCSE302L – DATABASE SYSTEMS 60


Min
calculates the average of a set of values.

SELECT min(column_name
) Syntax
FROM table_name
WHERE condition;

Example

BCSE302L – DATABASE SYSTEMS 61


BCSE302L – DATABASE SYSTEMS 62
BCSE302L – DATABASE SYSTEMS 63
BCSE302L – DATABASE SYSTEMS 64
BCSE302L – DATABASE SYSTEMS 65
BCSE302L – DATABASE SYSTEMS 66
BCSE302L – DATABASE SYSTEMS 67
BCSE302L – DATABASE SYSTEMS 68
BCSE302L – DATABASE SYSTEMS 69
BCSE302L – DATABASE SYSTEMS 70
BCSE302L – DATABASE SYSTEMS 71
BCSE302L – DATABASE SYSTEMS 72
BCSE302L – DATABASE SYSTEMS 73
BCSE302L – DATABASE SYSTEMS 74
BCSE302L – DATABASE SYSTEMS 75
BCSE302L – DATABASE SYSTEMS 76
BCSE302L – DATABASE SYSTEMS 77
BCSE302L – DATABASE SYSTEMS 78
BCSE302L – DATABASE SYSTEMS 79
BCSE302L – DATABASE SYSTEMS 80
BCSE302L – DATABASE SYSTEMS 81
BCSE302L – DATABASE SYSTEMS 82
BCSE302L – DATABASE SYSTEMS 83
BCSE302L – DATABASE SYSTEMS 84
BCSE302L – DATABASE SYSTEMS 85
BCSE302L – DATABASE SYSTEMS 86
BCSE302L – DATABASE SYSTEMS 87
BCSE302L – DATABASE SYSTEMS 88
BCSE302L – DATABASE SYSTEMS 89
Nested Queries
A Subquery or Inner query or a Nested query is a query within another SQL
query and embedded within the WHERE clause.

A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.

Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

BCSE302L – DATABASE SYSTEMS 90


Nested Queries - Rules
Subqueries must be enclosed within parentheses.

A subquery can have only one column in the SELECT clause, unless
multiple columns are in the main query for the subquery to compare its selected
columns.

An ORDER BY command cannot be used in a subquery, although the main


query can use an ORDER BY. The GROUP BY command can be used to
perform the same function as the ORDER BY in a subquery.

BCSE302L – DATABASE SYSTEMS 91


Nested Queries - Rules
Subqueries that return more than one row can only be used with multiple
value operators such as the IN operator.

The BETWEEN operator cannot be used with a subquery. However, the


BETWEEN operator can be used within the subquery.

BCSE302L – DATABASE SYSTEMS 92


Subqueries with the SELECT
Statement
Syntax:
SELECT column_name [, column_name ]
FROM table_name
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table_name
[WHERE])

BCSE302L – DATABASE SYSTEMS 93


Subqueries with the SELECT Statement
SELECT *
FROM CUSTOMERS
WHERE ID IN
(SELECT ID
FROM CUSTOMERS 4,5,7
WHERE SALARY > 4500) ;

BCSE302L – DATABASE SYSTEMS 94


Subqueries with the UPDATE
Statement
The subquery can be used in conjunction with the UPDATE statement. Either single or

multiple columns in a table can be updated when using a subquery with the UPDATE statement.
Syntax:

UPDATE table SET column_name = new_value

WHERE OPERATOR [ VALUE ]


(SELECT COLUMN_NAME

TABLE_NAME

[ WHERE] )

BCSE302L – DATABASE SYSTEMS 95


Subqueries with the UPDATE Statement
Example:

Assuming, we have CUSTOMERS table The following example


updates SALARY by 0.25 times in the CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27.

Query:

UPDATE CUSTOMERS

SET SALARY = SALARY * 0.25

WHERE ID IN
(SELECT ID
FROM CUSTOMERS
WHERE AGE >= 27 );

BCSE302L – DATABASE SYSTEMS 96


Subqueries with the DELETE
Statement
Syntax:

DELETE FROM TABLE_NAME

WHERE OPERATOR [ VALUE ]

(SELECT COLUMN_NAME

FROM TABLE_NAME

[ WHERE])

BCSE302L – DATABASE SYSTEMS 97


Subqueries with the DELETE Statement
DELETE FROM CUSTOMERS
WHERE ID IN
(SELECT ID FROM CUSTOMERS
WHERE AGE >= 27 );

BCSE302L – DATABASE SYSTEMS 98


SQL - Using Joins
The SQL Joins clause is used to combine records from two or more tables in a database. A
JOIN is a means for combining fields from two tables by using values common to each.
SELECT ID, NAME, AGE,AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

BCSE302L – DATABASE SYSTEMS 99


SQL - Joins
Here, it is noticeable that the join is performed in the WHERE clause.
Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=,
BETWEEN, LIKE, and NOT; they can all be used to join tables.

 However, the most common operator is the equal to symbol.

BCSE302L – DATABASE SYSTEMS 100


SQL – Joins Types
There are different types of joins available in SQL :
INNER JOIN − returns rows when there is a match in both tables.
LEFT JOIN − returns all rows from the left table, even if there are no matches in the right
table.
RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left
table.
FULL JOIN − returns rows when there is a match in one of the tables.
CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or
more joined tables

BCSE302L – DATABASE SYSTEMS 101


Inner Join
The most important and frequently used joins is the INNER JOIN.

The INNER JOIN creates a new result table by combining column values of
two tables (table1 and table2) based upon the join-predicate.

The query compares each row of table1 with each row of table2 to find all pairs
of rows which satisfy the join-predicate.

 When the join-predicate is satisfied, column values for each matched pair of
rows of A and B are combined into a result row.

BCSE302L – DATABASE SYSTEMS 102


Inner Join
Syntax:
SELECT column1, column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;

BCSE302L – DATABASE SYSTEMS 103


Inner Join
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

BCSE302L – DATABASE SYSTEMS 104


SQL - LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no
matches in the right table. This means that if the ON clause matches 0 (zero)
records in the right table; the join will still return a row in the result, but with
NULL in each column from the right table.

This means that a left join returns all the values from the left table, plus
matched values from the right table or NULL in case of no matching join
predicate.

BCSE302L – DATABASE SYSTEMS 105


SQL - LEFT JOIN
Syntax:
SELECT column1, column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;

BCSE302L – DATABASE SYSTEMS 106


SQL - LEFT JOINS
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

BCSE302L – DATABASE SYSTEMS 107


SQL - RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are
no matches in the left table. This means that if the ON clause matches 0 (zero)
records in the left table; the join will still return a row in the result, but with
NULL in each column from the left table.

This means that a right join returns all the values from the right table, plus
matched values from the left table or NULL in case of no matching join
predicate.

BCSE302L – DATABASE SYSTEMS 108


SQL – RIGHT JOIN
Syntax:
SELECT column1, column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;

BCSE302L – DATABASE SYSTEMS 109


SQL – RIGHT JOIN
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

BCSE302L – DATABASE SYSTEMS 110


SQL - FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs
for missing matches on either side.
Syntax
SELECT column1, column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;

BCSE302L – DATABASE SYSTEMS 111


SQL - FULL JOIN
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

BCSE302L – DATABASE SYSTEMS 112


SQL - CARTESIAN or CROSS JOINS
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the
sets of records from two or more joined tables.
Thus, it equates to an inner join where the join-condition always evaluates to
either True or where the join-condition is absent from the statement.
Syntax:
SELECT column1,column2...
FROM table1, table2 , table3

BCSE302L – DATABASE SYSTEMS 113


SQL - CARTESIAN or CROSS
JOINS
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS;

BCSE302L – DATABASE SYSTEMS 114


TRANSACTION CONTROL LANGUAGE(TCL)
Transaction is a logical unit of work. All changes made to the database can be
referred to as a transaction.
Transaction changes can be made permanent to a database only if they are
commited.
1. Commit: It is used to save the transactions in the database.
SYNTAX:
commit;

BCSE302L – DATABASE SYSTEMS 115


TRANSACTION CONTROL LANGUAGE(TCL)
Rollback:It is used to restore the database to that state which was last
committed. Rollback command is used to undo the work done in the current
transaction.
SYNTAX:
rollback;

Savepoint: Savepoints are like markers to divide a very lengthy transaction to


smaller ones
SYNTAX:
savepoint <savepoint_id>;

BCSE302L – DATABASE SYSTEMS 116


Views
Description:
A view is a virtual table based on the result-set of an SQL statement. A
VIEW is created by joining one117or more table. It 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.
Create View:
CREATE VIEW command is used to define a view. This CREATE VIEW would
create a virtual table based on the result set of the SELECT statement.
Syntax:
create view <view_name> as select columns from tables [where conditions];

BCSE302L – DATABASE SYSTEMS


Views
Description of View:
Syntax:
desc <view_name>;
Insert in View:
INSERT command is used to insert a new row into the view.
Syntax:
insert into view_name (column name1,………) values(value1,….);

BCSE302L – DATABASE SYSTEMS 118


Views
Display View:
Syntax:
select * from <view_name>;

Update in View:
Syntax:
update <view_name> set <column_name>=(value(s)) where <condition>;

BCSE302L – DATABASE SYSTEMS 119


Views
Delete in View:
Syntax:
delete from view_name where <column _name> =’value’;
Drop of View:
DROP command is used to drop the view table
Syntax:
drop view <view_name>;

BCSE302L – DATABASE SYSTEMS 120


Views
Create View:

Description of View:

BCSE302L – DATABASE SYSTEMS 121


Views
Insert in View:

Display View:

BCSE302L – DATABASE SYSTEMS 122


Views
Update in View:

Delete in View:

BCSE302L – DATABASE SYSTEMS 123


Views
Drop of View:

BCSE302L – DATABASE SYSTEMS 124


PL/SQL
Pl/SQL stands for "Procedural Language extension of SQL”.

PL/SQL is a block structured language.

The programs of PL/SQL are logical blocks that can contain any number of
nested sub-blocks.

Although PL/SQL is closely integrated with SQL language, yet it adds some
programming constraints that are not available in SQL.

BCSE302L – DATABASE SYSTEMS 125


PL/SQL - Subprograms
 A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design'. A subprogram can
be invoked by another subprogram or program which is called the calling program.

PL/SQL provides two kinds of subprograms −

A. Functions − These subprograms return a single value; mainly used to compute and return a
value.

B. Procedures − These subprograms do not return a value directly; mainly used to perform an
action.

BCSE302L – DATABASE SYSTEMS 126


Procedures – Find min of two numbers

BCSE302L – DATABASE SYSTEMS 127


PL/SQL - Procedures
1.Write a procedure to find maximum of three numbers.

2. Write a procedure to find square of a number.

BCSE302L – DATABASE SYSTEMS 128


Functions
A function is same as a procedure
except that it returns a value.
Therefore, all the discussions of the
previous chapter are true for functions
too.
Creating a Function:
A standalone function is created
using the CREATE FUNCTION statement.
The simplified syntax for the CREATE
OR REPLACE PROCEDURE statement
is as follows.

BCSE302L – DATABASE SYSTEMS 129


Functions
Where,
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN represents the
value that will be passed from outside and OUT represents the parameter that will be used to
return a value outside of the procedure.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
function-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.

BCSE302L – DATABASE SYSTEMS 130


Functions – Calling a function
While creating a function, you give a definition of what the function has to do.
To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called
function.
A called function performs the defined task and when its return statement is
executed or when the last end statement is reached, it returns the program control
back to the main program.
To call a function, you simply need to pass the required parameters along with
the function name and if the function returns a value, then you can store the
returned value.

BCSE302L – DATABASE SYSTEMS 131


Functions – Max of two numbers

BCSE302L – DATABASE SYSTEMS 132


PL/SQL -Functions
1. Maximum of three numbers

BCSE302L – DATABASE SYSTEMS 133


Triggers
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,
Update is executed on a database table. A trigger is triggered automatically when an associated DML
statement is executed.
Syntax for Creating a Trigger:
Create [Or Replace ] Trigger trigger_name
{Before | After | Instead Of }
{Insert [Or] | Update [Or] | Delete}
[Of col_name]
On table_name
[For Each Row]
When (condition)
Begin
--- sql statements
End;

BCSE302L – DATABASE SYSTEMS 134


Triggers
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger
with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The
INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.

BCSE302L – DATABASE SYSTEMS 135


Triggers
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected.
WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.

BCSE302L – DATABASE SYSTEMS 136


Triggers
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

BCSE302L – DATABASE SYSTEMS 137


Triggers
Row Level Trigger:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

BCSE302L – DATABASE SYSTEMS 138


Triggers
INSERT INTO CUSTOMERS INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 ); VALUES (2, 'Priya', 32, 'HP',
8000.00 );

BCSE302L – DATABASE SYSTEMS 139


Triggers

UPDATE customers
SET salary = salary + 500
WHERE id = 2;

BCSE302L – DATABASE SYSTEMS 140


BCSE302L – DATABASE SYSTEMS 141

You might also like