Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

UNIT-2

Relational data Model and Language: Relational Data Model Concepts, Integrity Constraints, Entity Integrity, Referential
Integrity, Keys Constraints, Domain Constraints, Relational Algebra, Relational Calculus, Tuple and Domain Calculus.
Introduction on SQL: Characteristics of SQL, Advantage of SQL. SQl Data Type and Literals. Types of SQL Commands. SQL
Operators and Their Procedure. Tables, Views and Indexes. Queries and Sub Queries. Aggregate Functions. Insert, Update
and Delete Operations, Joins, Unions, Intersection, Minus, Cursors, Triggers, Procedures in SQL/PL SQL

What Are Data Models In DBMS ?

Relational model in DBMS


DBMS

In relational model, the data and relationships are represented by collection of inter-related tables. Each table is a
group of column and rows, where column represents attribute of an entity and rows represents records.

Sample relationship Model: Student table with 3 columns and four records.
Stu_Id Stu_Name Stu_Age
111 Ashish 23
123 Saurav 22
169 Lester 24
234 Lou 26
Course table: Course table

Stu_Id Course_Id Course_Name


111 C01 Science
111 C02 DBMS
169 C22 Java
169 C39 Computer Networks
Here Stu_Id, Stu_Name & Stu_Age are attributes of table Student and Stu_Id, Course_Id & Course_Name are
attributes of table Course. The rows with values are the records (commonly known as tuples).

Relation Data Model Concepts

Relational data model is the primary data model, which is used widely around the world for data storage and
processing. This model is simple and it has all the properties and capabilities required to process data with
storage efficiency.

Concepts
Tables − In relational data model, relations are saved in the format of Tables. This format stores the relation
among entities. A table has rows and columns, where rows represents records and columns represent the
attributes.

Tuple − A single row of a table, which contains a single record for that relation is called a tuple.

Relation instance − A finite set of tuples in the relational database system represents relation instance. Relation
instances do not have duplicate tuples.

Relation schema − A relation schema describes the relation name (table name), attributes, and their names.

Relation key − Each row has one or more attributes, known as relation key, which can identify the row in the
relation (table) uniquely.

Attribute domain − Every attribute has some pre-defined value scope, known as attribute domain.

Constraints
INTEGRITY CONSTRAINTS
• Database integrity refers to the validity and consistency of stored data. Integrity is usually expressed in
terms of constraints, which are consistency rules that the database is not permitted to violate. Constraints
may apply to each attribute or they may apply to relationships between tables.
• Integrity constraints ensure that changes (update deletion, insertion) made to the database by authorized
users do not result in a loss of data consistency. Thus, integrity constraints guard against accidental damage
to the database.
EXAMPLE- A brood group must be ‘A’ or ‘B’ or ‘AB’ or ‘O’ only (can not any other values else).

TYPES OF INTEGRITY CONSTRAINTS


Various types of integrity constraints are-
1. Domain Integrity
2. Entity Integrity Constraint
3. Referential Integrity Constraint
4. Key Constraints

1. Domain Integrity-
Domain integrity means the definition of a valid set of values for an attribute. You define data type, length or
size, is null value allowed , is the value unique or not for an attribute ,the default value, the range (values in
between) and/or specific values for the attribute.
2. Entity Integrity Constraint-
This rule states that in any database relation value of attribute of a primary key can't be null.
EXAMPLE- Consider a relation "STUDENT" Where "Stu_id" is a primary key and it must not contain any null
value whereas other attributes may contain null value e.g "Branch" in the following relation contains one null
value.

Stu_id Name Branch

11255234 Aman CSE

11255369 Kapil EcE

11255324 Ajay ME

11255237 Raman CSE

11255678 Aastha ECE


3.Referential Integrity Constraint-
It states that if a foreign key exists in a relation then either the foreign key value must match a primary key value
of some tuple in its home relation or the foreign key value must be null.
The rules are:

1. You can't delete a record from a primary table if matching records exist in a related table.
2. You can't change a primary key value in the primary table if that record has related records.
3. You can't enter a value in the foreign key field of the related table that doesn't exist in the primary key of
the primary table.
4. However, you can enter a Null value in the foreign key, specifying that the records are unrelated.

EXAMPLE-
Consider 2 relations "stu" and "stu_1" Where "Stu_id " is the primary key in the "stu" relation and foreign key in
the "stu_1" relation.
Relation "stu"

Stu_id Name Branch

11255234 Aman CSE

11255369 Kapil EcE

11255324 Ajay ME

11255237 Raman CSE

11255678 Aastha ECE


Relation "stu_1"
Stu_id Course Duration

11255234 B TECH 4 years

11255369 B TECH 4 years


Stu_id Course Duration

11255324 B TECH 4 years

11255237 B TECH 4 years

11255678 B TECH 4 years


Examples
Rule 1. You can't delete any of the rows in the ”stu” relation that are visible since all the ”stu” are in use in the
“stu_1” relation.
Rule 2. You can't change any of the ”Stu_id” in the “stu” relation since all the “Stu_id” are in use in the ”stu_1”
relation. * Rule 3.* The values that you can enter in the” Stu_id” field in the “stu_1” relation must be in the”
Stu_id” field in the “stu” relation.
Rule 4 You can enter a null value in the "stu_1" relation if the records are unrelated.
4.Key Constraints-
A Key Constraint is a statement that a certain minimal subset of the fields of a relation is a unique identifier for a
tuple. The types of key constraints-

1. Primary key constraints


2. Unique key constraints
3. Foreign Key constraints
4. NOT NULL constraints
5. Check constraints

1. Primary key constraints


Primary key is the term used to identify one or more columns in a table that make a row of data unique. Although
the primary key typically consists of one column in a table, more than one column can comprise the primary key.
For example, either the employee's Social Security number or an assigned employee identification number is the
logical primary key for an employee table. The objective is for every record to have a unique primary key or value
for the employee's identification number. Because there is probably no need to have more than one record for
each employee in an employee table, the employee identification number makes a logical primary key. The
primary key is assigned at table creation.
The following example identifies the EMP_ID column as the PRIMARY KEY for the EMPLOYEES table:

CREATE TABLE EMPLOYEE_TBL


(EMP_ID CHAR(9) NOT NULL PRIMARY KEY,
EMP_NAME VARCHAR (40) NOT NULL,
EMP_ST_ADDR VARCHAR (20) NOT NULL,
EMP_CITY VARCHAR (15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP INTEGER(5) NOT NULL,
EMP_PHONE INTEGER(10) NULL,
EMP_PAGER INTEGER(10) NULL);
2. Unique Constraints
A unique column constraint in a table is similar to a primary key in that the value in that column for every row of
data in the table must have a unique value. Although a primary key constraint is placed on one column, you can
place a unique constraint on another column even though it is not actually for use as the primary key.

CREATE TABLE EMPLOYEE_TBL


(EMP_ID CHAR(9) NOT NULL PRIMARY KEY,
EMP_NAME VARCHAR (40) NOT NULL,
EMP_ST_ADDR VARCHAR (20) NOT NULL,
EMP_CITY VARCHAR (15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP INTEGER(5) NOT NULL,
EMP_PHONE INTEGER(10) NULL UNIQUE,
EMP_PAGER INTEGER(10) NULL)

3. Foreign Key Constraints


A foreign key is a column in a child table that references a primary key in the parent table. A foreign key constraint
is the main mechanism used to enforce referential integrity between tables in a relational database. A column
defined as a foreign key is used to reference a column defined as a primary key in another table.

CREATE TABLE EMPLOYEE_PAY_TBL


(EMP_ID CHAR(9) NOT NULL,
POSITION VARCHAR2(15) NOT NULL,
DATE_HIRE DATE NULL,
PAY_RATE NUMBER(4,2) NOT NULL,
DATE_LAST_RAISE DATE NULL,

4. NOT NULL Constraints


Previous examples use the keywords NULL and NOT NULL listed on the same line as each column and after the
data type. NOT NULL is a constraint that you can place on a table's column. This constraint disallows the entrance
of NULL values into a column; in other words, data is required in a NOT NULL column for each row of data in
the table. NULL is generally the default for a column if NOT NULL is not specified, allowing NULL values in a
column.
5. Check Constraints
Check (CHK) constraints can be utilized to check the validity of data entered into particular table columns. Check
constraints are used to provide back-end database edits, although edits are commonly found in the front-end
application as well. General edits restrict values that can be entered into columns or objects, whether within the
database itself or on a front-end application. The check constraint is a way of providing another protective layer
for the data.

CREATE TABLE EMPLOYEE_TBL


(EMP_ID CHAR(9) NOT NULL,
EMP_NAME VARCHAR2(40) NOT NULL,
EMP_ST_ADDR VARCHAR2(20) NOT NULL,
EMP_CITY VARCHAR2(15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP NUMBER(5) NOT NULL,
EMP_PHONE NUMBER(10) NULL,
EMP_PAGER NUMBER(10) NULL),
PRIMARY KEY (EMP_ID),
CONSTRAINT CHK_EMP_ZIP CHECK ( EMP_ZIP = '46234');

OR
Every relation has some conditions that must hold for it to be a valid relation. These conditions are called
Relational Integrity Constraints. There are three main integrity constraints −

• Key constraints
• Domain constraints
• Referential integrity constraints

Key Constraints

There must be at least one minimal subset of attributes in the relation, which can identify a tuple uniquely. This
minimal subset of attributes is called key for that relation. If there are more than one such minimal subsets,
these are called candidate keys.

Key constraints force that −

• in a relation with a key attribute, no two tuples can have identical values for key attributes.
• a key attribute can not have NULL values.

Key constraints are also referred to as Entity Constraints.

Domain Constraints

Attributes have specific values in real-world scenario. For example, age can only be a positive integer. The
same constraints have been tried to employ on the attributes of a relation. Every attribute is bound to have a
specific range of values. For example, age cannot be less than zero and telephone numbers cannot contain a
digit outside 0-9.

Referential integrity Constraints

Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key attribute of a
relation that can be referred in other relation.

Referential integrity constraint states that if a relation refers to a key attribute of a different or same relation,
then that key element must exist.

Relational Algebra
Relational algebra is a procedural query language, which takes instances of relations as input and yields
instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary.
They accept relations as their input and yield relations as their output. Relational algebra is performed
recursively on a relation and intermediate results are also considered relations.

The fundamental operations of relational algebra are as follows −

• Select
• Project
• Union
• Set different
• Cartesian product
• Rename

We will discuss all these operations in the following sections.

Select Operation (σ)


It selects tuples that satisfy the given predicate from a relation.

Notation − σp(r)

Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use
connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < , >, ≤.

For example −

σsubject = "database"(Books)

Output − Selects tuples from books where subject is 'database'.

σsubject = "database" and price = "450"(Books)

Output − Selects tuples from books where subject is 'database' and 'price' is 450.

σsubject = "database" and price = "450" or year > "2010"(Books)

Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after
2010.

Project Operation (∏)


It projects column(s) that satisfy a given predicate.

Notation − ∏A1, A2, An (r)

Where A1, A2 , An are attribute names of relation r.

Duplicate rows are automatically eliminated, as relation is a set.


For example −

∏subject, author (Books)

Selects and projects columns named as subject and author from the relation Books.

Union Operation (∪)


It performs binary union between two given relations and is defined as −

r ∪ s = { t | t ∈ r or t ∈ s}

Notion − r U s

Where r and s are either database relations or relation result set (temporary relation).

For a union operation to be valid, the following conditions must hold −

• r, and s must have the same number of attributes.


• Attribute domains must be compatible.
• Duplicate tuples are automatically eliminated.

∏ author (Books) ∪ ∏ author (Articles)

Output − Projects the names of the authors who have either written a book or an article or both.

Set Difference (−)


The result of set difference operation is tuples, which are present in one relation but are not in the second
relation.

Notation − r − s

Finds all the tuples that are present in r but not in s.

∏ author (Books) − ∏ author (Articles)

Output − Provides the name of authors who have written books but not articles.

Cartesian Product (Χ)


Combines information of two different relations into one.

Notation − r Χ s

Where r and s are relations and their output will be defined as −

r Χ s = { q t | q ∈ r and t ∈ s}

σauthor = 'tutorialspoint'(Books Χ Articles)


Output − Yields a relation, which shows all the books and articles written by tutorialspoint.

Rename Operation (ρ)


The results of relational algebra are also relations but without any name. The rename operation allows us to
rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ.

Notation − ρ x (E)

Where the result of expression E is saved with name of x.

Additional operations are −

• Set intersection
• Assignment
• Natural join

////////////////////////////////////////////////////////

Relational Calculus
In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it tells what to
do but never explains how to do it.

Relational calculus exists in two forms −

Tuple Relational Calculus (TRC)

Filtering variable ranges over tuples

Notation − {T | Condition}

Returns all tuples T that satisfies a condition.

For example −

{ T.name | Author(T) AND T.article = 'database' }

Output − Returns tuples with 'name' from Author who has written article on 'database'.

TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀).

For example −

{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output − The above query will yield the same result as the previous one.

Domain Relational Calculus (DRC)


In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC,
mentioned above).

Notation −

{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

Where a1, a2 are attributes and P stands for formulae built by inner attributes.

For example −

{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}

Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database.

Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves relational
operators.

The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational
Algebra.

SQL Overview

SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple
relational calculus. SQL comes as a package with all major distributions of RDBMS.

SQL comprises both data definition and data manipulation languages. Using the data definition properties of
SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store
and retrieve data from database.

What are the characteristics of SQL?


(i) SQL enables end user and system persons to deal with a number of database managment systems where it is
available.
(ii) (ii) Applications written in SQL can be easily ported across systems. Such porting could be required when the
underlying DBMS needs to upgraded because of change in transaction volumes or when a system developed
in one environment is to be used on another.
(iii) (iii) SQL as a language is independent of the way it is implented internally. A query returns the same result
regardless of whether optimizing has been done with indexes or not. This is because SQL specifies what is
required and not how it is to be done.
(iv) The language while being simple and easy to learn can cope with complex situations.
(v) The results to be expected are well defined in SQL
Advantages of SQL:

Below given are the pros, advantages of Structured Query Language (SQL):

1) Portable: SQL is run in programs in mainframes, PCs, laptops, servers and even mobile phones. It runs in
local systems, intranet and internet. Databases using SQL can be moved from device to another without any
problems.

2) Used with any DBMS system with any vendor: SQL is used by a all the vendors who develop DBMS.

3) SQL Standard: First standard for SQL was put up in 1986 by ANSI (American National Standards Institute)
and ISO (International Standards Organization). It was later expanded in 1989 and in 1992 and 1999.

4) Used for relational databases: SQL is widely used for relational databases.

5) Easy to learn and understand: SQL mainly consists of English statements and it is very easy to learn and
understand a SQL query.

6) Interactive language: SQL can be used to communicate with the databases and get answers to complex
questions in seconds.

7) Both as programming language and interactive language: SQL can do both the jobs of being a
programming as well as an interactive language at the same time.

8) Complete language for a database: SQL is used to create databases, manage security of a database. It can
also be used for updating, retrieving and sharing data with users.

9) Multiple data views: By use of SQL, different views of structure and content of a database can be provided
for different users.

10) Client/Server language: SQL is used for linking front end computers and back end databases. Thus,
providing client server architecture.

11) Dynamic database language: By the use of SQL database structure can be changed in a dynamic fashion
even when the contents of the database are accessed by users at the same time.
12) Supports object based programming: SQL supports the latest object based programming and is highly
flexible.

13) Supports enterprise applications: SQL is the database language which is used by businesses and
enterprises throughout the globe. For an enterprise application it is a perfect language for a database.

14) Integrates with Java: SQL integrates with Java by using an API known as JDBC (Java Database
Connectivity).

15) Used in internet: SQL is used in three tiered Internet architecture. The architecture includes a client,
application server and a database.

Disadvantages of SQL:

* Difficulty in Interfacing:
Interfacing an SQL database is more complex than adding a few lines of code.

* More Features Implemented in Proprietary way:


Although SQL databases conform to ANSI & ISO standards, some databases go for proprietary
extensions to standard SQL to ensure vendor lock-in.

SQL Data Types


Like all other computer languages, SQL deals with data. So let's first look at how SQL defines data.

Data Type: A group of data that shares some common characteristics and operations.

SQL defines the following data types:

SQL Data Types

SQL data types can be broadly divided into following categories.

1. Numeric data types such as int, tinyint, bigint, float, real etc.
2. Date and Time data types such as Date, Time, Datetime etc.
3. Character and String data types such as char, varchar, text etc.
4. Unicode character string data types, for example nchar, nvarchar, ntext etc.
5. Binary data types such as binary, varbinary etc.
6. Miscellaneous data types – clob, blob, xml, cursor, table etc.
SQL: Literals
This SQL tutorial explains how to use literals (strings, integers, decimals, and datetime values) in SQL with
examples.

Description
In SQL, a literal is the same as a constant. We'll cover several types of literals - string, integer, decimal, and
datetime literals.

String Literals
String literals are always surrounded by single quotes (').
For example:

'TechOnTheNet.com'
'This is a literal'
'XYZ'
'123'

These string literal examples contain of strings enclosed in single quotes.

Integer Literals
Integer literals can be either positive numbers or negative numbers, but do not contain decimals. If you do not
specify a sign, then a positive number is assumed. Here are some examples of valid integer literals:

536
+536
-536

Decimal Literals
Decimal literals can be either positive numbers or negative numbers and contain decimals. If you do not specify
a sign, then a positive number is assumed. Here are some examples of valid decimal literals:

24.7
+24.7
-24.7

Datetime Literals
Datetime literals are character representations of datetime values that are enclosed in single quotes. Here are
some examples of valid datetime literals:

'April 30, 2015'


'2015/04/30'
'2015/04/30 08:34:25'

Types of SQL Commands


DDL

Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:

o CREATE - to create objects in the database


o ALTER - alters the structure of the database
o DROP - delete objects from the database
o TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
o COMMENT - add comments to the data dictionary
o RENAME - rename an object

DML

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

o SELECT - retrieve data from the a database


o INSERT - insert data into a table
o UPDATE - updates existing data within a table
o DELETE - deletes all records from a table, the space for the records remain
o EXPLAIN PLAN - explain access path to data
o LOCK TABLE - control concurrency

DCL

Data Control Language (DCL) statements. Some examples:

o GRANT - gives user's access privileges to database


o REVOKE - withdraw access privileges given with the GRANT command

TCL

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to
be grouped together into logical transactions.

o COMMIT - save work done


o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT

SQL Operators
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform
operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple
conditions in a statement.

• Arithmetic operators
• Comparison operators
• Logical operators
• Operators used to negate conditions
• Bitwise operators

• Unary operators

SQL Arithmetic Operators:


Assume variable a holds 10 and variable b holds 20, then:

Show Examples

Operator Description Example

+ Addition - Adds values on either side of the operator a + b will give 30

Subtraction - Subtracts right hand operand from left


- a - b will give -10
hand operand

Multiplication - Multiplies values on either side of the


* a * b will give 200
operator

Division - Divides left hand operand by right hand


/ b / a will give 2
operand

Modulus - Divides left hand operand by right hand


% b % a will give 0
operand and returns remainder

SQL Comparison Operators:


Assume variable a holds 10 and variable b holds 20, then:

Show Examples

Operator Description Example

Checks if the values of two operands are equal or not,


= (a = b) is not true.
if yes then condition becomes true.

Checks if the values of two operands are equal or not,


!= (a != b) is true.
if values are not equal then condition becomes true.

Checks if the values of two operands are equal or not,


<> (a <> b) is true.
if values are not equal then condition becomes true.

Checks if the value of left operand is greater than the


> value of right operand, if yes then condition becomes (a > b) is not true.
true.

Checks if the value of left operand is less than the


< value of right operand, if yes then condition becomes (a < b) is true.
true.

Checks if the value of left operand is greater than or


>= equal to the value of right operand, if yes then (a >= b) is not true.
condition becomes true.
Checks if the value of left operand is less than or
<= equal to the value of right operand, if yes then (a <= b) is true.
condition becomes true.

Checks if the value of left operand is not less than the


!< value of right operand, if yes then condition becomes (a !< b) is false.
true.

Checks if the value of left operand is not greater than


!> the value of right operand, if yes then condition (a !> b) is true.
becomes true.

SQL Logical Operators:


Here is a list of all the logical operators available in SQL.

Show Examples

Operator Description

ALL The ALL operator is used to compare a value to all values in another value set.

The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
AND
clause.

The ANY operator is used to compare a value to any applicable value in the list according to the
ANY
condition.

The BETWEEN operator is used to search for values that are within a set of values, given the
BETWEEN
minimum value and the maximum value.

The EXISTS operator is used to search for the presence of a row in a specified table that meets
EXISTS
certain criteria.

IN The IN operator is used to compare a value to a list of literal values that have been specified.

LIKE The LIKE operator is used to compare a value to similar values using wildcard operators.

The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT
NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

OR The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.

IS NULL The NULL operator is used to compare a value with a NULL value.

UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
Bitwise Operators

Bitwise operators perform bit manipulations between two expressions of any of the data types of the integer
data type category.

Operator Meaning

& (Bitwise AND) Bitwise AND (two operands).

| (Bitwise OR) Bitwise OR (two operands).

^ (Bitwise Exclusive OR) Bitwise exclusive OR (two operands).

Unary Operators

Unary operators perform an operation on only one expression of any of the data types of the numeric data type
category.

Operator Meaning

+ (Positive) Numeric value is positive.

- (Negative) Numeric value is negative.

~ (Bitwise NOT) Returns the ones complement of the number.

SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is known as relation and row as tuple

Table is the simple form of data storage. A table is also considered as a convenient representation of relations.

Let's see an example of an employee table:

Employee

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000


In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY" are the column names. The
combination of data of multiple columns forms a row e.g. "Ankit", "Lucknow" and 15000 are the data of one row.

SQL TABLE Variable


The SQL Table variable is used to create, modify, rename, copy and delete tables. Table variable was introduced by Microsoft.

It was introduced with SQL server 2000 to be an alternative of temporary tables.

It is a variable where we temporary store records and results. This is same like temp table but in the case of temp table we need to
explicitly drop it.

Table variables are used to store a set of records. So declaration syntax generally looks like CREATE TABLE syntax.

1. create table "tablename"


2. ("column1" "data type",
3. "column2" "data type",
4. ...
5. "columnN" "data type");

SQL Views
A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is
actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one or many tables
which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
• Structure data in a way that users or classes of users find natural or intuitive.
• Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they
need and no more.
• Summarize data from various tables which can be used to generate reports.

Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a single table,
multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL
SELECT query.
SQL indexes
Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put,
an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic, you first refer to the
index, which lists all the topics alphabetically and are then referred to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with
the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the
table and which column or columns to index, and to indicate whether the index is in an ascending or descending
order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries in the
column or combination of columns on which there is an index.

The CREATE INDEX Command


The basic syntax of a CREATE INDEX is as follows.
CREATE INDEX index_name ON table_name;
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as follows.
CREATE INDEX index_name
ON table_name (column_name);
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any
duplicate values to be inserted into the table. The basic syntax is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);

Subquery in SQL?
A subquery is a SQL query nested inside a larger query.

• A subquery may occur in :

o - A SELECT clause
o - A FROM clause

o - A WHERE clause

• The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery.

• A subquery is usually added within the WHERE Clause of another SQL SELECT statement.

• You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row operator,
such as IN, ANY, or ALL.

• A subquery is also called an inner query or inner select, while the statement containing a subquery is also called an
outer query or outer select.

• The inner query executes first before its parent query so that the results of an inner query can be passed to the outer
query.

You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the
following tasks:

• Compare an expression to the result of the query.

• Determine if an expression is included in the results of the query.

• Check whether the query selects any rows.

Syntax :

• The subquery (inner query) executes once before the main query (outer query) executes.

• The main query (outer query) use the subquery result.

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:

• AVG() - Returns the average value


• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum

SQL Queries (Insert, Delete, & Update Operations)


Creating a basic table involves naming the table and defining its columns and each column's data type.

The SQL CREATE TABLE statement is used to create a new table.

Syntax:
Basic syntax of CREATE TABLE statement is as follows:

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to
create a new table. The unique name or identifier for the table follows the CREATE TABLE statement.

Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax
becomes clearer with an example below.

A copy of an existing table can be created using a combination of the CREATE TABLE statement and the
SELECT statement. You can check complete details atCreate Table Using another Table
SQL - INSERT Query
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.

Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]


VALUES (value1, value2, value3,...valueN);

Here, column1, column2,...columnN are the names of the columns in the table into which you want to insert
data.

You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns
of the table. But make sure the order of the values is in the same order as the columns in the table. The SQL
INSERT INTO syntax would be as follows:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example:
Following statements would create six records in CUSTOMERS table:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

SQL - SELECT Query


SQL SELECT statement is used to fetch the data from a database table which returns data in the form of result
table. These result tables are called result-sets.

Syntax:
The basic syntax of SELECT statement is as follows:

SELECT column1, column2, columnN FROM table_name;

Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the
fields available in the field, then you can use the following syntax:

SELECT * FROM table_name;

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would fetch ID, Name and Salary fields of the customers available in
CUSTOMERS table:

SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;

This would produce the following result:

+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

If you want to fetch all the fields of CUSTOMERS table, then use the following query:

SQL> SELECT * FROM CUSTOMERS;

This would produce the following result:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

SQL - WHERE Clause


The SQL WHERE clause is used to specify a condition while fetching the data from single table or joining with
multiple tables.

If the given condition is satisfied then only it returns specific value from the table. You would use WHERE
clause to filter the records and fetching only necessary records.

The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement,
etc., which we would examine in subsequent chapters.

Syntax:
The basic syntax of SELECT statement with WHERE clause is as follows:

SELECT column1, column2, columnN


FROM table_name
WHERE [condition]

You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc. Below examples
would make this concept clear.

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table where
salary is greater than 2000:

SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000;

This would produce the following result:

+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

SQL - UPDATE Query


The SQL UPDATE Query is used to modify the existing records in a table.

You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be
affected.

Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

You can combine N number of conditions using AND or OR operators.


Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would update ADDRESS for a customer whose ID is 6:

SQL> UPDATE CUSTOMERS


SET ADDRESS = 'Pune'
WHERE ID = 6;

Now, CUSTOMERS table would have the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not need to
use WHERE clause and UPDATE query would be as follows:
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;

Now, CUSTOMERS table would have the following records:

+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+

SQL - DELETE Query


The SQL DELETE Query is used to delete the existing records from a table.

You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be
deleted.

Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:

DELETE FROM table_name


WHERE [condition];

You can combine N number of conditions using AND or OR operators.

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would DELETE a customer, whose ID is 6:

SQL> DELETE FROM CUSTOMERS


WHERE ID = 6;

Now, CUSTOMERS table would have the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause and
DELETE query would be as follows:

SQL> DELETE FROM CUSTOMERS;

Now, CUSTOMERS table would not have any record.

DBMS - Joins
We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples
that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we
encounter huge relations with thousands of tuples having a considerable large number of attributes.
Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples
from different relations, if and only if a given join condition is satisfied.

We will briefly describe various join types in the following sections.

Theta (θ) Join


Theta join combines tuples from different relations provided they satisfy the theta condition. The join condition
is denoted by the symbol θ.

Notation
R1 ⋈θ R2

R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have
anything in common, that is R1 ∩ R2 = Φ.

Theta join can use all kinds of comparison operators.

Student
SID Name Std
101 Alex 10
102 Maria 11
Subjects
Class Subject
10 Math
10 English
11 Music
11 Sports

Student_Detail −

STUDENT ⋈Student.Std = Subject.Class SUBJECT


Student_detail
SID Name Std Class Subject
101 Alex 10 10 Math
101 Alex 10 10 English
102 Maria 11 11 Music
102 Maria 11 11 Sports

Equijoin
When Theta join uses only equality comparison operator, it is said to be equijoin. The above example
corresponds to equijoin.

Natural Join (⋈)


Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does.
We can perform a Natural Join only if there is at least one common attribute that exists between two relations.
In addition, the attributes must have the same name and domain.

Natural join acts on those matching attributes where the values of attributes in both the relations are same.

Courses
CID Course Dept
CS01 Database CS
ME01 Mechanics ME
EE01 Electronics EE
HoD
Dept Head
CS Alex
ME Maya
EE Mira
Courses ⋈ HoD
Dept CID Course Head
CS CS01 Database Alex
ME ME01 Mechanics Maya
EE EE01 Electronics Mira

Outer Joins
Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with
matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to
include all the tuples from the participating relations in the resulting relation. There are three kinds of outer
joins − left outer join, right outer join, and full outer join.

Left Outer Join(R S)


All the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any
matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL.

Left
A B
100 Database
101 Mechanics
102 Electronics
Right
A B
100 Alex
102 Maya
104 Mira
Courses HoD
A B C D
100 Database 100 Alex
101 Mechanics --- ---
102 Electronics 102 Maya

Right Outer Join: ( R S)


All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without
any matching tuple in R, then the R-attributes of resulting relation are made NULL.

Courses HoD
A B C D
100 Database 100 Alex
102 Electronics 102 Maya
--- --- 104 Mira

Full Outer Join: ( R S)


All the tuples from both participating relations are included in the resulting relation. If there are no matching
tuples for both relations, their respective unmatched attributes are made NULL.

Courses HoD
A B C D
100 Database 100 Alex
101 Mechanics --- ---
102 Electronics 102 Maya
--- --- 104 Mira

UNION operator
In SQL the UNION clause combines the results of two SQL queries into a single table of all matching rows. The
two queries must result in the same number ofcolumns and compatible data types in order to unite. Any duplicate
records are automatically removed unless UNION ALL is used.
UNION can be useful in data warehouse applications where tables aren't perfectly normalized. A simple example
would be a database having tables sales2005 and sales2006 that have identical structures but are separated because
of performance considerations. A UNION query could combine results from both tables.
Note that UNION does not guarantee the order of rows. Rows from the second operand may appear before, after,
or mixed with rows from the first operand. In situations where a specific order is desired, ORDER BY must be
used.
Note that UNION ALL may be much faster than plain UNION .
Examples[edit]
Given these two tables:

sales2005

person amount

Jeno 1000

Alex 2000

Bob 5000

sales2006

person amount

Joe 2000

Alex 2000

Zach 35000

Executing this statement:

SELECT * FROM sales2005


UNION
SELECT * FROM sales2006;

yields this result set, though the order of the rows can vary because no ORDER BY clause was supplied:

person amount

Joe 1000

Alex 2000

Bob 5000

Joe 2000

Zach 35000
Note that there are two rows for Joe because those rows are distinct across their columns. There is only one row for Alex
because those rows are not distinct for both columns.

UNION ALL gives different results, because it will not eliminate duplicates. Executing this statement:

SELECT * FROM sales2005


UNION ALL
SELECT * FROM sales2006;

would give these results, again allowing variance for the lack of an ORDER BY statement:

person amount

Joe 1000

Joe 2000

Alex 2000

Alex 2000

Bob 5000

Zach 35000
The discussion of full outer joins also has an example that uses UNIOn

SQL INTERSECT

DESCRIPTION
The SQL INTERSECT operator is used to return the results of 2 or more SELECT statements. However, it only
returns the rows selected by all queries or data sets. If a record exists in one query and not in the other, it will be
omitted from the INTERSECT results.

Intersect Query

Explanation: The INTERSECT query will return the records in the blue shaded area. These are the records that
exist in both Dataset1 and Dataset2.

Each SQL statement within the SQL INTERSECT must have the same number of fields in the result sets with
similar data types

SQL INTERSECT is query that allows you to select related information from 2 tables, this is combine 2
SELECT statement into 1 and display it out.
INTERSECT produces rows that appear in both queries.that means INTERSECT command acts as
an ANDoperator (value is selected only if it appears in both statements).

The syntax is as follows:

SELECT [COLUMN NAME 1], [COLUMN NAME 2],… FROM [TABLE NAME 1]
INTERSECT
SELECT [COLUMN NAME 1], [COLUMN NAME 2],… FROM [TABLE NAME 2]

EXAMPLE :

We have 2 table name GamesScores, GameScores_new.

Table GameScores

PlayerName Department Scores


Jason IT 3000
Irene IT 1500
Jane Marketing 1000
David Marketing 2500
Paul HR 2000
James HR 2000

Table GameScores_new
PlayerName Department Scores
Jason IT 3000
David Marketing 2500
Paul HR 2000
James HR 2000
SQL statement :

SELECT PlayerName FROM GameScores


INTERSECT
SELECT PlayerName FROM GameScores_new

Result:

PlayerName

David
James
Jason
Paul
SQL: MINUS OPERATOR
This SQL tutorial explains how to use the SQL MINUS operator with syntax and examples.

DESCRIPTION
The SQL MINUS operator is used to return all rows in the first SELECT statement that are not returned by the second
SELECT statement. Each SELECT statement will define a dataset. The MINUS operator will retrieve all records from
the first dataset and then remove from the results all records from the second dataset.

Minus Query

Explanation: The MINUS query will return the records in the blue shaded area. These are the records that exist in
Dataset1 and not in Dataset2.

Each SELECT statement within the MINUS query must have the same number of fields in the result sets with
similar data types.

The MINUS operator is not supported in all SQL databases. It can used in databases such as Oracle.

For databases such as SQL Server, PostgreSQL, and SQLite, use the EXCEPT operator to perform this type of
query.

SYNTAX
The syntax for the SQL MINUS operator is:

SELECT expression1, expression2, ... expression_n


FROM tables
WHERE conditions
MINUS
SELECT expression1, expression2, ... expression_n
FROM tables
WHERE conditions;
Parameters or Arguments
expression1, expression2, expression_n

The columns or calculations that you wish to retrieve.

tables

The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.

conditions

These are conditions that must be met for the records to be selected.

Note:

• There must be same number of expressions in both SELECT statements.


• The corresponding expressions must have the same data type in the SELECT statements. For
example:expression1 must be the same data type in both the first and second SELECT statement.

The MINUS command operates on two SQL statements. It takes all the results from the first SQL statement, and then
subtract out the ones that are present in the second SQL statement to get the final answer. If the second SQL statement
includes results not present in the first SQL statement, such results are ignored.

The syntax is as follows:

[SQL Statement 1]
MINUS
[SQL Statement 2];

Let's continue with the same example:

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table Internet_Sales

Txn_Date Sales

Jan-07-1999 250
Jan-10-1999 535

Jan-11-1999 320

Jan-12-1999 750

and we want to find out all the dates where there are store sales, but no internet sales. To do so, we use the following SQL
statement:

SELECT Txn_Date FROM Store_Information


MINUS
SELECT Txn_Date FROM Internet_Sales;

Result:

Txn_Date

Jan-05-1999

Jan-08-1999

'Jan-05-1999', 'Jan-07-1999';, and 'Jan-08-1999' are the distinct values returned from SELECT Txn_Date FROM
Store_Information. 'Jan-07-1999' is also returned from the second SQL statement, SELECT Txn_Date FROM
Internet_Sales, so it is excluded from the final result set.

Please note that the MINUS command will only return distinct values.

Some databases may use EXCEPT instead of MINUS. Please check the documentation for your specific database for the
correct usage.

Cursor in PL/SQL :

A cursor can be basically referred to as a pointer to the context area.Context area is a memory area that is created by Oracle
when SQL statement is processed.The cursor is thus responsible for holding the rows that have been returned by a SQL
statement.Thus the PL/SQL controls the context area by the help of cursor.An Active set is basically the set of rows that the
cursor holds. The cursor can be of two types: Implicit Cursor, and Explicit Cursor.

Advantages of Cursor:
• They are helpful in performing the row by row processing and also row wise validation on each row.
• Better concurrency control can be achieved by using cursors.
• Cursors are faster than while loops.
Disadvantages of Cursor:
• They use more resources each time and thus may result in network round trip.
• More number of network round trips can degrade the performance and reduce the speed.

2. Trigger in PL/SQL :
A Trigger is basically a program which gets automatically executed in response to some events such as
modification in the database.Some of the events for their execution are DDL statement, DML statement or any
Database operation.Triggers are thus stored within the database and come into action when specific conditions
match.Hence, they can be defined on any schema, table, view etc. There are six types of triggers: BEFORE
INSERT, AFTER INSERT, BEFORE UPDATE, AFTER UPDATE, BEFORE DELETE, and AFTER DELETE.

Advantages of Trigger:
• They are helpful in keeping the track of all the changes within the database.
• They also help in maintaining the integrity constraints.
Disadvantages of Trigger:
• They are very difficult to view which makes the debugging also difficult.
• Too much use of the triggers or writing complex codes within a trigger can slow down the
performance.

Difference between Cursor and Trigger:


S.NO CURSOR TRIGGER

It is a pointer which is used to control It is a program which gets executed

the context area and also to go in response to occurrence of some

1. through the records in the database. events.

A cursor can be created within a

trigger by writing the declare A trigger cannot be created within a

2. statement inside the trigger. cursor.

It gets created in response to

execution of SQL statement thus it is

3. not previously stored. It is a previously stored program.

The main function of the cursor is The main function of trigger is to

retrieval of rows from the result set maintain the integrity of the

4. one at a time (row by row). database.


S.NO CURSOR TRIGGER

A trigger is executed in response to

A cursor is activated and thus created a DDL statement, DML statement

5. in response to any SQL statement. or any database operation.

The main disadvantage of cursor is The main disadvantage of trigger is

that it uses more resources each time that they are hard to view which

and thus results in network round makes the debugging really

6. trip. difficult.

PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more specific tasks. It is just like
procedures in other programming languages.

The procedure contains a header and a body.

o Header: The header contains the name of the procedure and the parameters or variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception section similar to a general PL/SQL block.

How to pass parameters in procedure:


When you want to create a procedure or function, you have to define parameters .There is three ways to pass parameters in procedure:

1. IN parameters: The IN parameter can be referenced by the procedure or function. The value of the parameter cannot be
overwritten by the procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure or function, but the value of the parameter can
be overwritten by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure or function and the value of the parameter
can be overwritten by the procedure or function.

PL/SQL Create Procedure


Syntax for creating procedure:

1. CREATE [OR REPLACE] PROCEDURE procedure_name


2. [ (parameter [,parameter]) ]
3. IS
4. [declaration_section]
5. BEGIN
6. executable_section
7. [EXCEPTION
8. exception_section]
9. END [procedure_name];

Create procedure example


In this example, we are going to insert record in user table. So you need to create user table first.

Table creation:

1. create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user values(id,name);
7. end;
8. /

Output:

Procedure created.

Mapping constraints: Mapping constraints of mapping cardinalities or cardinality ratio, express


the number of entities to which another entity can be associated via a relationship set. Mapping cardinalities are
most useful in describing binary relationship sets that involve more than two entity sets. For a binary relationship
set R between entities sets A and B the mapping cardinality must be one of the following:

One to One: An entity in A is associated with at most one entity in B and an entity in B is associated with at most
one entity in A(see figure). One to Many: An entity in A is associated with any number (Zero to more) of entities
in B. An entity in B, however can be associated with at most one entity in A (see figure).Many to One: An entity
in A is associated with at most one entity in B. An entity in B, however, can be associated with any number (zero
of more) of entity in A (see figure) Many to Many : An entity in A is associated with any number of entities in
B, and an entity cardinality for a particular relationship set obviously depends on the real word situation that the
relationship set is modeling. As an illustration, consider the borrower relationship set. If in a particular bank a
loan can belong to only one customer and customer can have several loans, then the relationship set from customer
to loan is one to many. If a loan can belong to several customers the relationship set is many to many.
Mapping Cardinality
A mapping cardinality is a data constraint that specifies how many entities an entity can be related to in a
relationship set.

Example: A student can only work on two projects, the number of students that work on one project is not limited.

A binary relationship set is a relationship set on two entity sets. Mapping cardinalities on binary relationship
sets are simplest.

Consider a binary relationship set R on entity sets A and B. There are four possible mapping cardinalities in this
case:

1. one-to-one - an entity in A is related to at most one entity in B, and an entity in B is related to at most one
entity in A.

2. one-to-many - an entity in A is related to any number of entities in B, but an entity in B is related to at


most one entity in A.

3. many-to-one - an entity in A is related to at most one entity in B, but an entity in B is related to any
number of entities in A.

4. many-to-many - an entity in A is related to any number of entities in B, but an entity in B is related to


any number of entities in A.

You might also like