You are on page 1of 35

TECHNICAL INTERVIEW QUESTIONS

DATABASE MANAGEMENT SYSTEMS

1.Data:
Known fact is called as data.
Example:
Student Rollno,Name

2.Information:
The processed data is called as information

3.DataBase:
Collection of interrelated data
Example:
Bank DataBase

4.DBMS:
DataBase Management System is software which is used to store and retrieve the information
from the database.
(or)
It is the collection of interrelated files and a set of programs that allow users to access and
modify these files.
Example:
o Ms-Access

o Foxpro

5.DataBase System Applications


o Banking

o Airlines

o Universities

o Finance

o Telecommunications
6.RDBMS:
Relational DataBase Management Systems.
The database which stores the data in table format.
Ex:
o Sql

o Oracle

7. Difference between DBMS and RDBMS


S.NO DBMS RDBMS
1. DataBase Management Systems Relational DataBase Management Systems
2. No relationship concept Relationship between two database objects
3. Supports single user only Supports multiple user only
4. Low software and hardware requirements High software and hardware requirements

8. Advantages of DBMS
o Control Data redundancy

o Data consistency

o Sharing of data

o Accessing Data is easy

o Improved Integrity

o Increased Concurrent Access

o Improved Security

9.Data Redundancy
Same information may be duplicated in several files
Leads higher storage and access cost

10.Integrity
Data values stored in the database must satisfy certain types of conditions

11. ConcurrentAccess Anomalies


Multiple users to update the data simultaneously

12. Security
Prevention of data access by unauthorized users.

13. Disadvantages of DBMS


o Cost of DBMS

o Higher impact of failure

o Additional Hardware costs

14.Schema:
The overall design of DataBase

15. Instance
The information is stored in the database at a particular moment is called an instance.

16.Data Model:
Set of concepts are used to describe the structure of database

17. Types of Data Model


o Relational Model

o E-R Model

o Object Based Model

o Hierarchical Model

18.Relational Model
Consist of collection of tables

19.E-R Model
Representing relationship between entities

20.E-R Diagram
21.Entity
An entity is thing or object
Example:
Person,car,house

22.Attributes
The properties of an entity
Example:
In Customer entity customer id,name,street are the attributes

23.Types of Attributes:
o Simple Attribute

o Composite Attribute

o Single valued Attribute

o Multivalued Attribute

o Derived Attribute

24.Object Based Model


Supports object oriented programming concepts like object and inheritance

25. Hierarchical Model


Data is organized in a hierarchical way

26.DDL
Data Definition Language is used to define the database structure or schema

27.Types of DDL:
o Create

o Alter

o Drop

o Truncate

28.Data Types:
Number Integer values
NumericReal values
Date Date of birth
CharString values
Varchar String values
Varchar2String values
BLOBImage Data Type (Binary Large Object)
LONGBLOB Image Data Type(1MB)
CLOBCharacter Large OBject

29. Difference between char,varchar and varchar2


S.NO CHAR VARCHAR VARCHAR2
1 Fixed Length Variable length Variable Length
2. 10 bytes character 2000 bytes character 4000 bytes character
3. Occupy space for Occupy space for NULL Will not occupy the space for
NULL values values NULL values

30.Create :
This command is used to create table or object in the database.
Syntax:
Create table <tablename>(column1 datatype1, column2 datatype2…,column n )
Student

Rollno Name DOB Mark1 Mark2


Ex:
SQL> create table student(rollno number(10),name varchar2(20),DOB date,
Mark1 number(3),Mark2 number(3));

31.create copy of table:


Syntax:
Create table <new table name> AS select * from <Existing table name>
Example:
SQL>create table student1 AS select * from student;

32.Describe the table:


SQL>desc student;

33.Alter:
This command is used to alter the structure of the database

Rollno Name DOB Mark1 Mark2 Mark3Add Field

Syntax:
Alter table student ADD column name data type);
Example:
SQL>alter table student ADD(Mark3 number(3));

34.MODIFY:
SQL>alter table student MODIFY(Mark3 number(4));

35.RENAME:
This is used to change the existing field name in table
SQL>alter table student RENAME COLUMN Mark1 TO subject1;
OUTPUT:
Rollno Name DOB Subject1 Mark2 Mark3

36.DELETE COLUMN:
SQL>alter table student DROP COLUMN Mark3;
OUTPUT:

Rollno Name DOB Subject1 Mark2

37.Truncate:
This command is used to remove all the records in a table
Syntax:
Truncate table <Existing table name>
Example:
SQL>Truncate table student;

38. Drop:
This command is used to delete table from the database
Syntax:
Drop table <Existing table name>
Example:
SQL> Drop table student;

39.DML
Data Manipulation Language is used to for managing data within schema objects.

40.Types of DML:
o Insert

o Select

o Update

o Delete

41.Insert:
Insert the data into a table
Syntax:
Insert into <Existing Table name> values(data1,data2,..,datan)

Rollno Name DOB Subject1 Mark2


101 Mani 01-OCT-1983 96 95

Example:
SQL>insert into student values(101,’Mani’,’01-OCT-1983’,96,95);

42. Insert More than one records:


Syntax:
Insert into <Existing table name> values(&data1,’&data2’,’&data3’,&data4,&data5)

Rollno Name DOB Subject1 Mark2


101 Mani 01-OCT-1983 96 95
102 Saravanan 06-NOV-1980 99 99

Example:
SQL>insert into student values(&rollno,’&name’,’&DOB’,&subject1,&Mark1);
Enter rollno:102
Enter name:Saravanan
Enter DOB:06-NOV-1980
Enter Subject1:99
Enter Mark2:99
SQL> / or r or run

43. Select:
Retrieve records from database
Syntax:
Select * from <Existing table name>
*  Indicates all the fields
Example:
SQL>select * from student;
Rollno Name DOB Subject1 Mark2
101 Mani 01-OCT-1983 96 95
102 Saravanan 06-NOV-1980 99 99

44. Open particular fields of data:


SQL>select rollno,name from student;

Rollno Name
101 Mani
102 Saravanan

45.Select command in some conditions:


SQL>select * from student WHERE Mark2>=96

Rollno Name DOB Subject1 Mark2


102 Saravanan 06-NOV-1980 99 99

46. Ascending Order:


SQL>select * from student ORDER BY name;
47. Descending Order:
SQL>select * from student ORDER BY name DESC;

48.Update:
This is command is used to update existing data in a table
Syntax:
Update <existing table name> set existing filed name= new value WHERE existing field
name=existing value
Before Changing:

Rollno Name DOB Subject1 Mark2


101 Mani 01-OCT-1983 96 95
102 Saravanan 06-NOV-1980 99 99
Example:
SQL>update student set Mark2=99 WHERE rollno=101;
After Changing:

Rollno Name DOB Subject1 Mark2


101 Mani 01-OCT-1983 96 99
102 Saravanan 06-NOV-1980 99 99

49.Delete:
It is used to delete one record or group records.
Syntax:
Delete from <existing table name>
SQL>Delete from student;

50. Delete the records in some conditions:


Example:
Delete from student WHERE rollno=102;
OUTPUT:

Rollno Name DOB Subject1 Mark2


101 Mani 01-OCT-1983 96 99

51. Difference between DELETE and TRUNCATE


S.NO TRUNCATE DELETE

1. Delete all the records Delete one record or group of records

2. Cannot recover the records Recover the records by using ROLLBACK command
(permanent delete the records)

52.DCL:
Data Control Language

53.Types of DCL
o Grant

o Revoke

54.Create the user


Syntax;
Create user username identified by password;

Example:
SQL>create user mani indentified by 123;

55. Connect to the user:


SQL>connect mani/123;

56.Grant
Gives users access privileges to database
Syntax:
Grant privileges to username;
Example:
SQL>Grant create, insert, select to mani;

57.Revoke:
Withdraw access privileges given with the GRANT command
Syntax:
Revoke privileges from existing username;
Example:
SQL>Revoke create,insert, select from mani;

58. Aggregate Function:

Aggregate functions are functions that take a collection of values as input and return a
single value

59. Behavior of Aggregate Functions:

Operates - on a single column


Return - a single value.
Used only in the SELECT list and in the HAVING clause.
Accepts:
DISTINCT : consider only distinct values of the argument expression.
ALL : consider all values including all duplicates.
Example: SELECT COUNT( DISTINCT column_name)

60. Types of SQL Aggregate Functions


o SUM

o AVG

o MIN

o MAX

o COUNT

61.STAFF
sno fname lname salary position
SL100 John White 30000.00 Manager
SL101 Susan Brand 24000.00 Manager
SL102 David Ford 12000.00 Project Manager
SL103 Ann Beech 12000.00 Project Manager
SL104 Mary Howe 9000.00 Project Manager
SL100 John White 30000.00 Manager
SL101 Susan Brand 24000.00 Manager
SL102 David Ford 12000.00 Project Manager
SL103 Ann Beech 12000.00 Project Manager
SL104 Mary Howe 9000.00 Project Manager

62. SUM()
Returns: The sum of the values in a specified column.
Example: Find the total/sum of the Managers salary
Query:
SELECT SUM( salary) AS sum_salary FROM Staff WHERE Staff.position = ‘Manager’;
Result:
sum_salary
54000.00

63. AVG()
Returns: The average of the values in a specified column.
Example: Find the average of the Project Managers salary .

Query:
SELECT AVG( DISTINCT salary) AS avg_salary FROM Staff
WHERE Staff.position = ‘Project Manager’;
Result:
avg_salary
10500.00 // Error in Result
// avg_salary = 11000.00

64. Revised Query for AVG()


Query:
SELECT AVG(ALL salary) AS avg_salary FROM Staff WHERE Staff.position = ‘Project
Manager’;
Result :
avg_salary
11000.00
CAUTION: Using DISTINCT and ALL in SUM() and AVG()

65. MIN() and MAX()


Returns: MIN() returns the smallest value of a column.
MAX() returns the largest value of a column.
Example: Find the minimum and maximum staff salary.
Query:
SELECT MIN( salary) AS min_salary, MAX (salary) AS max_salary
FROM Staff;
Result: min_salary max_salary
9000.00 30000.00
66. Use of COUNT() and SUM()
Example: Find the total number of Managers and the sum of there salary.

Query: SELECT COUNT( sno) AS sno_count , SUM(salary) AS sum_salary


From Staff WHERE Staff.position = ‘Manager’;

67. COUNT(*)
Input: There is no input to this function.
Returns: It counts all the rows of a table , regardless of
whether Nulls or the duplicate occur.
Example: How many Project Manager salary is more than
9000.00
Query: SELECT COUNT(*) AS Count_Salary FROM Staff
WHERE Staff.position = ‘Project Manager’ AND Staff.salary > 9000.00
 Result:

Count_ Salary
2

68.TCL:
Transaction control statements manage changes made by DML statements.

A transaction is a set of SQL statements which Oracle treats as a Single Unit. all the statements should execute
successfully or none of the statements should execute.

69.Types of TCL:
COMMIT : Make changes done in transaction permanent.
ROLLBACK : Rollbacks the state of database to the last commit point.
SAVEPOINT : Use to specify a point in transaction to which later you can rollback.
70. COMMIT

To make the changes done in a transaction permanent issue the COMMIT statement.

Example

insert into emp (empno,ename,sal) values (101,’Abid’,2300);


commit;

71. ROLLBACK

Rollback restore the state of the database to the last commit point.

Example :
delete from emp;
rollback; /* undo the changes */

72. SAVEPOINT

Specify a point in a transaction to which later you can roll back.

Example

insert into emp (empno,ename,sal) values (109,’Sami’,3000);


savepoint a;
insert into dept values (10,’Sales’,’Hyd’);
savepoint b;
insert into salgrade values (‘III’,9000,12000);

73.ROLLBACK TO
To recover particular records during transaction.
rollback to a;

If you give

rollback;

Then the whole transactions is roll backed.

If you give

commit;
Then the whole transaction is committed and all savepoints are removed.

74.Subqueries
Using a Subquery to Solve a Problem

Main query:
Which employees have salaries greater than Abel’s salary?
Subquery:
What is Abel’s salary?
Syntax:

SELECT select_list FROM table


WHERE expr operator (SELECT select_list FROM table);

 The subquery (inner query) executes once before the main query (outer query).
 The result of the subquery is used by the main query.
Example:

75.View
A view is a virtual table.

view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.

Syntax:
CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition

Example:

CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products


WHERE Discontinued=No

76.SQL Constraints

SQL constraints are used to specify rules for the data in a table.

If there is any violation between the constraint and the data action, the action is aborted by the
constraint.

Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after
the table is created (inside the ALTER TABLE statement).

77.SQL CREATE TABLE + CONSTRAINT Syntax:


CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);

78.Types of Constraints:

 NOT NULL - Indicates that a column cannot store NULL value


 UNIQUE - Ensures that each row for a column must have a unique value
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or
combination of two or more columns) have an unique identity which helps to find a particular
record in a table more easily and quickly
 FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in
another table
 CHECK - Ensures that the value in a column meets a specific condition
 DEFAULT - Specifies a default value when specified none for this column
79. SQL NOT NULL Constraint

The NOT NULL constraint enforces a column to NOT accept NULL values.

Example

CREATE TABLE PersonsNotNull


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) ) ;

80. UNIQUE Constraint

The UNIQUE constraint uniquely identifies each record in a database table.

The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column
or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

S.NO PRIMARY KEY UNIQUE

1 Cannot allow duplicate values Cannot allow duplicate values

2 Will not allow NULL values Allow the NULL values

3 only one PRIMARY KEY constraint per you can have many UNIQUE constraints per
table. table

Example:

CREATE TABLE Persons


(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
81. PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

Most tables should have a primary key, and each table can have only ONE primary key.

Example:

CREATE TABLE Persons


(
P_Id int PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255));

82.CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a single column it allows only certain values for this column.

If you define a CHECK constraint on a table it can limit the values in certain columns based on values
in other columns in the row.

Example:

CREATE TABLE Persons


(
P_Id int CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

83.FOREIGN KEY Constraint

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.


Let's illustrate the foreign key with an example. The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 2
4 24562 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.

The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

Example: Parent Table

CREATE TABLE Persons


(
P_Id int PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

Child Table:

CREATE TABLE Orders


(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
);

84.SELECT DISTINCT Statement


In a table, a column may contain many duplicate values; and sometimes you only want to list the
different (distinct) values.

The DISTINCT keyword can be used to return only distinct (different) values.

85.SQL SELECT DISTINCT Syntax


SELECT DISTINCT column_name1,column_name2 FROM table_name;

CID CNAME CITY

101 Prasath Chennai

102 Ramkumar Chennai

103 Vimal Karur

Example:

SQL>SELECT DISTINCT City FROM Customers;

OUTPUT:

CITY

Chennai

Karur

86.The UCASE() Function

The UCASE() function converts the value of a field to uppercase.

Example:

SQL>SELECT UCASE(CustomerName) FROM Customers

87.The LCASE() Function

The LCASE() function converts the value of a field to lowercase.


Example:

SQL>SELECT LCASE(CustomerName) FROM Customers;

88. What is database normalization?


It is a process of analyzing the given relation schemas based on their functional dependencies and
primary keys to achieve the following desirable properties:
1) Minimizing Redundancy
2) Minimizing the Insertion, Deletion, And Update Anomalies
Relation schemas that do not meet the properties are decomposed into smaller relation schemas that
could meet desirable properties.

89.Do you have any idea about database normalization and its various normal forms?

Normalization :- Normalization can be defined as the process of organization the data to reduce the
redundant table data to the minimum. This process is carried out by dividing the database into two or
more than two tables and defining relationship between them so that deletion, updation and insertion
can be made to just one table and it can be propagated to other tables through defined relationships.

90.Normalization can be done for the following reason:-

o To simplify the database structure so that it is easy to maintain.


o To retrieve the data quickly from the database.

o To reduce the need of restructuring the database when enhancement of the application required
in future.

91.Normal Forms: - The normal form can be refers to the highest normal form condition that it
meets and hence indicates the degree to which it has been modified. The normal forms are:-

o First Normal Form (INF)


o Second Normal Form (2NF)

o Third Normal Form (3NF)

o Boyce- Codd Normal Form

o Forth Normal Form (4NF)


o Fifth Normal Form(5NF)

Note: - Normalization into 5NF is considered very rarely in practice.

92.First Normal Form (INF):- A table is said to be in a First Normal Form (1NF) if it satisfy the
below three conditions:-

1) If the columns of the table only contain atomic values (Single, indivisible).

2) Primary key is defined for the table

3) All the columns of the table are defined on the primary key.

93.Second Normal Form (2NF):- A table is said to be in its Second Normal Form if it satisfied the
following conditions:-

1) It satisfies the condition for the First Normal Form (1NF),

2) It do not includes and partial dependencies where a column is dependent only a part of a primary
key.

Diagram
94.Third Normal Form (3NF):- A table is said to be in the Third Normal form (3NF) if it satisfy
the following conditions:-

1) It should be in the 2NF

2) It should not contain any transitive dependency which means that any non key column of the table
should not be dependent on another non key column.

Diagram:

95. Denormalization:- Denormalization can be defined as the process of moving from higher
normal form to a lower normal forms in order to speed up the database access.

96.What is Join?
An SQL Join is used to combine data from two or more tables, based on a common field between
them. For example, consider the following two tables.

Student Table
EnrollNo StudentName Address
1000 geek1 geeksquiz1
1001 geek2 geeksquiz2
1002 geek3 geeksquiz3

StudentCourse Table

CourseID EnrollNo
1 1000
2 1000
3 1000
1 1002
2 1003

Following is join query that shows names of students enrolled in different courseIDs.

SELECT StudentCourse.CourseID, Student.StudentName


FROM StudentCourse
INNER JOIN Customers
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID;

The above query would produce following result.

CourseID StudentName
1 geek1
1 geek2
2 geek1
2 geek3
3 geek1

97. What is a JOIN? Explain types of JOIN in oracle.

A JOIN is used to match/equate different fields from 2 or more tables using primary/foreign keys.
Output is based on type of Join and what is to be queries i.e. common data between 2 tables, unique
data, total data, or mutually exclusive data.

98.Types of JOINS:

Simple JOIN:
SELECT p.last_name, t.deptName FROM person p, dept t WHERE p.id = t.id;

Find name and department name of students who have been allotted a department

Inner/Equi/Natural JOIN

SELECT * from Emp INNER JOIN Dept WHERE Emp.empid=Dept.empid

Extracts data that meets the JOIN conditions only. A JOIN is by default INNER unless OUTER
keyword is specified for an OUTER JOIN.

Outer Join

SELECT distinct * from Emp LEFT OUTER JOIN Dept Where Emp.empid=Dept.empid

It includes non matching rows also unlike Inner Join.

Self JOIN

SELECT a.name,b.name from emp a, emp b WHERE a.id=b.rollNumber

Joining a Table to itself.

99.What is a JOIN? Explain types of JOIN in oracle.

A join is a query that extracts data from two or more tables, views or snapshots.

100.Types of JOIN

EQUI-JOIN
This is represented by (=) sign. This join retrieves information by using equality condition.

NON-EQUI JOIN
If sign other than =, then it is non-equi join.

SELF JOIN
Self join is a join type between a row of a table to another row of the same table.

OUTER JOIN
This type fetches the row that matches the join condition and rows that don’t match the join condition.

101.What are the guidelines for joins?


o Join condition should ideally be written in the FROM clause.
o There should be no ambiguity in the column names to be joined.
o Depending on requirement, the type of JOIN should be chosen.

o To increase performance, one can limit the number of rows to be joined.

o Ideally, join tables with columns having same data type, width etc.

o Avoid joining tables with columns having few unique values.

102.What are the types of Join?

NON-EQUI JOIN: This join does not make use of the following comparison operators:- >, <, >=, <=.
This is to say, it joins two or more tables based on a specified column value not equaling a specified
column value in another table.

Example:
SELECT STUDENT_TBL.STD_ID, STUDENT_MARKS_TBL.DATE_EXAM
FROM STUDENT_TBL, STUDENT_MARKS_TBL
WHERE STUDENT_TBL.STD_ID!= STUDENT_MARKS_TBL.EMP_ID;

103.CARTESIAN JOIN: Cartesian join does not join two tables based on a condition. In this case
combined rows of both tables are returned.

Example:
select employee_id, manager_id
from employee cross join manager;

104.SELF JOIN: This joins is a join to the table itself. As per the condition, the results are returned.
Since the same name of the table can’t be used twice, aliases of the tables are created.

Example:
select b.std_last_name STUDENT, a.std_last_name PROFESSOR
from std a right outer join std b on (a.std_key = b.professor);

105.OUTER JOIN: In this type of join results are returned only if the join condition is met- i.e. the
joined fields are equal.

Example:
Select employee.employee_id, employee.employee_name, manager.manager_id
from employee, manager where employee.employee_id = manager.employee_id(+);

106.what’s the difference between an inner and outer join?

Joins are used to combine the data from two tables, with the result being a new, temporary table.
The temporary table is created based on column(s) that the two tables share, which represent
meaningful column(s) of comparison. The goal is to extract meaningful data from the resulting
temporary table. Joins are performed based on something called a predicate, which specifies the
condition to use in order to perform a join. A join can be either an inner join or an outer join,
depending on how one wants the resulting table to look.

It is best to illustrate the differences between inner and outer joins by use of an example. Here we have 2
tables that we will use for our example:

Employee Location

EmpID EmpName EmpID EmpLoc


13 Jason 13 San Jose
8 Alex 8 Los Angeles
3 Ram 3 Pune, India
17 Babu 17 Chennai, India
25 Johnson 39 Bangalore, India

It’s important to note that the very last row in the Employee table does not exist in the Employee
Location table. Also, the very last row in the Employee Location table does not exist in the Employee
table. These facts will prove to be significant in the discussion that follows.

107.Outer Joins
Let’s start the explanation with outer joins. Outer joins can be further divided into left outer joins, right outer
joins, and full outer joins. Here is what the SQL for a left outer join would look like, using the tables above:

select * from employee left outer join location


on employee.empID = location.empID;

In this SQL we are joining on the condition that the employee ID’s match in the rows tables. So, we will be
essentially combining 2 tables into 1, based on the condition that the employee ID’s match. Note that we can
get rid of the "outer" in left outer join, which will give us the SQL below. This is equivalent to what we have
above.

select * from employee left join location


on employee.empID = location.empID;

A left outer join retains all of the rows of the left table, regardless of whether there is a row that
matches on the right table. The SQL above will give us the result set shown below.
Employee.EmpID Employee.EmpName Location.EmpID Location.EmpLoc
13 Jason 13 San Jose
8 Alex 8 Los Angeles
3 Ram 3 Pune, India
17 Babu 17 Chennai, India
25 Johnson NULL NULL

108.The Join Predicate – a geeky term you should know


Earlier we had mentioned something called a join predicate. In the SQL above, the join predicate is
"on employee.empID = location.empID". This is the heart of any type of join, because it
determines what common column between the 2 tables will be used to "join" the 2 tables. As you
can see from the result set, all of the rows from the left table are returned when we do a left outer join.
The last row of the Employee table (which contains the "Johson" entry) is displayed in the results even
though there is no matching row in the Location table. As you can see, the non-matching columns in
the last row are filled with a "NULL". So, we have "NULL" as the entry wherever there is no match.

A right outer join is pretty much the same thing as a left outer join, except that the rows that are retained are
from the right table. This is what the SQL looks like:

select * from employee right outer join location


on employee.empID = location.empID;

select * from employee right join location


on employee.empID = location.empID;

Using the tables presented above, we can show what the result set of a right outer join would look like:

Employee.EmpID Employee.EmpName Location.EmpID Location.EmpLoc


13 Jason 13 San Jose
8 Alex 8 Los Angeles
3 Ram 3 Pune, India
17 Babu 17 Chennai, India
NULL NULL 39 Bangalore, India

We can see that the last row returned in the result set contains the row that was in the Location table,
but not in the Employee table (the "Bangalore, India" entry). Because there is no matching row in the
Employee table that has an employee ID of "39", we have NULL’s in the result set for the Employee
columns.

109.Inner Joins

Now that we’ve gone over outer joins, we can contrast those with the inner join. The difference
between an inner join and an outer join is that an inner join will return only the rows that actually match
based on the join predicate. Once again, this is best illustrated via an example. Here’s what the SQL for an
inner join will look like:

select * from employee inner join location on


employee.empID = location.empID

This can also be written as:

select * from employee, location


where employee.empID = location.empID

Now, here is what the result of running that SQL would look like:

Employee.EmpID Employee.EmpName Location.EmpID Location.EmpLoc


13 Jason 13 San Jose
8 Alex 8 Los Angeles
3 Ram 3 Pune, India
17 Babu 17 Chennai, India

110.Inner vs Outer Joins

We can see that an inner join will only return rows in which there is a match based on the join
predicate. In this case, what that means is anytime the Employee and Location table share an Employee
ID, a row will be generated in the results to show the match. Looking at the original tables, one can see
that those Employee ID’s that are shared by those tables are displayed in the results. But, with a left or
right outer join, the result set will retain all of the rows from either the left or right table.

111.What is PL/SQL ?

PL/SQL is a procedural language which has interactive SQL, as well as procedural programming
language constructs like conditional branching and iteration.

112.Difference between SQL and PL/SQL


S.NO SQL PL/SQL

1. Structured Query Language Procedural Language/ Structured Query


Language

2. Only one query execute at the same More than one query execute at the same time
time

113. Differentiate between % ROWTYPE and TYPE RECORD.

% ROWTYPE is used when a query returns an entire row of a table or view.

TYPE RECORD, on the other hand, is used when a query returns column of different tables or views.

Eg. TYPE r_emp is RECORD (sno smp.smpno%type,sname smp sname %type)

e_rec smp ROWTYPE

Cursor c1 is select smpno,dept from smp;

e_rec c1 %ROWTYPE

114.PLSQL SYNTAX:

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

Example:

DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
115.Procedures: these subprograms do not return a value directly, mainly used to perform an action.

Creating a Procedure

CREATE [OR REPLACE] PROCEDURE procedure_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

Example:

CREATE OR REPLACE PROCEDURE greetings


AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/

116.Functions: these subprograms return a single value, mainly used to compute and return a value.

Creating a Function

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Example:

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/
117.Cursor:
Oracle creates a memory area, known as context area, for processing an SQL statement, which
contains all information needed for processing the statement.
Types:

 Implicit cursors
 Explicit cursors

118.Implicit Cursors

Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/

119. Explicit Cursors

Explicit cursors are programmer defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.

DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
120.Trigger:
Triggers are stored programs, which are automatically executed or fired when some events occur.

Syntax:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

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

You might also like