0% found this document useful (0 votes)
11 views

Advanced Database Management System

The document outlines the differences between DBMS and RDBMS, emphasizing the relational structure and integrity constraints of RDBMS. It details SQL components including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), along with commands for creating, altering, and managing database tables and their constraints. Additionally, it explains various SQL commands such as INSERT, DELETE, UPDATE, and SELECT, along with clauses like ORDER BY, GROUP BY, and HAVING for data retrieval and organization.

Uploaded by

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

Advanced Database Management System

The document outlines the differences between DBMS and RDBMS, emphasizing the relational structure and integrity constraints of RDBMS. It details SQL components including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), along with commands for creating, altering, and managing database tables and their constraints. Additionally, it explains various SQL commands such as INSERT, DELETE, UPDATE, and SELECT, along with clauses like ORDER BY, GROUP BY, and HAVING for data retrieval and organization.

Uploaded by

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

ADVANCED DATABASE MANAGEMENT SYSTEM

1.​ Difference between DBMS & RDBMS


DBMS RDBMS

A DBMS has to be persistent, that is it RDBMS is a Relational Database


should be accessible when the Management System Relational DBMS.
program created the data ceases to This adds the additional condition that
exist or even the application that the system supports a tabular
created the data restarted. structure for the data, with enforced
relationships between the tables.

A DBMS also has to provide some SQL queries make it simple to retrieve
uniform methods independent of a data.At the same time, many data
specific application for accessing the items can be accessed
information that is stored.

There is no correlation between the Data is kept in the form of tables that
data are linked together via foreign keys

DBMS does not impose any RDBMS defines the integrity constraint
constraints or security with regard to for the purpose of holding ACID
data manipulation. It is the user or property.
programmer’s responsibility to ensure
ACID properties.

2.​ Data Definition Language (DDL)


○​ Data Definition Language is a part of SQL that is responsible for the
creation, updation and deletion of tables. It is responsible for creation
of views and indexes also.
○​ The list of DDL Commands are: CREATE TABLE,CREATE VIEW,
CREATE INDEX, ALTER TABLE, DROP TABLE.

3.​ Data Manipulation Language (DML)


○​ Data manipulation commands manipulate (insert, delete, update and
retrieve) data. The DML language includes commands that run queries
and changes in data.
○​ It includes the following commands: SELECT, UPDATE, DELETE,
INSERT.

4.​ Data Control Language (DCL)


○​ The commands that form data control language are related to the
security of the database performing tasks of assigning privileges so
users can access certain objects in the database.
○​ The DCL commands are: GRANT, REVOKE, COMMIT, ROLLBACK

5.​ Domain/Data Types in SQL


The SQL - 92 standard supports a variety of built-in domain types,
including the following :
○​ Numeric data types include:
■​ Integer numbers of various size
1.​ INT or INTEGER
2.​ SMALLINT
■​ Real numbers of various precision
1.​ REAL
2.​ DOUBLE PRECISION
3.​ FLOAT (n)
■​ Formatted numbers can be represented by using
1.​ DECIMAL (i, j) or DEC (i, j)
2.​ NUMERIC (i, j) or NUMBER (i, j)
where, i - the precision, is the total number of decimal digits
and j - the scale, is the number of digits after the decimal point.
○​ Character string data types which are either fixed length or varying
length.
■​ CHAR (n) or CHARACTER (n) - It is a fixed length string with user
specified length n.
■​ VARCHAR (n) - It is a variable length character string with user
specified maximum length n. The full form of CHARACTER
VARYING (n) is equivalent
○​ Date and Time data types
■​ DATE - It is a calendar date containing year, month and day
typically in the form yyyy : mm : dd
■​ TIME - It is the time of day, in hours, minutes and seconds,
typically in the form HH : MM : SS
Varying length character strings, date and time were not part of SQL -
89 standard.

6.​ CREATE TABLE command


○​ The CREATE TABLE COMMAND is used to specify a new relation by
giving it a name and specifying its attributes and constraints.
○​ The attributes are specified first, and each attribute is given a name, a
data type to specify its domain of values and any attribute constraints
such as NOT NULL.
○​ The key, entity integrity and referential integrity constraints can be
specified within the CREATE TABLE statement, after the attributes are
declared.
○​ Syntax of create table command :
CREATE TABLE table_name (
Column_name_1 data_type [NOT NULL],
:
:
Column_name_n data_type [NOT NULL] );
○​ The variables are defined as follows :
■​ table_name - is the name for the table.
■​ column_name 1 to column_name n - are the valid column names
or attributes.
■​ NOT NULL – It specifies that column is mandatory. This feature
allows you to prevent data from being entered into tables without
certain columns having data in them.
○​ Ex.,Create Table Employee(
E_name varchar2 (20) NOT NULL,
B_Date Date,
Salary Decimal (10, 12)
Address Varchar2 (50) );

7.​ Constraints in CREATE TABLE command


○​ CREATE TABLE Command lets you enforce several kinds of
constraints on a table : primary key, foreign key, and check condition,
unique condition.
○​ A constraint clause can constrain a single column or group of columns
in a table.
○​ There are two ways to specify constraints :
■​ As part of the column definition ie. a column constraint
■​ At the end of the create table command ie. table constraint.
Clauses that constrain several columns are the table constraints.

8.​ PRIMARY KEY Constraint


○​ A table's primary key is the set of columns that uniquely identifies
each row in the table. CREATE TABLE command specifies the primary
key as follows :
create table table_name (
Column_name 1 data_type [not null],
:
:
Column_name n data type [NOT NULL],
[Constraint constraint_name]
[Primary key (Column_name A, Column_name B... Column_name X)]);
○​ Ex.
Create table Employee
(E_name Varchar2 (20),
Salary Decimal (10, 2),
Address Varchar2 (80),
Constraint PK_Employee
Primary key (Ename));

9.​ FOREIGN KEY Constraint


○​ A foreign key is a combination of columns with values based on the
primary key values from another table.
○​ A foreign key constraint, also known as a referential integrity
constraint, specifies that the values of the foreign key correspond to
actual values of the primary key in another table.
○​ Create table command specifies the foreign key as follows :
Create Table table_name
(Column_name 1 data type [NOT NULL],
:
:
Column_name n data type [NOT NULL],
[constraint constraint_name
Foreign key (column_name F1 ... Column_name Fn) references
referenced-table (column_name P1, ... column_name Pn)]);
○​ Ex.
Create table_department
(Department_id Varchar2 (20),
Department_name Varchar2 (20),
Constraint PK_Department
Primary key (Department_id));

Create table_course
(Course_id Varchar2 (20),
Department_id Varchar2 (20),
Title Varchar2 (20),
Constraint PK_course
Primary key (Course_id, Department_id),
Constraint FK_course
Foreign key (Department_id) references Department(Department_id));

10.​ UNIQUE Constraint or Candidate Key


○​ A candidate key is a combination of one or more columns, the values
of which uniquely identify each row of the table.
○​ Create table command specifies the unique constraint as follows:
CREATE TABLE table_name
(column_name 1 data_type [NOT NULL],
:
:
column_name n data_type [NOT NULL],
[constraint constraint_name
Unique (Column_name A,......... Column_nameX)]);
○​ Ex.
Create table student
(Student_id Varchar2 (20),
Last_name Varchar2 (20), NOT NULL,
First_name Varchar2 (20), NOT NULL,
BDate Date,
State Varchar2 (20),
Constraint UK-student
Unique (last_name, first_name),
Constraint PK-student
Primary key (Student_id));

11.​CHECK Constraint
○​ Using CHECK constraint SQL can specify the data validation for
columns during table creation.
○​ CHECK clause is a Boolean condition that is either TRUE or FALSE.
○​ If the condition evaluates to TRUE, the column value is accepted by
the database, if the condition evaluates to FALSE, the database will
return an error code.
○​ The check constraint is declared in CREATE TABLE statement using
the syntax :
Column_name datatype [constraint constraint_name] [CHECK (Condition)]
○​ Ex.
Create table_worker
(NameVarchar2 (25) NOT NULL,
Age Number,
Constraint CK_worker
CHECK (Age Between 18 AND 65) );

12.​ Default Clause


○​ By using the DEFAULT clause when defining a column, you can
establish a default value for that column.
○​ This default value is used for a column, whenever, row is inserted into
the table without specifying the column in the INSERT statement.
○​ Ex.
Create table_student
(Student_id Varchar2 (20),
Last_name Varchar2 (20) NOT NULL,
First_name Varchar2 (20) NOT NULL,
City Varchar2 (20), DEFAULT 'PUNE'.
Constraint PK_student
Primary key (Student_id);

13.​ ALTER TABLE command


○​ You can modify a table's definition using the ALTER TABLE command.
This statement changes the structure of a table, not its contents.
○​ Using the ALTER TABLE command, you can make the following
changes to the table:
■​ Adding a new column to an existing table:
ALTER TABLE table_name
ADD (Column_name datatype
:
:
Column_name n datatype);
■​ Modify an existing column in the existing table:
ALTER TABLE [TABLENAME] DROP CONSTRAINT
[CONSTRAINTNAME];
■​ Adding a constraint to an existing table : Any constraint i.e. a
primary key, foreign key, unique key or check constraint can be
added to an existing table using ALTER TABLE command.
ALTER TABLE table_name
ADD (constraint)
○​ A column in the table can be modified in following ways -
■​ Changing a column definition from NOT NULL to NULL i.e. from
mandatory to optional and Vice versa - If a table is empty, you
can define a column to be NOT NULL. However, if the table is not
empty, you cannot change a column to NOT NULL unless every
row in the table has a value for that particular column.
Alter Table ex_table modify (column_name datatype Null);
■​ Increasing and Decreasing a Column's Width :
​ ​ ​ CREATE TABLE Example
​ ​ ​ (Name Varchar(20) NOT NULL,
​ ​ ​ roll int);
​ ​ ​ ALTER TABLE Example MODIFY(Name Varchar(40));

14.​ DROP TABLE command


○​ Dropping a table means to remove the table's definition from the
database.
○​ DROP TABLE command is used to drop the table as follows :
​ DROP TABLE table_name;
○​ Ex.,
○​ SQL >Drop table_student;
Table dropped.
○​ You drop a table only when you no longer need it

15.​INSERT command
○​ The syntax of insert statement is :
INSERT INTO table_name
[(column_name [ , column_name] ...... [ , column_name])]
VALUES
(column_value [ , column_value] ...... [ , column_value]);
○​ The number of columns in the list of column_names must match the
number of literal values or expressions that appear in parenthesis after
the keyword values.
○​ If the column names specified in the Insert statement are more than
values, then it returns an error.
○​ Column and value data type must match.
○​ Ex.
SQL> Insert into Employee
(E_name, B_Date, Salary, Address)
Values
('Sachin', '21-MAR-73', 50000.00, 'Mumbai');
16.​DELETE Command
○​ The syntax of delete statement is :
DELETE FROM table_name
[WHERE condition]
○​ DELETE Command without WHERE clause will empty the table
completely.
○​ Ex.
SQL>Delete from Student
Where Student_id = 'SE 201';
1 row deleted.

17.​UPDATE Command
○​ If you want to modify existing data in the database, UPDATE command
can be used to do that. With this statement you can update zero or
more rows in a table.
○​ The syntax of UPDATE command is :
UPDATE table_name
SET column_name : : expression
[, column_name : : expression]
[, column_name : : expression]
[where condition]
○​ The UPDATE statement references a single table and assigns an
expression to at least one column.
○​ The WHERE clause is optional; if an UPDATE statement does not
contain a WHERE clause, the assignment of a value to a column will be
applied to all rows in the table.

18.​ SELECT Command


○​ The basic structure of an SQL expression consists of three clauses :
○​ The SELECT clause corresponds to the projection operation of the
relational algebra. It is used to list the attributes desired in the result of
a query.
○​ The FROM clause corresponds to the cartesian product operation of
the relational algebra. It lists the relations to be scanned in the
elevation of the expression.
○​ The WHERE clause corresponds to the selection predicate of the
relational algebra. It consists of predicates involving attributes of the
relations that appear in the FROM clause.
○​ Simple SQL query i.e. select statement has the form :
SELECT A1, A2, ......, An
FROM r1, r2 , ......, rm
WHERE P
○​ The variables are defined as follows :
A1, A2, ..., An represent the attributes.
r1, r2, ..., rm represents the relations from which the attributes are
selected.
P - is the predicate.
○​ The WHERE clause is optional. If the where clause is omitted, the
predicate P is true.
○​ The purpose of the SELECT statement is to retrieve and display data
from one or more database tables.
○​ It is an extremely powerful statement capable of performing the
equivalent relational algebra’s Selection, Projection, and Join
operations in a single statement.
○​ To select all columns in the table you can use
SELECT * FROM table_name;

19.​ ORDER BY Clause


○​ The ORDER BY clause is similar to the GROUP BY clause. The ORDER
BY clause enables you to sort your data in either ascending or
descending order.
○​ The ORDER BY clause consists of a list of column identifiers that the
result is to be sorted on, separated by columns. A column identifier
may be either a column name or a column number.
○​ It is possible to include more than one element in the ORDER BY
clause. The major sort key determines the overall order of the result
table
○​ If the values of the major sort key are unique, there is no need for
additional keys to control the sort.
○​ If a second element appears in the ORDER BY clause, it is called a
minor sort key.
○​ Ex.
​ ​ SELECT * FROM worker ORDER BY f_name asc;

20.​ GROUP BY clause


○​ A GROUP BY clause arranges your data rows into a group according
to the columns you specify.
○​ A query that includes group by clause is called a grouped query
because it groups that data from the SELECT tables and generates a
single summary row for each group.
○​ The columns named in the group by clause are called the grouping
columns.
○​ When a GROUP BY clause is used, each item in the SELECT list must
be single-valued per group.
○​ All column names in SELECT must appear in GROUP BY clause, unless
the name is used only in an aggregate function. The contrary is not
true.
○​ Ex. To group by more than one column,
○​ SQL>select *
from worker
group by status, Gender;

21.​ HAVING clause


○​ The Having clause is similar to the where clause.
○​ The Having clause does for aggregate data what where clause does
for individual rows.
○​ The having clause is another search condition.In this case, however,
the search is based on each group of grouped table.
○​ The difference between where clause and having clause is in the way
the query is processed.
○​ In a where clause, the search condition on the row is performed
before rows are grouped. In having clause, the groups are formed first
and the search condition is applied to the group.
○​ Ex. To select all workers grouped by their status and gender having F
SQL>select *
from worker
Group By status, Gender
Having Gender = 'F';

22.​ LIKE operator
○​ The most commonly used operation on strings is pattern matching
using the operator like.
○​ We describe patterns using two special characters.
■​ Percent (%) - The % character matches any substring
■​ Underscore (_) : The-character matches any character.
○​ Patterns are case sensitive.
○​ Ex. Find the names of customers whose city name include "bad"
SQL>select cust_name, cust_city
from customer
where cust_city like "%bad";
23.​ ALL Operator
○​ The keyword ALL allows to specify explicitly that the duplicates are
not removed.
○​ Ex.
SQL>select all branch_name
from loan;
○​ It specifies that duplicates are not eliminated from the result relation.
Since duplicate retention is by default, we do not need to use ALL.

24.​ ANY Operator


○​ The ANY operator returns TRUE if ANY of the subquery values meet
the condition & returns a boolean value as a result.
○​ Ex.
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
○​ This lists the ProductName if it finds ANY records in the OrderDetails
table has Quantity equal to 10

25.​ IN Operator
○​ The IN operator allows you to easily test if an expression matches any
value in a list of values.
○​ It is used to help reduce the need for multiple OR conditions in a
SELECT, INSERT, UPDATE, or DELETE statement.
○​ Syntax: expression IN (value1, value2, .... value_n);
○​ Ex.
SELECT *
FROM customers
WHERE customer_id IN (5000, 7000, 8000, 9000);
○​ This example would return all records from the customers table where
the customer_id is either 5000, 7000, 8000 or 9000.

26.​ BETWEEN Operator


○​ In order to select data that is within a range of values ,the BETWEEN
operator is used.
○​ The BETWEEN operator allows the selection of rows that contain
values within a specified lower and upper limit.
○​ The range coded after the word BETWEEN is inclusive.
○​ The lower value must be coded first.The two values in between the
range must be linked with the keyword AND
○​ The BETWEEN operator can be used with both character and numeric
data types.
○​ However the data types can not be mixed.i.e the lower value of a
range of values from a character column and the other from a numeric
column.
○​ Ex. To list the transactions performed in months of January to March
○​ SELECT * FROM TRANS_MSTR WHERE TO_CHAR(DT,’MM’) BETWEEN
01 AND 03;

27.​ NOT Operator


○​ The NOT Operator is used to negate a condition in the WHERE clause
of a SELECT, INSERT, UPDATE, or DELETE statement.
○​ Ex.
SELECT *
FROM customers
WHERE customer_id NOT IN (5000, 7000, 8000, 9000);
○​ This example would return all records from the customers table where
the customer_id is not 5000, 7000, 8000 or 9000.

28.​ EXISTS Operator


○​ The SQL EXISTS condition is used in combination with a subquery and
is considered to be met, if the subquery returns at least one row. It
can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
○​ The syntax for the EXISTS condition in SQL is:
WHERE EXISTS ( subquery );
○​ Ex.
SELECT *
FROM customers
WHERE EXISTS
(SELECT *
FROM orders
WHERE customers.customer_id = orders.customer_id);
○​ This selects all the records from the customers table where there is at
least one record in the orders table with the same customer_id.
29.​ IS NULL Operator
○​ The IS NULL condition is used in SQL to test for a NULL value. It
returns TRUE if a NULL value is found, otherwise it returns FALSE. It
can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
○​ The syntax for the IS NULL condition in SQL is:
expression IS NULL
○​ Ex.
SELECT *
FROM customers
WHERE favorite_website IS NULL;
○​ This will select all the records from the customers table where the
favorite_website column is NULL.

30.​ AND Operator


○​ The AND operator is a logical operator that combines two or more
conditions in a SQL statement.
○​ Syntax:
SELECT *
FROM table_name
WHERE condition1 AND condition2 and ...conditionN;
○​ Ex.
SELECT * FROM Employees WHERE salary > 50000 AND department
= 'sales'
○​ This returns all employees with a salary greater than 50000 and are in
the sales department.

31.​ OR Operator
○​ The OR operator is a logical operator in SQL that combines two or
more expressions to return true if any of the conditions are true.
○​ Syntax:
SELECT * FROM table_name WHERE condition1 OR condition2 OR...
conditionN;
○​ Ex.
SELECT * FROM employees
WHERE last_name = 'Smith' OR first_name = 'John';
○​ This will select all employees whose last_name is Smith OR first_name
is John.

32.​ DISTINCT keyword


○​ SELECT statement has an optional Keyword distinct.
○​ This keyword follows select and return only those rows which have
distinct values for the specified columns. i.e. it eliminates duplicate
values.
○​ Ex.
SQL>select distinct branch_name
from loan
which eliminates duplicate values in the result.

33.​ RENAME operation


○​ SQL provides a mechanism for renaming both relations and attributes.
○​ It uses AS clause and the syntax is :
old_name as new_name
○​ The AS clause can appear in both the select and from clauses.
○​ Ex.
○​ SQL> select customer_name, borrower_loan_no as loan_id
from borrower, loan
where borrower loan_no = loan·loan_no
And branch name = 'ICICI';

34.​ Short note on SQL Grammar


Here, are some grammatical requirements to keep in mind when you are
working with SQL:
○​ Every SQL statement is terminated by a semicolon.
○​ An SQL statement can be entered on one line or split across several
lines for clarity.
○​ SQL isn't case sensitive. You can mix uppercase and lowercase when
referencing SQL keywords (Such as SELECT and INSERT), table
names, and column names.
○​ However, case does matter when referencing the contents of a
column.

35.​ GRANT command


○​ The objects created by one user are not accessible by another user
unless the owner of those objects gives such permissions to other
users. These permissions can be given by using the GRANT
statement.
○​ One user can grant permission to another user if he is the owner of
the object or has the permission to grant access to other users.
○​ The grant statement provides various types of access to database
objects such as tables, views and sequences.
○​ SYNTAX -
GRANT {object privileges}
ON object name
To user name
[with GRANT OPTION]
○​ Each object privilege that is granted authorises the grantee to perform
some operations on the object. The user can grant all the privileges or
grant only specific object privileges
○​ The list of object privileges is as follows :
■​ Alter - allows the grantee to change the table definition with the
ALTER TABLE command.
■​ Delete - allows the grantee to remove the records from the table
with the DELETE command.
■​ Index - allows the grantee to create an index on table with the
CREATE INDEX command.
■​ Insert - allows the grantee to add records to the table with the
INSERT command.
■​ Select - allows the grantee to query the tables with SELECT
command.
■​ Update - allows the grantee to modify the records in tables with
UPDATE command.
■​ With grant option - It allows the grantee to grant object
privileges to other users.
○​ Ex. Grant all privileges on the student table to user Sachin with grant
option.
SQL>GRANT ALL
ON student
To Sachin
WITH GRANT OPTION;

36.​ REVOKE command


○​ The REVOKE statement is used to deny the grant given on an object.
○​ Syntax :
REVOKE {object privileges}
ON object name
FROM user name;
○​ The list of object privileges is :
■​ Alter - allows the grantee to change the table definition with the
ALTER TABLE command.
■​ Delete - allows the grantee to remove the records from the table
with the DELETE command.
■​ Index - allows the grantee to create an index on table with the
CREATE INDEX command.
■​ Insert - allows the grantee to add records to the table with the
INSERT command.
■​ Select - allows the grantee to query the tables with SELECT
command.
■​ Update - allows the grantee to modify the records in tables with
UPDATE command.
○​ You cannot use REVOKE command to perform following operations :
■​ Revoke the object privileges that you didn't grant to the revokee.
■​ Revoke the object privileges granted through the operating
system.
○​ Ex. Revoke all privileges on student that were granted to Pradeep.
○​ SQL>Revoke ALL
ON student
FROM Pradeep

37.​ COMMIT command


○​ Commit command is used to permanently record all changes that the
user has made to the database since the last commit command was
issued or since the beginning of the database session.
○​ Syntax : COMMIT;
○​ Implicit COMMIT - The actions that will force a commit to occur even
without your instructing it to are : quit, exit, create table or create view
,drop table or drop view,grant or revoke,connect or
disconnect,alter,audit and non-audit
○​ Using any of these commands is just like using commit. Until you
commit, only you can see how your work affects the tables. Anyone
else with access to these tables will continue to get the old
information.

38.​ ROLLBACK command


○​ The ROLLBACK statement does the exact opposite of the commit
statement. It ends the transaction but undoes any changes made
during the transaction.
○​ Rollback is useful for two reasons :
■​ If you have made a mistake, such as deleting the wrong row for a
table, you can use rollback to restore the original data.
■​ ROLLBACK is useful if you have started a transaction that you
cannot complete.
○​ Syntax : ROLLBACK [WORK] [TO [SAVEPOINT] savepoint]
where
WORK - is optional and is provided for ANSI compatibility
SAVEPOINT - is optional and is used to rollback a partial transaction,
as far as the specified save point.
Savepoint : is a savepoint created during the current transaction.
○​ Ex. To rollback to savepoint sps : ROLLBACK TO SAVEPOINT sps1;

39.​ What are Savepoints?


○​ Savepoints mark and save the current point in the current processing
of a transaction.
○​ Used with the ROLLBACK statement, savepoints can undo part of a
transaction.
○​ By default the maximum number of savepoints per transaction is 5.
○​ An active savepoint is the one that is specified since the last commit
or rollback.
○​ Syntax : SAVEPOINT savepoint ;
○​ After a savepoint is created, you can either continue processing,
commit your work, rollback the entire transaction, or rollback to the
savepoint.

40.​ Define Functions


○​ A function is similar to a procedure which is simply a PL/SQL block
that executes certain tasks.
○​ The main difference between the function and procedure is that a
function returns a value where procedure does not.
○​ The different types of functions available in SQL are:
■​ Aggregate functions
■​ Date and time functions
■​ Arithmetic functions
■​ Character functions
■​ Conversion functions
■​ Miscellaneous functions.

41.​ Aggregate Functions in SQL


○​ These functions are also referred to as group functions. They return a
value based on the values in a column.
○​ SQL offers five built-in aggregate functions
○​ AVG( ) - computes the column's average value. ​
Ex.Find the average balance ​
SQL> select avg(balance) from account;
○​ MIN( ) - return the minimum value for the specified column
Ex. Find the minimum values of balance.
SQL> Select min(balance) from account;
○​ MAX( ) - return the maximum values for the specified column.
Ex. Find the maximum values of balance.
SQL> Select max(balance) from account;
○​ SUM( ) - computes the column's total value.
Ex. Find the sum of total balance.
SQL> Select sum(balance) from account;
○​ COUNT( ) - It counts the number of rows. There are two forms of
count:
■​ count (*) - which counts all the rows in a table that satisfy any
specified criteria.
■​ count (column_name) - which counts all rows in a table that have
a non-null value for column_name and satisfy the specified
criteria.
​ ​ Ex. Find the number of transactions done.
​ ​ SQL>select count(transaction_id) from account;
○​ VARIANCE( ) - Variance produces the square of the standard deviation
a number vital to many statistical calculations.
Ex.
SQL>SELECT VARIANCE(NAME) FROM TEAM; //output - invalid
number
○​ COUNT, MIN and MAX apply to both numeric and non-numeric fields,
but SUM and AVG may be used on numeric fields only.
○​ Apart from COUNT(*), each function eliminates nulls first and
operates only on the remaining non-null values.

42.​ Date and Time Functions


○​ NEW_TIME( ) - If you need to adjust the time according to the time
zone you are in, the New_TIME function is used.
Syntax - NEW_TIME( date, oldzone1, newzone2 );
○​ NEXT_DAY( ) - It finds the name of the first day of the week that is
equal to or later than another specified date.
Syntax - NEXT_DAY( date, weekday );
○​ SYSDATE - returns the system time and date.
Ex. SELECT DISTINCT SYSDATE FROM PROJECT;
Output -
SYSDATE
—---------------------
30-MAR-24 1037PM

43.​ Arithmetic Functions


○​ ABS( ) - The ABS function returns the absolute value of the number
you point to. ABS changes all the negative numbers to positive and
leaves positive numbers alone.
Ex.
SQL>SELECT ABS(-1); //Output - 1
○​ CEIL( ) - CEIL returns the smallest integer greater than or equal to its
argument.
Ex.
SQL>SELECT CEIL(0.69); //Output - 1
○​ FLOOR( ) - FLOOR returns the largest integer equal to or less than its
argument.
Ex.
SQL> SELECT FLOOR(3.14); //Output - 3
○​ SIN( ) , COS( ) , TAN( ) - The COS, SIN, and TAN functions provide
support for various trigonometric concepts. They all work on the
assumption that n is in radians.
Ex.
SQL> SELECT COS(3.14); //Output - -1
○​ EXP( ) - EXP enables you to raise e (e is a mathematical constant used
in various formulas) to a power.
Ex.
SQL>SELECT EXP(5); //Output - 148.41
○​ LN( ) , LOG( ) - These two functions centre on logarithms. LN returns
the natural logarithm of its argument which has to be positive.
Ex.
SQL>SELECT LN(5); //Output - 1.609
○​ MOD( ) - The MOD function divides the first argument by the second
argument and returns the remainder.
Ex.
SQL>SELECT MOD(5,2); //Output - 1
○​ POWER( ) - returns the value of a number raised to the power of
another number. In the power function, we have to pass the two
numbers as the argument in which one number acts as exponent and
other acts as the base.
Ex.
SQL> SELECT POWER(5,2) AS POWER_of5; //Output - 25
○​ SIGN( ) - SIGN returns -1 if its argument is less than 0, 0 if its
argument is equal to 0 and 1 if its argument is greater than 0.
Ex.
SQL>SELECT SIGN(0) AS SIGN_of0; //Output - 0
○​ SQRT( ) - The function SQRT returns the square root of an argument.
Because the square root of a negative number is undefined, you
cannot use SQRT on negative numbers.
Ex.
SQL>SELECT SQRT(16) AS SQRT_of16; //Output - 4

44.​ Character Functions


○​ CHR - CHR returns the character equivalent of the number it uses as
an argument. The character it returns depends on the character set of
the database that is set to ASCII
Ex. SELECT CHR(69) FROM DUAL; //Output - E
○​ CONCAT - the CONCAT function allows you to concatenate strings
together.
Ex. SELECT CONCAT(‘Prix’, ‘Studios’); //output - Prix Studios
○​ INITCAP - INITCAP capitalises the first letter of a word and makes all
other characters lowercase.
Ex. SELECT INITCAP(‘PREM’) FROM DUAL; //Output - Prem
○​ LOWER & UPPER - LOWER changes all the characters to lowercase;
UPPER does just the reverse.
Ex. SELECT UPPER(‘rastogi’) FROM DUAL; /Output - RASTOGI
○​ LPAD - LPAD function pads the left-side of a string with a specific set
of characters (when string1 is not null).
Syntax - LPAD(string1, padded_length, pad_string);
Where string1 - string to pad characters to
padded_length - The number of characters to return
pad_string - Optional. This is the string that will be padded to the
left-hand side of string1
Ex. SELECT LPAD(‘tech’, 8, ‘0’) FROM DUAL; //Output - 0000tech
○​ RPAD - RPAD function similar to LPAD pads the right-side of a string
with a specific set of characters.
Ex. SELECT RPAD(‘tech’, 8,’0’) FROM DUAL; //Output - tech0000
○​ LTRIM - LTRIM function removes all specified characters from the
left-hand side of a string.
Ex. SELECT LTRIM(‘000123’, ’0’) FROM DUAL; //Output - 123
○​ RTRIM - the RTRIM function removes all space characters from the
right-hand side of a string.
Ex. SELECT RTRIM(‘123000’, ’0’) FROM DUAL; //Output - 123
○​ REPLACE - It replaces a sequence of characters in a string with
another set of characters.
Ex. SELECT REPLACE(‘000123’, ’0’, ‘x’) FROM DUAL; //Output -
xxx123
○​ SUBSTR - This function allows you to extract a substring from a string.
Ex. SELECT SUBSTR(‘Tech on the Net’, 1, 4) FROM DUAL; //Output -
Tech
○​ TRANSLATE - TRANSLATE function replaces a sequence of
characters in a string with another set of characters. However, it
replaces a single character at a time.
Ex. SELECT TRANSLATE('1tech23', '123', '456') FROM DUAL; //Output
- 4tech56
○​ INSTR - It returns the location of a substring in a string.
Ex. SELECT INSTR('Tech on the net', 'e', 1, 3) FROM DUAL;
//Output (the third occurrence of 'e') - 14
○​ LENGTH - It returns the length of the specified string.
Ex. SELECT LENGTH(‘Prix’) FROM DUAL; //Output - 4

45.​ Conversion Functions


○​ to_char( ) - This function converts a number or date to a string.
Ex. SELECT TO_CHAR(sysdate, 'yyyy/mm/dd' ) FROM DUAL; //Output
- 2024/03/30
○​ to_number( ) - TO_NUMBER function converts a string to a number.
Ex. SELECT TO_NUMBER(‘69420’, ‘99999’) FROM DUAL; //Output -
69420

46.​ Miscellaneous Functions


○​ GREATEST - It returns the greatest value in a list of expressions.
Ex. SELECT GREATEST(2, 5, 12. 3) FROM DUAL; //Output - 12
○​ LEAST - It returns the least value in a list of expressions
Ex. SELECT LEAST(2, 5, 12. 3) FROM DUAL; //Output - 2
○​ USER - It returns the user_id from the current Oracle session.
Ex. SELECT USER FROM CONVERT; //Output - Prem

47.​ JOINS in SQL


○​ The JOIN statement of SQL enables you to design smaller, more
specific tables that are easier to maintain than larger tables.
○​ JOINS are used to retrieve data from multiple tables. A JOIN is
performed whenever two or more tables are joined in a SQL
statement.
○​ There are 4 different types of Oracle joins:
■​ INNER JOIN (or sometimes called simple join)
■​ LEFT OUTER JOIN (or sometimes called LEFT JOIN)
■​ RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
■​ FULL OUTER JOIN (or sometimes called FULL JOIN)

48.​ INNER JOIN (simple join)


○​ It is the most common type of join. INNER JOIN returns all rows from
multiple tables where the join condition is met.
○​ It is also known as Equi Join
○​ Syntax -
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
○​ In this visual diagram, the Oracle INNER JOIN returns the shaded area:

○​ The Oracle INNER JOIN would return the records where table1 and
table2 intersect.

49.​ LEFT OUTER JOIN


○​ Another type of join is called an Oracle LEFT OUTER JOIN.
○​ This type of join returns all rows from the LEFT-hand table specified in
the ON condition and only those rows from the other table where the
joined fields are equal (join condition is met).
○​ Syntax -
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
○​ In some databases, the LEFT OUTER JOIN keywords are replaced with
LEFT JOIN.
○​ In this visual diagram, the Oracle LEFT OUTER JOIN returns the
shaded area:

○​ The LEFT OUTER JOIN would return all records from table1 and only
those records from table2 that intersect with table1.

50.​ RIGHT OUTER JOIN


○​ Another type of join is called an Oracle RIGHT OUTER JOIN. This type
of join returns all rows from the RIGHT-hand table specified in the ON
condition and only those rows from the other table where the joined
fields are equal (join condition is met).
○​ SYNTAX
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
○​ In some databases, the RIGHT OUTER JOIN keywords are replaced
with RIGHT JOIN.
○​ In this visual diagram, the Oracle RIGHT OUTER JOIN returns the
shaded area:

○​ The Oracle RIGHT OUTER JOIN would return all records from table2
and only those records from table1 that intersect with table2.

51.​ FULL OUTER JOIN


○​ Another type of join is called an Oracle FULL OUTER JOIN. This type
of join returns all rows from the LEFT-hand table and RIGHT-hand
table with nulls in place where the join condition is not met.
○​ Syntax -
SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;
○​ In some databases, the FULL OUTER JOIN keywords are replaced with
FULL JOIN.
○​ In this visual diagram, the Oracle FULL OUTER JOIN returns the
shaded area:

○​ The Oracle FULL OUTER JOIN would return all the records from both
table1 and table2.

52.​ NON EQUI JOINS


○​ Non-Equi Join is also a type of INNER Join in which we need to
retrieve data from multiple tables.
○​ Non-Equi Join matches the column values from different tables based
on an inequality based on the operators like, <,>,<=,>=,!=, BETWEEN,
etc.
○​ We use the Non-Equi joins for the below-mentioned reasons-
■​ Retrieving data matching in a range of values.
■​ Checking for duplicate data between tables.
■​ For calculating totals.
○​ Syntax
SELECT *
FROM TableName1, TableName2
WHERE TableName1.columnName [> | < | >= | <= | != | BETWEEN ]
TableName2.columnName;
○​ Non-Equi Join in SQL retrieves data using any operator or condition
except the equality condition

53.​ Explain Views


○​ An Oracle VIEW, in essence, is a virtual table that does not physically
exist. Rather, it is created by a query joining one or more tables.
○​ Syntax for Creating a View is:
CREATE VIEW view_name AS
SELECT columns
FROM tables
[WHERE conditions];
○​ Once a VIEW has been created, you can drop it with the DROP VIEW
Statement. The syntax for DROP VIEW is:
DROP VIEW view_name;
○​ We can think of view as a way of specifying a table that we need not
exist physically.

54.​ Explain Indexes


○​ An index is a physical access structure that is specified on one or
more attributes of the relation.
○​ The attributes on which an index is created are termed indexing
attributes.
○​ In general, if attributes used in selection conditions and in join
conditions of a query are indexed, the execution time of the query is
greatly improved.
○​ In SQL indexes can be created and dropped dynamically. The create
Index command is used to specify an index.
○​ Each index is given a name, which is used to drop the index when we
do not need it any more.
○​ Syntax:
CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, ... column_n);
○​ In general, the index is arranged in ascending order of the indexing
attribute values. If we want the values in descending order we can
add the keyword DESC after the attribute name.
○​ There are two additional options on indexes in SQL. The first is to
specify the key constraint on the indexing attribute or combination of
attributes.
○​ The keyword unique following the CREATE command is used to
specify a key.
○​ The second option on index creation is to specify whether on index is
clustering index.
○​ You can drop an index in SQL using the DROP INDEX statement.
○​ Syntax:
■​ DROP INDEX index_name;
○​ The reason for dropping indexes is that they are expensive to maintain
whenever the base relation is updated and they require additional
storage.
○​ However, the indexes that specify a key constraint should not be
dropped as long as we want the system to continue enforcing that
constraint.
○​ Ex.
​ ​ CREATE INDEX websites_idx
​ ​ ON websites (site_name);

55.​ Explain Sequences


○​ In Oracle, you can create an autonumber field by using sequences.
○​ A sequence is an object in Oracle that is used to generate a number
sequence.
○​ This can be useful when you need to create a unique number to act as
a primary key.
○​ The value generated can have a maximum of 38 digits.
○​ A sequence can be defined to:
■​ Generate numbers in ascending or descending order
■​ Provide intervals between numbers
■​ Caching of sequence numbers in memory to speed up their
availability
○​ A sequence is an independent object and can be used with any table
that requires its output.
○​ Syntax for Creating a Sequence is:
CREATE SEQUENCE sequence_name
MINVALUE value /NOMINVALUE
MAXVALUE value /NOMAXVALUE
START WITH value
INCREMENT BY value
​ ​ CYCLE/NOCYCLE
CACHE value/NOCACHE;
○​ To simply view sequence value, Use a select statement as below:
SELECT sequence_name.Nextval from DUAL ;
This will display the next value held in the cache on the screen.
○​ To reference the current value of a sequence:
SELECT <SequenceName>.CurrVal FROM DUAL;
○​ The DROP SEQUENCE command is used to remove the sequence
from the database as below:
DROP SEQUENCE sequence_name;

56.​ Define the different Keywords & parameters used when Creating a
Sequence.
○​ INCREMENT BY : Specifies the interval between sequence numbers. It
can be any positive or negative value but not zero.If this clause is
omitted ,the default value is 1 .
○​ MINVALUE : Specifies the sequence minimum value.
○​ NOMINVALUE : Specifies a minimum value of 1 for an ascending
sequence and – (10)^26 for a descending sequence.
○​ MAXVALUE: Specifies the maximum value that a sequence can
generate.
○​ NOMAXVALUE : Specifies a maximum of 10^27 for an ascending
sequence or -1 for a descending sequence. This is the default clause.
○​ START WITH : Specifies the first sequence number to be generated.
The default for an ascending sequence is the sequence minimum
value(1) and for a descending sequence, it is the maximum value(-1)
○​ CYCLE : Specifies that the sequence continues to generate repeat
values after reaching either its maximum value.
○​ NOCYCLE: Specifies that a sequence cannot generate more values
after reaching the maximum value.
○​ CACHE : :Specifies how many values a sequence oracle pre-allocates
and keeps in memory for faster access.The minimum value for this
parameter is two.
○​ NOCACHE : Specifies that values of a sequence are not pre-allocated.

57.​ Short note on Nested Sub queries

58.​ Procedures
○​ Procedures are simply a PL/SQL block that executes certain tasks.
○​ A procedure is completely portable among platforms in which Oracle
is executed.
○​ A procedure is created using the CREATE PROCEDURE command.
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
​ executable_section
[EXCEPTION
​ exception_section]
END [procedure_name];
○​ To execute the stored procedure simply call it by name in EXECUTE
command as
SQL> execute myproc1(7768);
This will execute myproc1 with the value 7768.
○​ To delete a procedure DROP PROCEDURE command is used.
Syntax :
DROP PROCEDURE procedure_name;

59.​ Advantages of procedures


○​ Improved performance :
■​ A block is placed on the database and it is parsed at the time it is
stored. When it is subsequently executed Oracle already has the
block compiled and it is therefore much faster.
■​ Reduce the number of calls to the database and decrease
network traffic by bundling commands.
○​ Improved maintenance :
■​ Modify routines online without interfering with other users.
■​ Modify one routine to affect multiple applications.
■​ Modify one routine to eliminate duplicate testing.
○​ Improved data security and integrity :
■​ Control indirect access to objects from non privileged users.
■​ Ensure that related actions are performed together or not at all,
by funnelling actions for related tables through a single path.

60.​ Short note on PL/SQL


○​ PL/SQL stands for Procedural Language/SQL.
○​ PL/SQL extends SQL by adding constructs found in procedural
languages, resulting in a structural language that is more powerful
than SQL.
○​ PL/SQL is not case sensitive.
○​ All PL/SQL programs are made up of blocks, each block performs a
logical action in the program.
○​ A PL/SQL block has the following structure:
DECLARE
/* Declaration section */
BEGIN
/* Executable section */
EXCEPTION
/* Exception handling section */
END;
○​ A PL/SQL block consists of three parts:
■​ Declaration section - This is the first section which starts with
the word Declare. All the identifiers (constants and variables) are
declared in this section before they are used in the SELECT
command.
■​ Executable section - This section contains procedural and SQL
statements. This is the only section of the block which is
required. This section starts with ‘Begin’ word.
■​ Exception Handling section - This section is used to handle
errors that occur during execution of PL/SQL programs. This
section starts with an ‘exception’ word .
○​ The ‘End’ indicates the end of the PL/SQL block.
○​ Only the executable section is required. The other sections are
optional.

61.​ Architecture of PL/SQL

​ ​ ​ ​ ​ ​ PL/SQL Engine
○​ The PL/SQL compilation and run-time system is a technology, not an
independent product. Think of this technology as an engine that
compiles and executes PL/SQL blocks and subprograms.
○​ The engine can be installed in an Oracle server or in an application
development tool such as Oracle Forms or Oracle Reports.
○​ So, PL/SQL can reside in two environments :
■​ The Oracle server
■​ Oracle tools.
○​ These two environments are independent.
○​ PL/SQL is bundled with the Oracle server but might be unavailable in
some tools.
○​ In either environment, the PL/SQL engine accepts as input any valid
PL/SQL block or subprogram.
○​ The figure shows the PL/SQL engine processing an anonymous block.
○​ The engine executes procedural statements but sends SQL
statements to the SQL Statement Executor in the Oracle server.

62.​ PL/SQL Data Types


○​ The default data types that we can declare in PL/SQL are
■​ Numeric - Numeric values on which arithmetic operations are
performed.
■​ Character - Alphanumeric values that represent single
characters or strings of characters.
■​ Boolean - Logical values on which logical operations are
performed.
■​ Datetime - Dates and times.
○​ number, char and date data types can have NULL values.

63.​ If Statement in PL/SQL


○​ PL/SQL allows decision making using if statement.
○​ An IF statement in PL/SQL looks like :
IF <condition> THEN
<statement_list>
END IF;
○​ If condition is true the statements present inside IF will get executed.
○​ If.... Else construct :
IF <condition> THEN
<statement_list>
ELSE
<statement_list>
END IF;
○​ In PL/SQL, the IF – THEN – ELSIF – ELSE – END IF construct in code
blocks allow specifying certain conditions under which a specific
block of code should be executed.
○​ Syntax:
​ ​ IF <Condition> THEN
<Action>
ELSEIF <Condition> THEN
<Action>
ELSE
<Action>
END IF;
○​ Ex.
○​ Accept two numbers and print the largest number
DECLARE
x number;
y number;
BEGIN
x :=&x;
y :=&y;
if (x>y) then
dbms_output.put_line(‘x is largest than y’);
else
dbms_output.put_line(‘y is largest than x’);
end if;
End;

Output:
7
5
x is largest than y

64.​ Loops in PL/SQL


A loop marks a sequence of statements that has to be repeated. The
keyword loop has to be placed before the first statement in the sequence of
statements to be repeated, while the keyword end loop is placed immediately
after the last statement in the sequence.
There are three types of loops in PL/SQL :
○​ Simple loop
■​ Syntax 1:
LOOP
<commands> /* A list of statements. */
if <codition> then
EXIT;
End if;
END LOOP;
The loop breaks if <condition> is true.
■​ Syntax 2:
LOOP
<commands> /* A list of statements. */
EXIT WHEN <condition>;
END LOOP;
The loop breaks when <condition> is true.
■​ Ex.
■​ DECLARE
​ num NUMBER := 0;
BEGIN
LOOP
num := num + 1;
dbms_output.put_line(num);
IF(num>=3) THEN
​ EXIT;
END IF;
END LOOP;
​ ​ ​ END;
​ ​ ​
​ ​ ​ Output:
​ ​ ​ 1
​ ​ ​ 2
​ ​ ​ 3

○​ For...loop
■​ Syntax:
FOR <var> IN [reverse] <start>. .<finish> LOOP
<commands> /* A list of statements. */
END LOOP;
■​ Here, <var> can be any variable; it is local to the for-loop and
need not be declared.
■​ Also, <start> and <finish> are constants.
■​ The value of a variable <var> is automatically incremented by 1.
■​ The commands inside the loops are automatically executed until
the final value of variable is reached.
■​ Reverse is optional part, when you want to go from maximum
value to minimum value in that case reverse is used.
■​ Ex.
BEGIN
For i in 1. .3 LOOP
dbms_output.put_line(i);
END LOOP;
END;

Output:
1​
2​
3
○​ While loop:
■​ Syntax:
WHILE <condition> LOOP
<commands> /* A list of statements. */
END LOOP;
■​ This loop executes the commands if the condition is true.
■​ Ex.
DECLARE
i NUMBER := 0;
BEGIN
While i<=3 LOOP
i := i+1;
dbms_output.put_line(i);
END LOOP;
END;

Output:
1
2
3
65.​ The GOTO statement
○​ The GOTO statement changes the flow of control within a PL/SQL
block.
○​ This statement allows execution of a section of code, which is not in
the normal flow of control.
○​ The entry point into such a block of code is marked using the tags
<<userdefined name>>.
○​ The GOTO statement can then make use of this user-defined name to
jump into that block for execution.
○​ Syntax:
GOTO <codeblock name> ;

66.​ Cursors
○​ Whenever a SQL statement is issued the Database server opens an
area of memory called Private SQL area in which the command is
processed and executed. An identifier for this area is called a cursor.
○​ There are two types of cursors.
■​ Implicit cursors - When the executable part of a PL/SQL block
issues a SQL command, PL/SQL creates an implicit cursor which
has the identifier SQL. PL/SQL internally manages this cursor.
■​ Explicit cursors - If SELECT statements in PL/SQL block return
multiple rows then you have to explicitly create a cursor which is
called an explicit cursor. The set of rows returned by an explicit
cursor is called a result set. The row that is being processed is
called the current row.
○​ Oracle uses four commands to handle Cursors. They are :
■​ DECLARE - Defines the name and structure of the cursor
together with the SELECT statement.Cursors are defined within a
DECLARE section of a PL/SQL block with DECLARE command.
Syntax to declare a Cursor:
Cursor cursor_name [(parameters)] [RETURN return_type]
IS SELECT query.
Parameter and return are optional parts. When parameters are
passed to the cursor it is called a parameterized cursor.
■​ OPEN - Cursors are opened with the OPEN statement, this
populates the cursor with data.
Syntax : OPEN Cursor_name[parameters];
■​ FETCH - To access the rows of data within the cursor the FETCH
statement is used.
Syntax: FETCH Cursor_name[parameters];
■​ CLOSE - The CLOSE statement releases the cursor and any rows
within it, you can open the cursor again to refresh the data in it.
Syntax: CLOSE cursor_name;
○​ Ex.,
CURSOR c1
IS
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;
The result set of this cursor is all course_numbers whose
course_name matches the variable called name_in.

67.​ SQL Cursor Attributes


○​ PL/SQL provides some attributes which allows to evaluate what
happened when the cursor was last used.
○​ You can use these attributes in PL/SQL statements like functions but
you cannot use them within SQL statements.
○​ The SQL cursor attributes are :
■​ %ROWCOUNT : The number of rows processed by a SQL
statement.
■​ %FOUND : TRUE if at least one row was processed.
■​ %NOTFOUND : TRUE if no rows were processed.
■​ %ISOPEN : TRUE if cursor is open or FALSE if cursor has not
been opened or has been closed. Only used with explicit
cursors.

68.​ Exception(error) Handling in PL/SQL


○​ The Exception section in PL/SQL block is used to handle an error that
occurs during the execution of PL/SQL program.
○​ If an error occurs within a block PL/SQL passes control to the
EXCEPTION section of the block.
○​ If no EXCEPTION section exists within the block or the EXCEPTION
section does not handle the error that's occurred then the error is
passed out to the host environment.
○​ Exceptions occur when either an Oracle error occurs (this
automatically raises an exception) or you explicitly raise an error or a
routine that executes corrective action when detecting an error.
○​ Thus Exceptions are identifiers in PL/SQL that are raised during the
execution of a block to terminate its action.
○​ There are two classes of exceptions, these are :
■​ Predefined exception - Oracle predefined errors which are
associated with specific error codes.
■​ User-defined exception - Declared by the user and raised when
specifically requested within a block.
○​ PL/SQL provides two special functions for use within an EXCEPTION
section, they are:
■​ SQLCODE - SQLCODE is the Oracle error code of the exception
■​ SQLERRM - SQLERRM is the Oracle error message of the
exception.
○​ You can use these functions to detect what error has occurred (very
useful in an OTHERS action).
○​ This is generally used to store errors occurs in PL/SQL program in
table so SQLCODE and SQLERRM should be assigned to variables
before you attempt to use them.
○​ Ex. of a Exception block using SQLCODE & SQLERRM
WHEN OTHERS THEN
ERR_CDE := SQLCODE;
ERR_MSG := SUBSTR(SQLERRM,1,100);
INSERT INTO ERRORS (CODE, MESSAGE) VALUES(ERR_CDE,
ERR_MSG);

69.​ Pre-defined Exceptions in PL/SQL


○​ Oracle predefined errors which are associated with specific error
codes.
○​ The two most common errors originating from a SELECT statement
occur when it returns no rows or more than one row (remember that
this is not allowed in PL/SQL select command).
○​ If no rows are selected from SELECT statement then WHEN
NO_DATA_FOUND exception is used and for more than one row WHEN
TOO_MANY_ROWS exception is used.
○​ To cover all possible errors other than this, use WHEN OTHERS
exception.
○​ Ex.
DECLARE
TEMP_Sal NUMBER(10,2);
BEGIN
SELECT sal INTO TEMP_sal
From emp
WHERE empno>=7698;
IF TEMP_sal > 1000 THEN
UPDATE emp SET sal = (TEMP_sal*1.175)
WHERE empno>=7698;
ELSE
UPDATE emp SET sal = 5000
WHERE empno>=7698;
END IF;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
Dbms.Output.put_line(‘Empno does not exists’);
WHEN TOO_MANY_ROWS THEN
Dbms.Output.put_line(‘No. of rows selected’);
WHEN OTHERS THEN
Dbms.Output.put_line(‘SOME ERROR OCCURRED’);
END;
This block will trap all errors. If the exception is not no rows returned
or too many rows returned then the OTHERS action will perform the
error handling

70.​ User Defined Exceptions in PL/SQL


○​ Declared by the user and raised when specifically requested within a
block. You can associate a user-defined exception with an error code
if you wish.
○​ There are two methods of defining exception by user.
■​ RAISE statement - If you explicitly need to raise an error then
RAISE statement is used and you have to declared an exception
variable in declared section.
■​ Ex.
DECLARE
TEMP_Sal NUMBER(10,2);
NEGATIVE_SAL EXCEPTION;
BEGIN
SELECT sal INTO TEMP_Sal
From emp
WHERE empno=7698;
IF TEMP_Cal < 0 THEN
Raise NEGATIVE_SAL;
ELSE
UPDATE emp SET Sal = 5000
WHERE empno=7698;
END IF;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line(‘Record NOT FOUND’);
WHEN NEGATIVE_SAL THEN
dbms_output.put_line(‘Salary is negative’);
END;
If the above example find row with an Sal less than 0 then
PL/SQL raise user_defined Negative_Sal exception.
■​ RAISE_APPLICATION_ERROR statement - The
RAISE_APPLICATION_ERROR takes two input parameters : The
error number and error message. The error number must be
between –20001 to –20999. You can call
RAISE_APPLICATION_ERROR from within procedures, functions,
packages and triggers.
■​ Ex.
DECLARE
TEMP_Sal NUMBER(10, 2);
BEGIN
SELECT sal INTO TEMP_sal
From emp
WHERE empno=7698;
UPDATE emp SET sal = TEMP_sal *1.5
WHERE empno=7698;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR (–20100,‘Record NOT
FOUND’);
END;
■​ In this case exception variable declaration is not required.

71.​Triggers
○​ A trigger is PL/SQL code block which is executed by an event which
occurs to a database table.
○​ Triggers are implicitly invoked when INSERT, UPDATE or DELETE
command is executed.
○​ A trigger is associated with a table or a view. When a view is used, the
base table triggers are normally enabled.
○​ Triggers are stored as text and compiled at execute time, because of
this it is wise not to include much code in them. You may not use
COMMIT, ROLLBACK and SAVEPOINT statements within trigger
blocks.
○​ The advantages of using trigger are :
■​ It creates consistency and access restrictions to the database.
■​ It implements security.
○​ A trigger is created with CREATE TRIGGER command.
Syntax:
​ CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE / AFTER / INSTEAD OF}
{DELETE /INSERT/UPDATE [OF column [,column....]}
ON {TABLE/VIEW}
FOR EACH {ROW / STATEMENT}
[WHEN (condition)]
PL/SQL block
○​ The BEFORE trigger is used when some processing is needed before
execution of the command. The AFTER trigger is triggered only after
the execution of the associated triggering commands. INSTEAD OF
trigger is applied to view only.
○​ Triggers may be called BEFORE or AFTER the following events :
INSERT, UPDATE and DELETE.
○​ Thus every trigger is divided into three components as :
■​ Triggering event - The trigger can be activated by a SQL
command or by system event or a user event which are called
triggering events.
■​ Triggering restriction - WHEN clause is used to specify
triggering restriction i.e. it specifies what condition must be true
for the trigger to be activated.
■​ Triggering action - PL/SQL block is a trigger action.
○​ A trigger can be modified using OR REPLACE clause of CREATE
TRIGGER command.
○​ A value of a column of a ROW-LEVEL trigger can be accessed using
NEW and OLD variable.
Syntax :
Column_name : NEW
Column_name : OLD
○​ To enable or disable a specific trigger, ALTER TRIGGER command is
used.
Syntax :
ALTER TRIGGER trigger_name ENABLE / DISABLE ;
○​ When a trigger is created, it is automatically enabled and it gets
executed according to the triggering command.
○​ To enable or disable all the triggers of a table, ALTER TABLE command
is used.
Syntax :
ALTER TABLE table_name ENABLE / DISABLE ALL TRIGGERS;
○​ To delete a trigger, use DROP TRIGGER command.
Syntax :
DROP TRIGGER trigger_name;
○​ Ex.
​ ​ CREATE TRIGGER tr_sal
BEFORE INSERT ON emp
FOR EACH ROW
BEGIN
IF :new.sal = 0 THEN
Raise_application_error('-20010','Salary should be greater than 0');
END IF;
END;

72.​ Different types of Triggers


Triggers may be ROW or STATEMENT types:
○​ ROW type trigger which is also called as ROW level trigger is executed
on all the rows that are affected by the command.
○​ STATEMENT type trigger (STATEMENT level trigger) is triggered only
once. For example if an DELETE command deletes 15 rows, the
commands contained in the trigger are executed only once and not
with every processed row.

73.​ Define Triggering Events


○​ The trigger can be activated by a SQL command or by system event
or a user event which are called triggering events.
○​ The different types are:
■​ TABLE triggers : Applied to DML commands (INSERT / DELETE /
UPDATE).
■​ SYSTEM EVENT triggers : Such as startup, shutdown of the
database and server error message event.
■​ USER EVENT triggers : Such as User logon and logoff, DDL
commands (CREATE, ALTER, DROP),

74.​ Short note on NoSQL


○​ NoSQL is a non-relational Database management system.
○​ The NoSQL database is used for distributed data stores with
humongous data storage need. NoSQL is used for Big Data and
real-time web apps.
○​ It is designed for distributed data stores with very large scale of data
storing needs. These types of data storing may not require fixed
schema, avoid join operations and typically scale horizontally.
○​ NoSQL database stands for “Not Only SQL” or “Not SQL” or “Not
Structured”
○​ Key Features of NoSQL
■​ Dynamic schema: NoSQL databases do not have a fixed schema
and can accommodate changing data structures without the
need for migrations or schema alterations.
■​ Horizontal scalability: NoSQL databases are designed to scale
out by adding more nodes to a database cluster, making them
well-suited for handling large amounts of data and high levels of
traffic.
■​ Document-based: Some NoSQL databases, such as MongoDB,
use a document-based data model, where data is stored in a
scales semi-structured format, such as JSON or BSON.
■​ Key-value-based: Other NoSQL databases, such as Redis, use a
key-value data model, where data is stored as a collection of
key-value pairs.
■​ Column-based: Some NoSQL databases, such as Cassandra,
use a column-based data model, where data is organized into
columns instead of rows.
■​ Distributed and high availability: NoSQL databases are often
designed to be highly available and to automatically handle node
failures and data replication across multiple nodes in a database
cluster.
■​ Flexibility: NoSQL databases allow developers to store and
retrieve data in a flexible and dynamic manner, with support for
multiple data types and changing data structures.
■​ Performance: NoSQL databases are optimized for high
performance and can handle a high volume of reads and writes,
making them suitable for big data and real-time applications

75.​ Advantages of NoSQL


○​ High scalability: NoSQL databases use sharding for horizontal scaling.
Partitioning of data and placing it on multiple machines in such a way
that the order of the data is preserved is sharding. Vertical scaling
means adding more resources to the existing machine whereas
horizontal scaling means adding more machines to handle the data.
○​ Flexibility: NoSQL databases are designed to handle unstructured or
semi-structured data, which means that they can accommodate
dynamic changes to the data model.
○​ They offer scalability for larger data sets, which are common in
analytics and artificial intelligence (AI) applications.
○​ NoSQL databases are better suited for cloud, mobile, social media and
big data requirements.
○​ They are designed for specific use cases and are easier to use than
general-purpose relational or SQL databases for those types of
applications

76.​ Disadvantages of NoSQL


The disadvantages of using a NoSQL database include the following:
○​ Each NoSQL database has its own syntax for querying and managing
data. This is in contrast to SQL, which is the lingua franca for relational
and SQL database systems.
○​ Lack of a rigid database schema and constraints removes the data
integrity safeguards that are built into relational and SQL database
systems.
○​ A schema with some sort of structure is required in order to use the
data. With NoSQL, this must be performed by the application
developer instead of the database administrator.
○​ Because NoSQL databases are newer, there are no comprehensive
industry standards as with relational and SQL DBMS offerings

77.​ Explain the types of NoSQL


There are four basic types of NoSQL databases
○​ Key-Value Databases
■​ It has a big hash table of keys and values
■​ Ex. Riak, Tokyo Cabinet, Redis server, Memcached and Scalaris
○​ Document-based databases
■​ It stores documents made up of tagged elements
■​ Ex. MongoDB, CouchDB, OrientDB and RavenDB
○​ Column-based database
■​ Each storage block contains data from only one column
■​ Ex. BigTable, Cassandra, Hbase and Hypertable
○​ Graph-based database
■​ A graph based database is a network database that uses nodes
to represent and store data
■​ Ex. Neo4J, InfoGrid, Infinite Graph and FlockDB

78.​ Types of Data


Data can be structured, semi-structured and unstructured.
○​ Structured Data:
■​ It is the type of data that fits nicely into a relational database.
■​ Its highly organized and easily analyzed
■​ Comprised of clearly defined data types whose patter akes them
easily searchable
■​ Ex. Dates, Phone Numbers, ZIP codes, Customer Names etc
■​ Its inherent structure and orderliness makes it simple to query
and analyze.
■​ Common applications that rely on structured data in relational
databases include CRM, ERP and POS systems
○​ Semi-Structured Data
■​ It is information that does not reside in a relational database but
that have some organizational properties that make it easier to
analyze.
■​ With some process, you can store them in the relational
database
■​ Ex. XML data
■​ Many big data solutions and tools have the ability to “read” and
process either JSON or XML. This reduces the complexity to
analyse structured data, compared to unstructured data
○​ Unstructured Data
■​ It has internal structure but is not structured via pre-defined data
models or schema.
■​ It may be textual or non textual and human or machine
generated.
■​ It may also be stored within a non relational database like NoSQL
■​ Ex. Text Files, Media files, Satellite images, Sensor Data etc.

79.​ Difference between SQL vs NoSQL


SQL NoSQL

SQL is primarily a Relational NoSQL is non-relational or


Database Distributed Database

Table base databases Document based, key value pairs,


graph databases or wide column
databases

Have predefined schema Have dynamic schema for


unstructured data

Vertically scalable Horizontally scalable

Best suited for complex queries Not so good for complex queries
Not suited for hierarchical data Best suited for hierarchical data
storage storage

SQL databases emphasizes on ACID NoSQL database follows the


properties (Atomicity, Consistency, Brewers CAP theorem (Consistency,
Isolation and Durability) Availability, and Partition tolerance)

Ex. MySQL, Oracle, SQLite, Ex. MongoDB, BigTable, Redis,


Postgres, MS-SQL RavenDB, Cassandra, HBase, Neo4j
and CouchDB

80.​ Explain Brewers CAP Theorem


○​ The CAP theorem, also known as Brewer's theorem, is a fundamental
principle in distributed systems that states that it is impossible for a
distributed data system to simultaneously provide all three of the
following guarantees:
○​ Consistency ( C ) - The data should remain consistent even after the
execution of an operation. This means once the data is written, any
future read request should contain that data. For example, after
updating the order status, all the clients should be able to see the
same data.
○​ Availability ( A ) - The database should always be available and
responsive. It should not have any downtime
○​ Partition Tolerance ( P ) - Partition Tolerance means that the system
should continue to function even if the communication among the
servers is not stable. For example, the servers can be partitioned into
multiple groups which may not communicate with each other. Here, if
part of the database is unavailable, other parts are always unaffected.

81.​ Explain Big Data


○​ Big data refers to large volumes of structured, semi-structured, and
unstructured data that inundates businesses on a day-to-day basis.
○​ This data comes from a wide variety of sources, including sensors,
social media, mobile devices, websites, transactions, and more.
○​ Big data is characterized by the three Vs:
■​ Volume: Big data involves vast amounts of data, typically ranging
from terabytes to petabytes and beyond. Traditional data
processing techniques and tools are often inadequate for
handling such massive volumes of data
■​ Velocity: Big data is generated and collected at high speeds.
Data streams in continuously and needs to be processed,
analyzed, and acted upon in real-time or near-real-time to derive
value from it. Examples include social media feeds, sensor data,
and financial transactions.
■​ Variety: Big data comes in various formats, including structured
data (e.g., relational databases), semi-structured data (e.g.,
XML, JSON), and unstructured data (e.g., text, images, videos).
This diverse mix of data types poses challenges for storage,
processing, and analysis
○​ In addition to the three Vs, two more Vs are often added to
characterize big data:
■​ Variability: Big data exhibits inconsistency or fluctuations in data
flow and formats. The data may be inconsistent in quality, arrive
at irregular intervals, or vary significantly in structure and
content.
■​ Veracity: Big data can include data of uncertain quality,
accuracy, and reliability. Veracity refers to the trustworthiness of
the data and the ability to ensure data integrity, correctness, and
validity

82.​ Short note on Embedded SQL


83.​ Short note on Dynamic SQL
○​ Dynamic SQL component of SQL - 92 allows programs to construct
and submit SQL queries at run-time.
○​ Using dynamic SQL programs can create SQL queries as strings at run
time and can execute them immediately or prepare them for
subsequent use.
○​ Preparing a dynamic SQL statement compiles it, and subsequent uses
of the prepared statement use the compiled version.
○​ It is mainly used to write the general-purpose and flexible programs
where the SQL statements will be created and executed at run-time
based on the requirement.

You might also like