0% found this document useful (0 votes)
7 views57 pages

SQL UNIT-II Name

Uploaded by

Harini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views57 pages

SQL UNIT-II Name

Uploaded by

Harini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 57

SQL – BASICS AND ADVANCED – PL/SQL

UNIT II STRUCTURED QUERY LANGUAGE

Basics of SQL, DDL, DML,DCL,TCL – creation, alteration, defining constraints – Functions – aggregate
functions, Built-in functions – Views – Joins – Procedure

1. SQL FUNDAMENTALS
IBM developed the original version of SQL, originally called Sequel, as part of the System R project in
the early 1970s. The Sequel language has evolved since then, and its name has changed toSQL (Structured
Query Language)

1.1 Data Definition Language (DDL)

The Data Definition Language is used to define the overall schema of the database. The DDL is also used
to specify additional properties of the data. DDL deals with database schemas and descriptions, of how the
data should reside in the database.

Example of DDL are:


• CREATE : to create database
• ALTER : alters the structure of the existing database
• DROP : delete objects from the database
• TRUNCATE : remove all records from a table, including all spaces allocated for therecords
are removed
• RENAME: Used to rename a relation

SQL Basic Data Types


The SQL standard supports a variety of built-in types, including:
• char(n): A fixed-length character string with user-specified length n. The full form,
character, can be used instead.
• varchar(n): A variable-length character string with user-specified maximum length n. The fullform,
character varying, is equivalent.
• int: An integer (a finite subset of the integers that is machine dependent). The full form,
integer, is equivalent.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 1


SQL – BASICS AND ADVANCED – PL/SQL

• smallint: A small integer (a machine-dependent subset of the integer type).


• numeric(p, d): A fixed-point number with user-specified precision. The number consists of p digits
(plus a sign), and d of the p digits are to the right of the decimal point. Thus, numeric(3,1) allows 44.5
to be stored exactly, but neither 444.5 or 0.32 can be stored exactly ina field of this type.
• real, double precision: Floating-point and double-precision floating-point numbers withmachine-
dependent precision.
• float(n): A floating-point number, with precision of at least n digits.

CREATE:
It is used to create a table or relation.
Syntax :
CREATE TABLE tablename (A1 D1, A2 D2, . . . ,An Dn, <integrity-constraint1>, . . .
,<integrity-constraintk)>);where
tablename - the name of the table
Ai - the attribute name
Di - the domain(data type ) of the attribute integrity-constrainti – data integrity constraint name

Integrity Constraints:
Integrity Constraints enforce rules on the data in a table whenever a row is inserted, updated, or deleted
from that table. The constraint must be satisfied for the operation to succeed. It prevent the deletion of a
table if there are dependencies from other tables

Primary Key Constraint: The Primary Key constraint uniquely identifies each record in a table. Primary
keys must contain unique values, and cannot contain NULL values. A table can have only one primary key,
which may consist of single or multiple fields.

Foreign Key Constraint: A foreign key is a key used to link two tables together. A foreign key is afield
(or collection of fields) in one table that refers to the primary key in another table. The table containing the
foreign key is called the child table, and the table containing the candidate key is called the referenced or
parent table.

Unique Constraint: The unique constraint ensures that all values in a column are different. Boththe
unique and primary key constraints provide a guarantee for uniqueness for a column or set of columns. A
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 2
SQL – BASICS AND ADVANCED – PL/SQL

primary key constraint automatically has a unique constraint.

NOT NULL Constraint: The NOT NULL constraint enforces a column to not accept NULL values. This
enforces a field to always contain a value, which means that you cannot insert a new record, or update a
record without adding a value to this field

Check Constraint: The check constraint is used to limit the value range that can be placed in a column.
Default Constraint: The default constraint is used to provide a default value for a column.

Example
CREATE TABLE Employee ( Eid
int,
Name varchar(255) NOT NULL,
Designation varchar(255), Salary int ,
check(Salary>0),
Phno varchar(255) , PRIMARY KEY(Eid)
);
Result:
Table created.
To view the structure of the table, DESCRIBE table_name
DESCRIBE Employee

Name NULL Type


Eid int
Name NOT NULL varchar(255)
Designation varchar(255)
Salary Int
Phno varchar(255)

ALTER :
The alter table statement is used to add, delete, or modify columns in an existing table.
Add Clause:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 3


SQL – BASICS AND ADVANCED – PL/SQL

The new column becomes the last column. If a table already contains rows when a column is added, then
the new column is initially null for all the rows.
Modify Clause:
Column modification can include changes to a column’s data type, size, and default value. the data type is
changed only if the column contains null values. A change to the default value of a column affects only
subsequent insertions to the table.
Drop Clause:
only one column can be dropped at a time. The table must have at least one column remaining in it after it
is altered. Once a column is dropped, it cannot be recovered.
Syntax:
ALTER TABLE table_name ADD|MODIFY column_name datatype;
ALTER TABLE table_name DROP column_name;
Where,
table_name - the name of the table
column_name – name of the attribute
datatype – domain of the attribute Example
1:

ALTER TABLE employee ADD (Address varchar(255));


Result:
Table Altered.
DESCRIBE Employee

Name NULL Type


Eid int
Name NOT NULL varchar(255)
Designation varchar(255)
Salary Int
Phno varchar(255)
Address varchar(255)

Example 2:
ALTER TABLE employee DROP Address;
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 4
SQL – BASICS AND ADVANCED – PL/SQL

Result:
Table Altered.
DESCRIBE Employee

Name NULL Type


Eid int
Name NOT NULL varchar(255)
Designation varchar(255)
Salary Int
Phno varchar(255)

DROP :

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 5


SQL – BASICS AND ADVANCED – PL/SQL

The DROP TABLE statement is used to drop an existing table in a database. The drop command
deletes the entire table along with its content. The DROP TABLE statement cannot beroll backed.
Syntax:
DROP TABLE table_name;

Example:

DROP TABLE Employee;


Result:
Table Dropped.
DESC Employee;
No table found

RENAME :
It is used to rename a table.

Syntax

RENAME old_name TO new_name;


Where,

old_name - the old name of the table, view, sequence, or synonym. new_name

- the new name of the table, view, sequence, or synonym.


Example:
RENAME Employee TO emp;
Result:
Table Renamed.

TRUNCATE :
Truncate is used to remove all rows from a table and to release the storage space used by that
table.It does not delete the table. The removed rows can not be roll backed.

Syntax:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 6


SQL – BASICS AND ADVANCED – PL/SQL

TRUNCATE TABLE table_name;

Example:
TRUNCATE TABLE Employee.

1.2 Data-Manipulation Language(DML)

A data manipulation language (DML) is a language that enables users to access or manipulate data
as organized by the appropriate data model.
DML commands are not auto-committed. It means that the changes are not permanent to database,
they can be rolled back. Data manipulation is retrieval of information, insertion of new information,
deletion of information or modification of information stored in the database.
DML statements are :

1.2.1.1 SELECT : retrieve data from the database


1.2.1.2 INSERT : insert data into a table
1.2.1.3 UPDATE : updates existing data in a table
1.2.1.4 DELETE : delete all records from a database
tableThere are two types of DML :
1. Procedural DML : it requires a user to specify what data are needed and how to get those
data.
2. Non-Procedural DML : it requires a user to specify what data are needed without
specifying how to get those data.

The basic structure of an SQL query consists of three clauses: select, from, and where. The query
takes as its input the relations listed in the from clause, operates on them as specified in the where
and select clauses, and then produces a relation as the result. The select clause is used to list the
attributes desired in the result of a query. The from clause is a list of the relations to be accessed in
the evaluation of the query. The where clause is a predicate involving attributes of the relation in the
from clause.

SELECT:

The select statement is used to select data from a database.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 7


SQL – BASICS AND ADVANCED – PL/SQL

Syntax:

SELECT * | { [DISTINCT] column|expression [alias],...}FROM table_name [WHERE condition(s)]


[GROUP BY group_by_expression] [HAVING group_condition][ORDER BYcolumn];

Where,
* - selects all columns
DISTINCT - suppresses duplicates
column|expression - selects the named column or the expression
alias - gives selected columns different headings
Where Clause : restricts the query to rows that meet a
condition Group by -

Example :
Consider the relation Employee

Eid Name Designation Salary Phno


125 Kumar Developer 25000 9489562312
128 Raju Accountant 27500 9557886321
568 Sachin HR 33000 8561234568
895 Dravid Developer 45070 7288635241
222 Dhoni Accountant 39650 8956235689

Query: Select * from Employee;


Result:

Eid Name Designation Salary Phno


125 Kumar Developer 25000 9489562312
128 Raju Accountant 27500 9557886321
568 Sachin HR 33000 8561234568
895 Dravid Developer 45070 7288635241
222 Dhoni Accountant 39650 8956235689

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 8


SQL – BASICS AND ADVANCED – PL/SQL

Query: Select Name, Salary from Employee;


Result:
Name Salary
Kumar 25000
Raju 27500
Sachin 33000
Dravid 45070
Dhoni 39650

Where Clause
It Restrict the rows returned by select statement.
Comparison Conditions:
= - Equal to
> - Greater than
>= - Greater than or equal to
< - Less than
<= - Less than or equal to
<> - Not equal to
BETWEEN - Between two values (inclusive)
IN(set) - Match any of a list of values (%)
LIKE - Match a character pattern
IS NULL - Is a null value
Logical Conditions:
AND - if all the conditions separated by AND is TRUE
OR - if any of the conditions separated by OR is TRUE

NOT - if the condition(s) is NOT TRUE


Rules of Precedence:
Arithmetic operators
Concatenation operator

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 9


SQL – BASICS AND ADVANCED – PL/SQL

Comparison conditions
IS [NOT] NULL, LIKE, [NOT] IN
NOT] BETWEEN
NOT logical condition
AND logical condition
OR logical condition

Query: Select Name, Salary from employee where Salary between 27500 and 40000
Result:

Name Salary
Raju 27500
Sachin 33000
Dhoni 39650

Query: Select Name, Designation, Salary from Employee where Salary>25000 and
Designation=’Developer’;
Result:

Name Designation Salary


Dravid Developer 45070

Query: Select Eid, Name, Designation from Employee where Name like ‘D%’

Eid Name Designation


895 Dravid Developer
222 Dhoni Accountant

Aggregate Functions
Aggregate functions are functions that take a collection of values as input and return a single
value. SQL offers five built-in aggregate functions:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 10


SQL – BASICS AND ADVANCED – PL/SQL

• avg- returns the average value of a numeric column.


• min- returns the smallest value of the selected column.
• max- returns the largest value of the selected column.
• sum- returns the total sum of a numeric column.
• count- returns the number of rows that matches a specified criteria.

Example:
Query :Select min(Salary) from Employee;
Result:
Min(Salary)
25000

Query: Select avg(Salary) from Employee where designation=’Accountant’;


Result: shows the average salary of employees with the designation Accountant

Avg(Salary)
33575

Group By Clause:

the GROUP BY clause to divide the rows in a table into groups. The attribute or attributes given
in the group by clause are used to form groups. By default, rows are sorted by ascending order of the
columns included in the GROUP BY list.

Query: select Designation, avg(Salary) from Employee group by Designation;


Result:

Designation Avg(Salary)
Accountant 33575.0
Developer 36250
HR 33000

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 11


SQL – BASICS AND ADVANCED – PL/SQL

Having Clause:
The HAVING clause is used to restrict groups. The groups that match the criteria in the HAVING
clause are displayed.
Query:
Select Designation, avg(Salary) as avg from Employee group by Designation having
avg(Salary)>34000;
Result:

Designation Avg
Developer 36250

INSERT:

It is used to insert a new row that contains values for each column. Only one row is inserted ata
time.

Syntax:
INSERT INTO table (column1, coulmn2, column3,) VALUES (value1, value2, value3, ...);.
If the order of the values is in the same order as the columns in the table
INSERT INTO table_name VALUES (value1, value2, value3, ...);

Example
Query:
Insert into Employee(Eid, Designation, Name, Salary, Phno)values(587,’Designer’,’Walter’,32570,
‘8978567780’)
Result:
1 row created.

Eid Name Designation Salary Phno

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 12


SQL – BASICS AND ADVANCED – PL/SQL

125 Kumar Developer 25000 9489562312


128 Raju Accountant 27500 9557886321
568 Sachin HR 33000 8561234568
895 Dravid Developer 45070 7288635241
222 Dhoni Accountant 39650 8956235689
587 Walter Designer 32570 8978567780

UPDATE :

The UPDATE command is used to modify attribute values of one or more selected tuples.
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2, ...WHERE condition;

Example:
Query:
Update Employee set salary=43575 where Eid=587;
Result:
1 row updated.

Eid Name Designation Salary Phno


125 Kumar Developer 25000 9489562312
128 Raju Accountant 27500 9557886321
568 Sachin HR 33000 8561234568
895 Dravid Developer 45070 7288635241
222 Dhoni Accountant 39650 8956235689
587 Walter Designer 43575 8978567780

DELETE:
The DELETE statement is used to delete existing records in a table. The delete operation is not made
permanent until the data transaction is committed. Ift the WHERE clause is omitted, all rows in the
table are deleted.

Syntax:
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 13
SQL – BASICS AND ADVANCED – PL/SQL

DELETE FROM table_name WHERE condition;

Example:
Query:
Delete from Employee where EID=587
Result:
1 row deleted.

Eid Name Designation Salary Phno


125 Kumar Developer 25000 9489562312
128 Raju Accountant 27500 9557886321
568 Sachin HR 33000 8561234568
895 Dravid Developer 45070 7288635241
222 Dhoni Accountant 39650 8956235689

Query:
Delete from Employee;
Result:
5 row deleted.

1.3 Transaction Control Language(TCL)


TCL commands are to keep a check on other commands and their affect on the database. These
commands can annul changes made by other commands by rolling back to original state. It can also
make changes permanent.
TCL Statements are:
COMMIT : to permanently save
ROLLBACK : to undo change
SAVEPOINT : to save temporarily
COMMIT:
It makes the change permanent.
Example:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 14


SQL – BASICS AND ADVANCED – PL/SQL

Query:
Delete from Employee where EID=587
Result: Remove Employee 587 in the Employee table.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 15


SQL – BASICS AND ADVANCED – PL/SQL

1 row deleted.
Query:
Commit;
Result: makes the change permanent
Commit complete.

ROLLBACK:
Data changes are undone. The previous state of the data is restored.
Example:
Query:
DELETE FROM Employee;
Result :all rows in the employee table is deleted
5 rows deleted.
Query:
ROLLBACK;
Result: deleted rows in the employee table is Roll backed.

SAVEPOINT:
It is used to create a marker in the current transaction which divides the transaction into smaller
sections. Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.
Query:
Delete from Employee where EID=587
Result: Remove Employee 587 in the Employee table.
1 row deleted.
Query:
savepoint A
Result:
Savepoint created.

Query:
Delete from Employee where EID=222
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 16
SQL – BASICS AND ADVANCED – PL/SQL

Result: Remove Employee 222 in the Employee table.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 17


SQL – BASICS AND ADVANCED – PL/SQL

1 row deleted.
Query:
ROLLBACK TO A;
Result:
Rollback complete.

Eid Name Designation Salary Phno


125 Kumar Developer 25000 9489562312
128 Raju Accountant 27500 9557886321
568 Sachin HR 33000 8561234568
895 Dravid Developer 45070 7288635241
587 Walter Designer 43575 8978567780

1.4 Data Control Language (DCL)

It is used to control database access. It gives access to specific objects in the database. Roles,
permissions, and referential integrity are created using data control language. Users can be given the
privileges to access database. Two types of privileges are there.
System Privilege :
More than 100 distinct system privileges are available for users and roles. System privileges
typically are provided by the database administrator.
Example:
CREATE SESSION
CREATE TABLE
CREATE SEQUENCE
CREATE VIEW
CREATE PROCEDURE
Object Privilege:
An object privilege is a privilege or right to perform a particular action on a specific table, view,
sequence, or procedure.
Example:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 18


SQL – BASICS AND ADVANCED – PL/SQL

ALTER

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 19


SQL – BASICS AND ADVANCED – PL/SQL

DELETE
EXECUTE
INDEX
INSERT
REFERENCES
SELECT
UPDATE

DCL statements:
GRANT
REVOKE

Create user:
The DBA creates users by using the CREATE USER statement.
Syntax:
CREATE USER user_name IDENTIFIED BY password;
Example:
Query:
CREATE USER Student IDENTIFIED BY welcome;
Result:
User created.
Where, user name is Student and the password is welcome.

Role:
A role is a named group of related privileges that can be granted to the user. This method makes it easier
to revoke and maintain privileges. The DBA must create the role. Then the DBA can assignprivileges
to the role and users to the role.
Create role:
Syntax:
CREATE ROLE role;
Example:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 20


SQL – BASICS AND ADVANCED – PL/SQL

CREATE ROLE Manager;

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 21


SQL – BASICS AND ADVANCED – PL/SQL

Role created.
GRANT:
Database Administrator (DBA) can grant specific privileges to a user or role. DBA can create userand
role. Then the privilege is granted.

Grant System Privilege to user:


Syntax:
GRANT privilege [, privilege...]TO user [, user| role, PUBLIC...];
Example:
Query:
GRANT create session, create table, create sequence, create view TO Student;
Result:
Grant succeeded.
For the student user, privileges (create session, create table, create sequence, create view ) are
granted.
Grant privileges to a role:
Syntax:
GRANT privilege(s) TO role_name;
Example:
GRANT create table, create view TO manager;
Grant succeeded.
Grant a role to users:
Syntax:
GRANT role_name TO user_name;
Example:
GRANT manager TO Student;
Result:
Grant succeeded.

create table, create view privileges are granted to the user student.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 22


SQL – BASICS AND ADVANCED – PL/SQL

Grant Object privilege to user:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 23


SQL – BASICS AND ADVANCED – PL/SQL

Syntax:
GRANT object_priv [(columns)] ON object TO {user|role|PUBLIC} [WITH GRANT OPTION];
Example:
GRANT select ON Employee TO Student;
Grant succeeded.
REVOKE:
The REVOKE statement is used to revoke privileges granted to other users.
Syntax:
REVOKE {privilege [, privilege...]|ALL} ON object FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];
Example:
REVOKE select ON Employee FROM Student;
Revoke succeeded.

CONSTRAINTS:

Constraints are the rules enforced on the data columns of a table. These are used to limit the type of
data that can go into a table. This ensures the accuracy and reliability of the data in the database.

Constraints could be either on a column level or a table level. The column level constraints are applied
only to one column, whereas the table level constraints are applied to the whole table.

Following are some of the most commonly used constraints available in SQL:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 24


SQL – BASICS AND ADVANCED – PL/SQL

1. Domain Constraint
a. Domain of an attribute specifies all the possible values that attribute can hold
b. It defines the domain or set of values for an attribute
c. It specifies that the value taken by the attribute must be the atomic (can’t be divided)
value from its domain
d. It contains
i. NOT NULL constraint
ii. CHECK constraint

2. Tuple Uniqueness Constraint


a. It specifies that all the tuples must be necessarily unique in any relation.
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 25
SQL – BASICS AND ADVANCED – PL/SQL

The above relation satisfies Tuple Uniqueness Constraint since all attributes are unique

The above relation does not satisfies Tuple Uniqueness Constraint since all attributes are not unique
3. Key Constraint
a. All the values of primary key must be unique.
b. The value of primary key must not be null.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 26


SQL – BASICS AND ADVANCED – PL/SQL

The above relation does not satisfies Tuple Uniqueness Constraint since all attributes are not unique

4. Entity Integrity Constraint


a. It specifies that no attribute of primary key must contain a null value in any relation.
b. This is because the presence of null value in the primary key violates the uniqueness
property.

The above relation does not satisfy Entity Integrity Constraint as here the Primary Key contains a NULL
value.
5. Referential Integrity Constraint
a. This constraint is enforced when a foreign key references the primary key of a relation.
b. It specifies that all the values taken by the foreign key must either be available in the
relation of the primary key or be null.
c. We can not insert a record into a referencing relation if the corresponding record does
not exist in the referenced relation.
d. We can not delete or update a record of the referenced relation if the corresponding
record exists in the referencing relation.
Eg : Consider two relations ‘student’ and ‘Department’
Here relation ‘student’ references the relation ‘Department’

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 27


SQL – BASICS AND ADVANCED – PL/SQL

Here,

• The relation ‘Student’ does not satisfy the referential integrity constraint.
• This is because in relation ‘Department’, no value of primary key specifies department no. 14.
• Thus, referential integrity constraint is violated.
Constraint and its creation:

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 28


SQL – BASICS AND ADVANCED – PL/SQL

1. NOT NULL :
• Values cannot be NULL
• A NULL is not the same as no data, rather, it represents unknown data.
Eg : CREATE TABLE STUDENTS(
ROLL_NO INT NOT NULL,
NAME VARCHAR (20) ,
AGE INT,
PHONE INT);
• To add NOT NULL constraint to an existing table
ALTER TABLE STUDENTS
MODIFY AGE INT NOT NULL;

2. DEFAULT :
• Set Default Value if not passed
• It provides a default value to a column when the INSERT INTO statement does not provide a
specific value.
Eg : CREATE TABLE CUSTOMERS(
ID_NO INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
COMPANY CHAR (25) ,
COMPANY VARCHAR (18) DEFAULT ‘Prepinsta’);
• To add DEFAULT constraint to an existing table
ALTER TABLE CUSTOMERS MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 29


SQL – BASICS AND ADVANCED – PL/SQL

3. UNIQUE :
• Values cannot match any older values
• It prevents two records from having identical values in a column but accepts NULL values
• It is similar to primary key i.e., used to identify row uniquely but can have NULL values
Eg : CREATE TABLE STUDENTS(
ROLL_NO INT NOT NULL UNIQUE,
NAME VARCHAR (20) ,
AGE INT,
PHONE INT);
• To add UNIQUE constraint to an existing table
ALTER TABLE STUDENTS
MODIFY AGE INT NOT NULL UNIQUE;
• To add UNIQUE constraint to an existing table
ALTER TABLE STUDENTS
ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, PHONE);

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 30


SQL – BASICS AND ADVANCED – PL/SQL

4. PRIMARY KEY :
• Used to uniquely identify a row
• A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
• A table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key.
• If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Eg : CREATE TABLE STUDENTS(
ROLL_NO INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
GPA DECIMAL (18, 2),
PRIMARY KEY (ROLL_NO)
);

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 31


SQL – BASICS AND ADVANCED – PL/SQL

•To create PRIMARY KEY constraint on more than one attribute in a table is called Composite
Primary Key
CREATE TABLE STUDENTS(
ROLL_NO INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
GPA DECIMAL (18, 2),
PRIMARY KEY (ROLL_NO, NAME));
• To add PRIMARY KEY constraint to an existing table
ALTER TABLE STUDENTS
ADD CONSTRAINT PK_ROLLNO PRIMARY KEY (ROLL_NO, NAME);

5. CHECK :
• Used to validates condition for a new value
• It enables a condition to check the value being entered into a record. If the condition evaluates to
false, the record violates the constraint and isn't entered the table.

CREATE TABLE STUDENTS(


ROLL_NO INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT CHECK (AGE >= 18),
);
• It checks the newly entered value for age column is greater than 18
• To add CHECK constraint to an existing table
ALTER TABLE STUDENTS

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 32


SQL – BASICS AND ADVANCED – PL/SQL

MODIFY AGE INT CHECK (AGE >= 18 );


OR
ALTER TABLE STUDENTS
ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);

6. FOREIGN KEY :
• Used to references a row in another table
• Uniquely identifies a row/record in any of the given database table.
• A foreign key is a key used to link two tables together. This is sometimes also called as a
referencing key.
• A Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table.
• The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
• If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 33


SQL – BASICS AND ADVANCED – PL/SQL

Eg: Consider the structure of the following two tables.

STUDENT_DETAILS table
CREATE TABLE Student_Details(
ROLL_NO INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
COURSE_ID VARCHAR(10),
PRIMARY KEY (COURSE_ID)
);

STUDENT_MARKS table
CREATE TABLE Student_Marks (
COURSE_ID INT references Student_Details(COURSE_ID),
MARKS INT
);

If the Student_Marks table has already been created and the foreign key has not yet been set, the use the
syntax for specifying a foreign key by altering a table.

ALTER TABLE Student_Marks


ADD FOREIGN KEY (COURSE_ID) REFERENCES Student_Details (COURSE_ID);

FUNCTIONS
• A function in Oracle is a subprogram that is used to perform an action such as complex
calculations and returns the result of the action as a value
• SQL is used to handle data in databases. It provides various in-built functions and commands

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 34


SQL – BASICS AND ADVANCED – PL/SQL

to access and manage databases according to our requirements.


• Functions are methods used to perform data operations. SQL has many in-built functions used
to perform string concatenations, mathematical calculations etc.
• SQL function is used to show the functionality of the database records, which we create or
delete, according to our condition. It is a collection of SQL statements, which allows the input
parameters, depending on which, it simply takes some types of inputs and displays a result
accordingly, nothing more or less than that. The function is executed each time, whenever it
was called.
• SQL functions are categorized into the following two categories:
i. Aggregate Functions
The Aggregate Functions in SQL perform calculations on a group of values and then
return a single value. Following are a few of the most commonly used Aggregate
Functions:
S.No Function Description
1 SUM() Used to return the sum of a group of values.
2 COUNT() Returns the number of rows either based on a condition,
or without a condition.
3 AVG() Used to calculate the average value of a numeric column.
4 MAX() Returns a maximum value of a column.
5 MIN() This function returns the minimum value of a column.

ii. Scalar Functions


The Scalar Functions in SQL are used to return a single value from the given input
value. Following are a few of the most commonly used Scalar Functions:

S.No Function Description


1 LCASE() Used to convert string column values to lowercase
2 UCASE() This function is used to convert a string column values to
Uppercase.
3 LEN() Returns the length of the text values in the column.
4 MID() Extracts substrings in SQL from column values having
String data type.
5 ROUND() Rounds off a numeric value to the nearest integer.
6 NOW() This function is used to return the current system date and
time.
7 FORMAT() Used to format how a field must be displayed.

To call a function in Oracle:


Following is the syntax to call a function in Oracle:
SELECT <FNAME>(VALUES) FROM DUAL;

Dual in Oracle:
1. It is a pre-define table in oracle.
2. It is having single column & single row
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 35
SQL – BASICS AND ADVANCED – PL/SQL

3. It is called a dummy table in oracle.


4. It is used for testing functions (pre-define & user define) functionalities.

Structure of Dual table:


DESC DUAL;

Data of DUAL table:


SELECT * FROM DUAL;

TYPES OF FUNCTIONS
1. System Defined Functions - These type of functions, SQL Server already contains, which will be
difficult to implement without the System Defined Functions. This function is easily mixed with the
complicated and immediately required operations.

2. User Defined Functions - This function returns a value, based on the user-defined condition. User
Defined Functions are used to create an easy statement. It generates at the time of execution, which
is based on these parts:
• Scalar-valued function: A user-defined function can return a scalar value, we use this
statement in all the database.
• Inline function: When a user-defined function holds the Select statement, that is
updatable or not, the tabular result returned by the function is also updatable. These
functions are called inline functions. We can use these functions in the 'Form clause
of another query.
• Table-valued function: When a user-defined function holds the Select statement, that
is updatable or not, this Table-valued function returned is not updatable. Table-
valued function shows a table and we can use these functions in the 'Form clause of
another query.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 36


SQL – BASICS AND ADVANCED – PL/SQL

Advantage of Functions
The SQL function have some advantages like:
• We can use these functions with where, having (clause).
• They can be used in a 'Select statement'.
• These are based on the function oriented.
• These functions are easy to use.

SYSTEM DEFINED FUNCTIONS:


• Also called as Built-in Functions / Pre-defined functions
• It is the functions which are already defined by the oracle system and ready to be used by the user
or developer
• It is an expression in which an SQL keyword or special operator executes some operation.
• It uses keywords or special built-in operators.
• They are SQL92 Identifiers and are case-insensitive.
• These are again classified into two categories.
o Single row functions (scalar functions) - These functions are returning a single row (or) a
single value. Following are the examples.

▪ Numeric Functions

Function Description Syntax Example O/P


used to convert (-VE) value into SELECT ABS(-12) FROM
ABS() ABS(number) 12
(+VE) value DUAL;
used to return a value that is
CEIL(NUMBE SELECT CEIL(9.3)
CEIL() greater than or equal to the 10
R) FROM DUAL;
given value

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 37


SQL – BASICS AND ADVANCED – PL/SQL

used to return the largest integer FLOOR(NUM SELECT FLOOR(9.8)


FLOOR() 9
equal to or less than n BER) FROM DUAL;
SELECT MOD(10,2)
0
used to return the remainder FROM DUAL;
MOD() MOD(m, n)
value SELECT MOD(15,4)
3
FROM DUAL;
used to return the power of a SELECT POWER(2, 3)
POWER() POWER(m, n) 8
given expression FROM DUAL;
SELECT ROUND(15.253, 15.
ROUND(NUM 1) FROM DUAL; 3
returns the nearest value of the
ROUND() BER,[DECIM SELECT
given expression
AL PLACES]) ROUND(15.253,-1) 20
FROM DUAL;
SELECT TRUNC(5.50)
5
FROM DUAL;
TRUNC
SELECT
used to return n1 truncated to n2 (NUMBER, 32.
TRUNC() TRUNC(32.456,2) FROM
decimal places DECIMAL 45
DUAL;
PLACES)
SELECT TRUNC(32.456,-
30
1) FROM DUAL;

▪ String Functions

Function Description Syntax Example O/P


SELECT
LENGTH used to return the length of a LENGTH(Strin
LENGTH('HELLO') 5
() given string g)
FROM DUAL;
used to return a specified SELECT
LOWER(Char hell
LOWER() character expression in LOWER('HELLO') FROM
Expression) o
lowercase letters DUAL;
used to return a specified HE
UPPER(CharE SELECT UPPER('hello')
UPPER() character expression in LL
xpression) FROM DUAL;
uppercase letters O
used to set the first letter of each
INITCAP INITCAP(STR SELECT INITCAP('hello') Hel
word in uppercase, and rest all
() ING) FROM DUAL; lo
other letters in lowercase
SELECT LTRIM(' ANU') AN
used to remove the unwanted
LTRIM(STRIN TRIML FROM DUAL; U
spaces (or) unwanted characters
LTRIM() G1 SELECT
from the left side of the given AN
[,STRING2]) LTRIM('XXXXXXANU','
string U
X') TRIML FROM DUAL;

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 38


SQL – BASICS AND ADVANCED – PL/SQL

SELECT RTRIM(' ANU ')


AN
TRIMR FROM DUAL;
U
used to remove the unwanted SELECT
RTRIM(STRIN
spaces (or) unwanted characters RTRIM('ANURAGXXXX AN
RTRIM() G1
from the right side of the given XX','X') TRIMR FROM U
[,STRING2])
string DUAL;
SELECT
AN
RTRIM('ANU123','123')
U
TRIMR FROM DUAL;
Go
SELECT
used to return the result (a od
CONCAT CONCAT(char CONCAT('Good',
string) of concatenating two Mo
() 1, char2) 'Morning') ConcatString
string values rnin
FROM DUAL;
g
REPLACE BL
used to return a string with (String, SELECT AC
REPLAC every occurrence of Search_String REPLACE('JACK and K
E() search_string replaced with [, JUE','J','BL') "New String" and
replacement_string Replacement_S FROM DUAL; BL
tring ]) UE
used to return a string with all
occurrences of each character TRANSLATE( SELECT
TRANSL specified in another string as expression, TRANSLATE(‘C|D|T’, '|', C,D
ATE() 2nd argument replaced by its from_string, ',') AS "New String" ,T
corresponding character to_string) FROM DUAL;
specified in the 3rd argument
Used to return the specified SUBSTR (char, SELECT
SUBSTR( number (substring_length) of position [, SUBSTR('HELLO',2,3) EL
) characters from a particular substring_lengt "New String" FROM L
position of a given string h ]) DUAL;
SELECT INSTR('HELLO
INSTR(string , WELCOME','O') "New 5
Used to search string for a substring [, String" FROM DUAL;
INSTR()
substring position [, SELECT INSTR('HELLO
occurrence ] ]) WELCOME','Z') "New 0
String" FROM DUAL;

▪ Date Functions

• Date functions can be defined as a set of functions that operate on date and
time and allows the developer to retrieve the current date and time in a
particular time zone or extract only the date/month/year or more complex
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 39
SQL – BASICS AND ADVANCED – PL/SQL

actions like extracting the last day of the month/next day/session time zone,
etc.
• It also consists of functions that can be used to convert a Date value to a
character string or convert a date that is in a character string to a Date value.

Function Description Syntax Example O/P


SELECT SYSDATE
20-AUG-22
FROM DUAL;
SELECT SYSDATE+10
used to return the current 30-AUG-22
FROM DUAL;
SYSDAT date and time set for the
SYSDATE SELECT
E operating system on which
the database resides TO_CHAR(SYSDATE,
20-AUG-22
‘MM-DD-YYYY
06:57:08
HH:MI:SS’) “NOW”
FROM DUAL;
used to return the date with a
ADD_MONT SELECT
ADD_MO given number of months
HS(date, ADD_MONTHS(SYSDA 20-OCT-22
NTHS() added (date plus integer
integer) TE, 2) FROM DUAL;
months)
SELECT
LAST_DAY(SYSDATE) 31-AUG-22
used to return the last day of FROM DUAL;
LAST_D LAST_DAY(d
the month that contains a SELECT
AY() ate)
date LAST_DAY(SYSDATE) -
11
SYSDATE "Days Left"
FROM DUAL;
SELECT
used to return the date of the NEXT_DAY(
NEXT_D NEXT_DAY(SYSDATE,'
first weekday that is later DATE,'<DAY 22-AUG-22
AY() MONDAY') FROM
than the date _NAME>’)
DUAL;
SELECT
MONTHS used to get the number of MONTHS_BE
MONTHS_BETWEEN(’0
_BETWE months between two dates TWEEN(DAT 12
5-JAN-81′,’05-JAN-80′)
EN() (date1, date2). E1, DATE2)
FROM DUAL;

▪ Conversion Functions
The Oracle Server uses data of one type where it expects data of a different data type.
This can happen when the Server automatically converts the data to the expected data
type. This data type conversion can be done implicitly by the Server, or explicitly by
the user. As a user, we can use the following two functions to convert explicitly.
Function Description Syntax Example O/P

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 40


SQL – BASICS AND ADVANCED – PL/SQL

used to convert a DateTime


or interval value of DATE,
TIMESTAMP, TO_CHAR({
SELECT 2022 22
TIMESTAMP WITH TIME Datetime |
TO_CHA TO_CHAR(SYSDATE,’Y TWENTY
ZONE, or TIMESTAMP Interval } [, fmt
R() YYY YY YEAR CC AD’) TWENTY-
WITH LOCAL TIME [, ‘nlsparam’ ]
FROM DUAL; TWO 21 AD
ZONE data type to a value of ])
VARCHAR2 datatype in a
specified format
INSERT INTO EMP
VALUES (7499, 'ALLEN',
'SALESMAN', Row
TO_DATE('20-FEB- inserted
TO_DATE(ST
TO_DAT used to convert char type to 1981', 'DD-MON-
RING[,FROM
E() oracle date format type YYYY'));
AT])
SELECT * FROM EMP Displays
WHERE records with
TO_CHAR(HIREDATE,’ hire date
YYYY’)=1982; year 1982

o Multiple row functions (grouping functions)


▪ It is also called as Aggregate Functions

AGGREGATE FUNCTIONS:
• SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 41


SQL – BASICS AND ADVANCED – PL/SQL

• Aggregate functions are often used with the GROUP BY and HAVING clauses of the SELECT
statement.
• These functions ignore the NULL values except the count function.
• It is a function where the values of multiple rows are grouped together as input on certain criteria
to form a single value of more significant meaning.
• It is also used to summarize the data.

Types of Aggregate Functions:

Now let us understand each Aggregate function with a example:


DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 42
SQL – BASICS AND ADVANCED – PL/SQL

i. COUNT:
• It is used to Count the number of rows in a database table. It can work on both numeric
and non-numeric data types.
Eg : Count(*): Returns total number of records .i.e 6.
Count(salary): Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null values over the column
salary .i.e 4
ii. SUM:
• It is used to calculate the sum of all selected columns. It works on numeric fields only.
Eg : sum(salary): Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.
iii. AVG:
• It is used to calculate the average value of the numeric type. AVG function returns the
average of all non-Null values.
Eg : Avg(salary) = Sum(salary) / count(salary) = 310/5
Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4
iv. MAX:
• It is used to find the maximum value of a certain column. This function determines the
largest value of all selected values of a column.
Eg : Max(salary): Maximum value in the salary column except NULL i.e., 80.
v. MIN:
• It is used to find the minimum value of a certain column. This function determines
the smallest value of all selected values of a column.
Eg : Min(salary): Minimum value in the salary column except NULL i.e., 40.

USER DEFINED FUNCTIONS:


• It is the Function is defined by the user or developer

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 43


SQL – BASICS AND ADVANCED – PL/SQL

• A PL/SQL function is a reusable program unit stored as a schema object in the Oracle Database
• Its structure is as follows,
CREATE [OR REPLACE] FUNCTION function_name (parameter_list)
RETURN return_type
IS
[declarative section]
BEGIN
[executable section]
[EXCEPTION]
[exception-handling section]
END;

The flow of executing the function is represented as follows,

A function consists of:


• Function Header:
o has the function name
o a RETURN clause that specifies the datatype of the returned value
o Each parameter of the function can be either in the IN, OUT, or INOUT mode
• Function Body : It has three sections
o Declarative Section
▪ section is between the IS and BEGIN keywords
▪ It is where you declare variables, constants, cursors, and user-defined types.
o Executable Section
▪ section is between the BEGIN and END keywords
▪ It is where you place the executable statements
▪ have at least one RETURN statement in the executable statement.
o Exception-Handling Section
▪ Contains exception handler code.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 44


SQL – BASICS AND ADVANCED – PL/SQL

A Sample Code for User-defined Function:


CREATE OR REPLACE FUNCTION get_total_sales(in_year PLS_INTEGER)
RETURN NUMBER
IS
l_total_sales NUMBER := 0;
BEGIN
-- get total sales
SELECT SUM(unit_price * quantity)
INTO l_total_sales
FROM order_items
INNER JOIN orders USING (order_id)
WHERE status = 'Shipped'
GROUP BY EXTRACT(YEAR FROM order_date)
HAVING EXTRACT(YEAR FROM order_date) = in_year;
-- return the total sales
RETURN l_total_sales;
END;
The user-defined function calling is done by:
1. In an assignment statement
DECLARE
l_sales_2017 NUMBER := 0;
BEGIN
l_sales_2017 := get_total_sales (2017);
DBMS_OUTPUT.PUT_LINE('Sales 2017: ' || l_sales_2017);
END;
2. In a Boolean Expression
BEGIN
IF get_total_sales (2017) > 10000000 THEN
DBMS_OUTPUT.PUT_LINE('Sales 2017 is above target');
END IF;
END;
3. In an SQL Statement
SELECT get_total_sales(2017)
FROM dual;

To remove a User-defined function,


DROP FUNCTION function_name;

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 45


SQL – BASICS AND ADVANCED – PL/SQL

Eg:
DROP FUNCTION get_total_sales;
PL/SQL STORED PROCEDURE:
• A PL/SQL procedure is a reusable unit that encapsulates specific business logic of the application
• It is a prepared SQL code that you can save, so the code can be reused over and over again.
• It is a named block stored as a schema object in the Oracle Database.
• Its basic syntax includes,
CREATE [OR REPLACE ] PROCEDURE procedure_name (parameter_list)
IS
[declaration statements]
BEGIN
[execution statements]
EXCEPTION
[exception handler]
END [procedure_name ];
The most important part is parameters. Parameters are used to pass values to the Procedure. There are 3
different types of parameters, they are as follows:
1. IN: This is the Default Parameter for the procedure. It always receives the values from calling
program.
2. OUT: This parameter always sends the values to the calling program.
3. IN OUT: This parameter performs both the operations. It Receives value from as well as sends the
values to the calling program.

The sample procedure includes,

CREATE OR REPLACE PROCEDURE print_contact(in_customer_id NUMBER )


IS
r_contact contacts%ROWTYPE;
BEGIN
-- get contact based on customer id
SELECT *
INTO r_contact
FROM contacts
WHERE customer_id = p_customer_id;

-- print out contact's information


dbms_output.put_line( r_contact.first_name || ' ' || r_contact.last_name || '<' || r_contact.email ||'>' );

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 46


SQL – BASICS AND ADVANCED – PL/SQL

EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line( SQLERRM );
END;

To execute a PL/SQL Procedure,


EXECUTE procedure_name( arguments); OR
EXEC procedure_name( arguments);

Eg:
EXEC print_contact(100);

To remove a PL/SQL Procedure,


DROP PROCEDURE procedure_name;
Eg:
DROP PROCEDURE print_contact;

STORED PROCEDURES(SP) Vs FUNCTIONS (USER DEFINED FUNCTION / UDF):

S.NO SP UDF
1 It may or may not return a value It must return a value
2 It can have input/output parameters It has only input parameters
3 Can call UDF from SP Cannot call SP from UDF
SP cannot be used in SQL statements like UDF can be used in SQL statements like
4
SELECT, INSERT, UPDATE, DELETE SELECT, INSERT, UPDATE, DELETE
SP cannot be used anywhere in the UDF can be used anywhere in the
5 WHERE/HAVING/SELECT part of WHERE/HAVING/SELECT part of SQL
SQL queries queries
Execution plan can be re-used in SP Execution plan can be compiled every time in
6
UDF
7 Can use transactions in SP Cannot use transactions in UDF
SP can have both table variables and UDF can have only table variables as it does not
8
temporary tables permit the use of temporary tables
• Improved security measures
• Client/server traffic is reduced. • Enables faster execution
9 • Programming abstraction and • Modular Programming
efficient code reuse • Can reduce network traffic (data)
• Pre-compiled Execution

VIEWS

• view is a virtual table that does not physically exist.


• It is stored in Oracle data dictionary and do not store any data. It can be executed when called.
• A view is created by a query joining one or more tables.
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 47
SQL – BASICS AND ADVANCED – PL/SQL

• Views are used in the following cases:


o Simplifying data retrieval
▪ Build a complex query, test it carefully, and encapsulate the query in a view
▪ Then, you can access the data of the underlying tables through the view instead of
rewriting the whole query again and again.
o Maintaining logical data independence
▪ expose the data from underlying tables to the external applications via views.
▪ Whenever the structures of the base tables change, you just need to update the view
▪ The interface between the database and the external applications remains intact
o Implementing data security
▪ Views allow you to implement an additional security layer
▪ They help you hide certain columns and rows from the underlying tables and expose
only needed data to the appropriate users.
▪ Oracle provides you the with GRANT and REVOKE commands on views so that
you can specify which actions a user can perform against the view
o

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 48


SQL – BASICS AND ADVANCED – PL/SQL

To create a new view in a database,


CREATE [OR REPLACE] VIEW view_name [(column_aliases)] AS
defining-query
[WITH READ ONLY]
[WITH CHECK OPTION]

A) Creating View
Eg:
CREATE VIEW employee_yos AS
SELECT employee_id, first_name || ' ' || last_name full_name,

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 49


SQL – BASICS AND ADVANCED – PL/SQL

FLOOR( months_between( CURRENT_DATE, hire_date )/ 12 ) yos FROM employees;

B) Creating read-only view


Eg:
CREATE OR REPLACE VIEW customer_credits(customer_id,name,credit) AS
SELECT customer_id, name, credit_limit FROM
customers WITH READ ONLY;
C) Creating join view
Eg:
SELECT product_name, EXTRACT(YEAR FROM order_date) YEAR, SUM( quantity * unit_price )
amount
FROM orders INNER JOIN order_items USING(order_id)
INNER JOIN products USING(product_id)
WHERE status = 'Pending'
GROUP BY EXTRACT(YEAR FROM order_date), product_name;

To remove a view,
DROP VIEW view_name;
Eg:
DROP VIEW employee_yos;

JOINS
• A Join operation pairs two tuples from different relations, if and only if a given join
condition issatisfied. Three types of joins available namely inner join, outer join, semi
join.
• Oracle join is used to combine columns from two or more tables based on values of the
related columns. The related columns are typically the primary key column(s) of the first
table and foreign key column(s) of the second table.
• Oracle supports inner join, left join, right join, full outer join and cross join.
• Note that you can join a table to itself to query hierarchical data using an inner join, left
join, or right join. This kind of join is known as self-join

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 50


SQL – BASICS AND ADVANCED – PL/SQL

• The VIEW continues to exist even after one of the tables (that the Oracle VIEW is based
on) is dropped from the database. However, if you try to query the Oracle VIEW after the
table has been dropped, you will receive a message indicating that the Oracle VIEW has
errors.

Inner Join :
An inner join includes only those tuples with matching attributes and the rest are discarded in the
resulting relation. Theta Join, Equijoin, and Natural Join are called inner joins.
Theta Join ( )
Theta join combines tuples from different relations provided they satisfy the theta condition. The
join condition is denoted by the symbol .Theta join can use all kinds of comparison operators. The
general form is
R1 R2
Example

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 51


SQL – BASICS AND ADVANCED – PL/SQL

Relations: Employee, Project


Query:
Employee Employee.Eid=Project.Empid Project
Result

Eid Name Designation Salary Phno Empid Pid Plocation


125 Kumar Developer 25000 9489562312 125 P123 Coimbatore
568 Sachin HR 33000 8561234568 568 P225 Bangalore
222 Dhoni Accountant 39650 8956235689 222 P556 Delhi

Equi Join( c)
Equijoin is a special case of join where only equality condition holds between a pair of attributes. As
values of two attributes will be equal in result of equijoin, only one attribute will appear in resultThe
general form is
R1 c R2
Example
Relations: Employee, Project
Query:
Employee Employee.Eid=Project.Empid Project
Result

Eid Name Designation Salary Phno Empid Pid Plocation


125 Kumar Developer 25000 9489562312 125 P123 Coimbatore
568 Sachin HR 33000 8561234568 568 P225 Bangalore
222 Dhoni Accountant 39650 8956235689 222 P556 Delhi

Natural Join ( )
It is used to combine related tuples from two relations into single based on equality condition. There
is noneed to specify equality condition explicitly

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 52


SQL – BASICS AND ADVANCED – PL/SQL

Example
Relation: Employee, Project
Query:
employee project
Result:

Eid Name Designation Salary Phno Pid Plocation


125 Kumar Developer 25000 9489562312 P123 Coimbatore
568 Sachin HR 33000 8561234568 P225 Bangalore
222 Dhoni Accountant 39650 8956235689 P556 Delhi

Semi Join (⋉)(𝖺)


A join where the result only contains the columns from one of the joined relations. A semi join
between two tables returns rows from the first table where one or more matches are found in the
second table.

Example
Relation: Employee, Project
Query:
employee ⋉ project
Result:

Eid Name Designation Salary Phno


125 Kumar Developer 25000 9489562312
568 Sachin HR 33000 8561234568
222 Dhoni Accountant 39650 8956235689

Outer Join
Outer joins 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.

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 53


SQL – BASICS AND ADVANCED – PL/SQL

Left Outer Join ( ⟕ )

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.
Example:
Customer Relation:

custome first_na
last_name email address city state zipcode
r_id me
gwashington 3200 Mt Vernon Mount
1 George Washington VA 22121
@usa.gov Hwy Vernon

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 54


SQL – BASICS AND ADVANCED – PL/SQL

jadams@usa.g
2 John Adams 1250 Hancock St Quincy MA 02169
ov
tjefferson@us 931 Thomas Charlott
3 Thomas Jefferson VA 22902
a.gov Jefferson Pkwy esville
11350
jmadison@us
4 James Madison Constitution Orange VA 22960
a.gov
Hwy
jmonroe@usa. 2050 James Charlott
5 James Monroe VA 22902
gov Monroe Parkway esville

Orders Relations

order_id order_date amount customer_id


1 07/04/1776 $234.56 1
2 03/14/1760 $78.50 3
3 05/23/1784 $124.00 2
4 09/03/1790 $65.50 3 Query:
5
Result 07/21/1795 $25.50 10
6 11/27/1787 $14.40 9
Customer ⟕ Orders

first_name last_name order_date order_amount


George Washington 07/04/1776 $234.56
John Adams 05/23/1784 $124.00
Thomas Jefferson 03/14/1760 $78.50
Thomas Jefferson 09/03/1790 $65.50
James Madison NULL NULL
James Monroe NULL NULL

Right Outer Join(⟖)

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.

Example
Relation: Customer, Orders
Query:
DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 55
SQL – BASICS AND ADVANCED – PL/SQL

Customer ⟖ Orders
Result:

first_name last_name order_date order_amount


George Washington 07/04/1776 $234.56
Thomas Jefferson 03/14/1760 $78.50
John Adams 05/23/1784 $124.00
Thomas Jefferson 09/03/1790 $65.50
NULL NULL 07/21/1795 $25.50
NULL NULL 11/27/1787 $14.40

Full Outer Join (⟗)


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

Relation:
Customer,
OrdersQuery:

Customer⟗

Orders

Result

first_name last_name order_date order_amount


George Washington 07/04/1776 $234.56
Thomas Jefferson 03/14/1760 $78.50
John Adams 05/23/1784 $124.00
Thomas Jefferson 09/03/1790 $65.50
NULL NULL 07/21/1795 $25.50
NULL NULL 11/27/1787 $14.40
James Madison NULL NULL
James Monroe NULL NULL

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 56


SQL – BASICS AND ADVANCED – PL/SQL

DR.N.SARANYA, AP(SL.G)/CSE, KPRIET 57

You might also like