Dbmslabmanual
Dbmslabmanual
List of Experiments:
SQL
1. Queries to facilitate acquaintance of Built-In Functions, String Functions, Numeric
Functions, Date Functions and Conversion Functions.
2. Queries using operators in SQL
3. Queries to Retrieve and Change Data: Select, Insert, Delete, and Update
4. Queries using Group By, Order By, and Having Clauses
5. Queries on Controlling Data: Commit, Rollback, and Save point
6. Queries to Build Report in SQL *PLUS
7. Queries for Creating, Dropping, and Altering Tables, Views, and Constraints
8. Queries on Joins and Correlated Sub-Queries
9. Queries on Working with Index, Sequence, Synonym, Controlling Access, and
Locking Rows for Update, Creating Password and Security features
PL/SQL
10. Write a PL/SQL Code using Basic Variable, Anchored Declarations, and Usage of
Assignment Operation
11. Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL
12. Write a PL/SQL block using SQL and Control Structures in PL/SQL
13. Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types
14. Write a PL/SQL Code using Procedures, Functions, and Packages
15. Write a PL/SQL Code Creation of forms for any Information System such as Student
Information System, Employee Information System etc.
16. Demonstration of database connectivity
ORACLE
Oracle Was first developed by Relational Software in the year 1979 later came to be known as oracle
Corporation. This company produces the most widely used , server based , multi user RDBMS named
Oracle
SQL
DDL
• This part of SQL is a syntax for database tables to be created or deleted. We can also define
indexes, specify links between tables, and impose constraints between database tables
• The important DDL statements are
– CREATE Table
– ALTER Table
– DROP Table
– TRUNCATE Table
– RENAME Table
DML
• This part of SQL is a syntax for executing queries. But the SQL language also include a syntax
to update, insert and delete records.
• The important DML Statements are
– SELECT – Extracts data from a database table
– UPDATE – Updates data in a database table
– DELETE – Deletes data from a database table
– INSERT INTO – Inserts new data into a database Table.
TCL
DCL
• This part SQL is a syntax to control the flow of data among different users of the database
• The important DCL statements are
– GRANT – Grants permissions to users
– REVOKE – Revokes permissions to users
Data Types
• CHAR(size)
– Used to store character strings. The size determines number of characters the cell can
hold. The max number is 255 Characters
• VARCHAR(size)/VARCHAR2(size)
– Stores Variable length aplhanumeric data.The max is 4000 characters
• DATE
– Used to represent date and time. The standard format is DD-Mon-YY as in 03-dec-08. If
we want to change date function use appropriate function. Valid date range is Jan 1,4712
B.C to December 31,4712 A.D.
• NUMBER(p,s)
– Used to store numbers. Number of virtually any magnitude can be stored up to 38 digits
of precission.
• LONG
– Used to store variable length character strings containing upto 2 GB
• RAW/ LONG RAW
– Used to store binary data such as digitized picture or images. Upto 2 GB.
• TIME STAMP
– Used to store year, month, day, hour, minutes and seconds
• ROWID
– Fixed length binary data. Every record in the data base has unique Physical Address. The
format is BBBBBBB.RRRR.FFFFF where BBBBBBB is the block in database file,
RRRR is the row in the block and FFFFF is the database file
• BFILE
– File locator that points to a read-only binary object outside the database. Up to 4 GB.
• BLOB
– Locator for Large Binary objects within the database. Up to 4GB
• CLOB
– Locator for Large Character objects within the database. Up to 4 GB
String Functions:
lower():-
Return the argument in lowercase.
Syntax:-
LOWER(string);
LOWER('SWARNANDHRA')
---------------------------------
swarnandhra
upper():-
Return the argument in uppercase.
Syntax:-
UPPER(string);
UPPER('SWARNANDHRA')
---------------------------------
SWARNANDHRA
length():-
Return the length of given string.
Syntax:-
LENGTH(String);
LENGTH('SWARNANDHRAINSTITUTE')
------------------------------
21
initcap():-
Returns char with first letter of each word in uppercase.
Syntax:-
INITCAP(String);
INITCAP('SWARNANDHRAINSTITUTEOFENGINEERINGANDTECHNOLOGY')
--------------------------------------------------------------------------------
Swarnandhra Institute Of Engineering And Technology
substr():-
SUBSTR('SWARNANDHRA')
------------------
andhra
instr():-
Return the index of the first occurrence of substring.
Syntax:-
INSTR(string,substring);
INSTR('SITE','I')
-----------------
2
SQL> select instr('swarnandhra','n',1,2) from dual;
INSTR('SWARNANDHRA','N',1,2)
----------------------------
7
trim():-
Remove leading and trailing spaces.
Syntax:-
TRIM(string);
TRIM('SWARNANDHRA')
---------------------------------
swarnandhra
TRIM(LEADING'*'FROM'***SWARNANDHRAINSTITUTE***')
------------------------------------------------------------------------
swarnandhra institute***
TRIM(BOTH'*'FROM'***SWARNANDHRAINSTITUTE***')
---------------------------------------------------------------
swarnandhra institute
ltrim():-
LTRIM('SWARNANDHRA','S')
------------------------------
warnandhra
LTRIM('SWARNANDHRA','SWARN')
---------------------
andhra
rtrim():-
Remove trailing spaces.
Syntax:-
RTRIM(string,remstring);
RTRIM('SWARNANDHRA','A')
------------------------------
swarnandhr
RTRIM('SWARNANDHARA','RA')
---------------------------
swarnandh
lpad():-
Return the string argument, left-padded with the specified string .
Syntax:-
LPAD(string,length,padstring);
LPAD('SIET',10,'*')
------------------------------
******Siet
LPAD('SIET',10)
------------------------------
Siet
rpad():-
RPAD('SIET',10,'*')
------------------------------
Siet******
RPAD('SIET',10,'NSP')
------------------------------
SietNspNsp
concat():-
Returns string1 concatenated with string2.
Syntax:-
CONCAT(string1,......stringn);
CONCAT('SWARNANDHRA','INSTITUTE')
------------------------------------------------------------
SwarnandhraInstitute
Numeric functions:-
abs():-
Returns the absolute value of a number.
Syntax:-
ABS(value);
Absolute Value
--------------
25
ABS(-21)
----------
21
power():-
Power(m,n) function returns m raised to n.
Syntax:-
power(m,n);
5 power 3
----------
125
SQL> select power(2,3) from dual;
POWER(2,3)
----------
8
sqrt():-
Returns the square root of a number.
Syntax:-
SQRT(value);
SQRT(49)
----------
7
mod():-
MOD(32,3)
----------
2
round():-
Round function for number rounded to specified integer to the right of the decimal
point.
Syntax:-
ROUND(value);
ROUND(23.29,1)
--------------
23.3
ROUND(23.29,2)
--------------
23.29
trunc():-
Returns n truncated to m decimal places.m can be omitted, to 0 places. m can be -
ve, to truncate(make zero) m digits left of the decimal point.
Syntax:-
TRUNC(n,m) ;
TRUNC(125.815,1)
----------------
125.8
TRUNC(125.815,2)
----------------
125.81
floor():-
Floor function returns previous whole number.
Syntax:-
FLOOR(value);
FLOOR(18.6)
-----------
18
FLOOR(32.12)
------------
32
ceil():-
Ceil function returns next whole number.
Syntax:-
CEIL(value);
CEIL(25.81)
-----------
26
CEIL(13.15)
-----------
14
exp():-
It Returns e raised to the nth power.
Syntax:-
EXP(n);
EXP(10)
----------
22026.4658
greatest():-
Returns the largest of multiple values.
Syntax:-
GREATEST(VALUE1,.......VALUEN);
GREATEST(23,67,45)
------------------
67
GREATE
------
67
least():-
Returns the smallest of multiple values.
Syntax:-
LEAST(value1,......valuen);
LEAST(4,5,17)
-------------
4
LEAST('4','5','17')
------
17
Date Functions():-
sysdate():-
It Returns the current date and time.
Syntax:-
sysdate();
SYSDATE
------------------
29-JUL-18
last_day():-
Return the last day of the month for the argument .
SQL> select last_day('21-Jun-18') from dual;
LAST_DAY('21-JUN-1
------------------
30-JUN-18
next_day():-
The Oracle NEXT_DAY() function returns the date of the first weekday specified
by day name that is later than a date.
Syntax:-
NEXT_DAY(date,weekday);
NEXT_DAY('25-AUG-18','SATURDAY')
------------------
01-SEP-18
add_months():-
ADD_MONTHS() function returns a date with a given number of months added
(date plus integer months). A month is defined by the session parameter
NLS_CALENDAR.
Syntax:-
ADD_MONTHS(date, integer);
ADD_MONTHS('12-JUN-18',3)
------------------
12-SEP-18
months_between():-
The MONTHS_BETWEEN() function is used to get the number of months
between dates (date1, date2).
Syntax:-
MONTHS_BETWEEN(date1, date2);
MONTHS_BETWEEN('25-JUL-18','25-APR-18')
---------------------------------------
3
round():-
The ROUND() function is used to get the date rounded to the unit specified by the
format model. It operates according to the rules of the Gregorian calendar.
Syntax:-
ROUND(date , fmt )
ROUND(TO_DATE('24-JUL-18'),'YEAR)
------------------
01-JAN-19
ROUND(TO_DATE('12-MAR-18'),'YEAR)
------------------
01-JAN-18
SQL> select round(to_date('21-Jul-18'),'Q') from dual;
ROUND(TO_DATE('21-JUL-18'),'Q')
------------------
01-JUL-18
ROUND(TO_DATE('21-AUG-18'),'Q')
------------------
01-OCT-18
ROUND(TO_DATE('21-JUL-18'),'month')
------------------
01-AUG-18
ROUND(TO_DATE('21-JUL-18'),'DAY')
------------------
22-JUL-18
trunc():-
The TRUNC (date) function returns date with the time portion of the day truncated
to the unit specified by the format model fmt. The value returned is always of datatype
TRUNC(TO_DATE('24-JUL-18'),'YEAR')
------------------
01-JAN-18
TRUNC(TO_DATE('24-JUL-18'),'YEAR')
------------------
01-JUL-18
TRUNC(TO_DATE('24-JUL-18'),'YEAR')
------------------
01-JUL-18
greatest():-
Return the greatest date in a list of expressions.
Syntax:-
SELECT GREATEST(to_date(date1),to_date(date2),..);
least():-
Return the smallest value in a list of expressions.
Syntax:-
SELECT LEAST(to_date(date1),to_date(date2),...);
LEAST(TO_DATE('01--JAN-18'),TO_DATE('01-FEB-18'),TO_DATE('20-APR-18'))
------------------
01-JAN-18
Conversion Functions():-
to_date():-
The TO_DATE function is used to convert a TEXT representation of a date into an
Oracle DATETIME value.By default, strings following the formats of DD-MON-YYYY,
DD-MON-YY, DD-MONTH-YYYY, DD-MONTH-YY can automatically be converted
without the need for a date_format.
Syntax:-
to_date(string, date_format);
TO_DATE('2018/07/2','YYYYMMDD)
------------------
29-JUL-18
SQL> select to_date('072917','mmddyy') from dual;
TO_DATE('072917','MMDDYY')
------------------
29-JUL-17
SQL> select to_date('20180729','yyyymmdd') from dual;
TO_DATE('20180729','YYYYMMDD')
------------------
29-JUL-18
to_char():-
The Oracle/PLSQL TO_CHAR function converts a number or date to a string.
Syntax:-
TO_CHAR( value , format_mask);
date to string:-
SQL> select to_char(sysdate,'yyyy/mm/dd') from dual;
TO_CHAR(SYSDATE,'YYYY/MM/DD')
------------------------------
2018/08/29
SQL> select to_char(sysdate,'month dd,yyyy') from dual;
TO_CHAR(SYSDATE,'MONTHDD,YYYY')
---------------------------------------------------
august 29,2018
SQL> select to_char(sysdate,'monddth,yyyy') from dual;
TO_CHAR(SYSDATE,'MONDDTH,YYYY')
------------------------------------
aug29th,2018
SQL> select to_char(to_date('24-Jul-18'),'dd-mm-yy') from dual;
TO_CHAR(TO_DATE('24-JUL-18'),'DD-MM-YY')
------------------------
24-07-18
Number to string:-
TO_CHAR(1000,'9999')
---------------
1000
TO_CHAR(1000,'9,999)
------------------
1,000
TO_CHAR(1000,'$9,999')
---------------------
$1,000
to_number():-
The Oracle TO_NUMBER function converts a string to a number.
Syntax:-
TO_NUMBER( string1 , format_mask);
TO_NUMBER('1000')
-----------------
1000
1000+TO_NUMBER('1000')
----------------------
2000
like operator():-
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards used in conjunction with the LIKE operator:
% The percent sign represents zero, one, or multiple characters.
_ The underscore represents a single character.
Syntax:-
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern;
SNO NAME
---------- ---------------------------------------------
502 Sita
504 Sai
506 Satya
509 Sushma
512 Sita
5 rows selected.
SNO NAME
---------- ---------------------------------------------
501 Rama
502 Sita
506 Satya
509 Sushma
510 Lalitha
511 Rama
512 Sita
7 rows selected.
Display the students whose names begin with letter 'R' and 'S'.
SQL> select Sno,Name from Student where Name like 'R%' or Name like 'S%';
SNO NAME
---------- ---------------------------------------------
501 Rama
502 Sita
504 Sai
506 Satya
509 Sushma
511 Rama
512 Sita
7 rows selected.
SNO NAME
---------- ---------------------------------------------
501 Rama
503 Lakshmi
504 Sai
506 Satya
508 Yamini
510 Lalitha
511 Rama
7 rows selected.
SNO NAME
---------- ---------------------------------------------
501 Rama
502 Sita
507 John
511 Rama
512 Sita
5 rows selected.
In operator:-
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Syntax:-
1) SELECT column_name(s) FROM table_name WHERE column_name IN
(value1, value2, ...);
2)select column1,...columnn from table_name where column in (condition);
not in operator:-
The NOT IN operator allows you to specify multiple values in a WHERE clause.
Syntax:-
6 rows selected.
8 rows selected.
Between operator:-
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Syntax:-
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN
value1 AND value2;
SQL> select Sno,Name,DBMS from Student where DBMS between 70 and 90;
SQL> select Sno,Name,DBMS from Student where DBMS not between 70 and 90;
9 rows selected.
SQL> select * from Student where DBMS not between 70 and 90;
9 rows selected.
Queries to Retrieve and Change Data: Select, Insert, Delete, and Update:
create command:-
Syntax:-
CREATE TABLE table_name (column_name1 datatype,column_name2 datatype,...
column_nameN datatype);
Table created.
insert statement:-
The INSERT statement adds one or more new rows of data to a database table.
If there are less values being described than there are columns in the table then it is
mandatory to indicate both the columns and there column values.
If there are exactly the same number of values as there are columns and the values
are sequenced in exactly in accordance with the data type of the table columns there is no
need to indicate the column names.
Syntax:-
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1,
value2, value3, ...);
1 row created.
SQL> /
Enter value for sno: 2
Enter value for department: Mechanical
SQL> /
Enter value for sno: 3
Enter value for department: ECE
Enter value for sections: 7
old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (3,'ECE',7)
1 row created.
SQL> /
Enter value for sno: 4
Enter value for department: CSE
Enter value for sections: 8
old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (4,'CSE',8)
1 row created.
SQL> /
Enter value for sno: 5
Enter value for department: MBA
Enter value for sections: 3
old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (5,'MBA',3)
1 row created.
select command:-
The SELECT statement is used to select data from a database.
Syntax:-
SELECT column1, column2, ... FROM table_name;
SELECT * FROM table_name;
Syntax:-
DELETE FROM table_name WHERE [condition];
1 row deleted.
alter command:-
The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
Syntax:-
ALTER TABLE table_name ADD column_name datatype;
alter table table_name add(column datatype);
Table altered.
12 rows selected.
update command:-
The UPDATE statement is used to modify the existing records in a table.
Syntax:-
UPDATE table_name SET column1 = value1, column2 = value2, ...
WHERE condition;
update table_name set condition;
12 rows updated.
12 rows selected.
8 rows selected.
group by clause:-
JOB SUM(SALARY)
------------------------------ -----------
Clerk 9000
Manager 215000
Analyst 5000
Salesman 11000
JOB COUNT(JOB)
------------------------------ ----------
Clerk 3
Manager 2
Analyst 1
Salesman 2
order by clause:-
Syntax:-
SELECT column_name(s) FROM table_name WHERE conditionORDER BY
column_name(s);
8 rows selected.
8 rows selected.
8 rows selected.
having clause:-
Syntax:-
SELECT column_name(s)FROM table_name WHERE condition GROUP BY
column_name(s) ;
JOB SUM(SALARY)
------------------------------ -----------
Clerk 9000
SQL> select Job,Sum(Salary) from Employee where Salary>3000 group by Job having
Job='Clerk';
JOB SUM(SALARY)
------------------------------ -----------
Clerk 4000
Find the sum of salaries of employees for each job title whose maximum
salary exceeds 10000.
JOB SUM(SALARY)
------------------------------ -----------
Manager 215000
commit command:-
Syntax:-
commit;
SQL> commit;
Commit complete.
rollback command:-
Syntax:-
ROLLBACK TO savepoint_name;
1 row deleted.
1 row deleted.
6 rows selected.
SQL> rollback;
Rollback complete.
no rows selected
SQL> rollback;
Rollback complete.
8 rows selected.
savepoint command:-
Syntax:-
SAVEPOINT savepoint_name;
6 rows selected.
SQL> rollback to xyz;
Rollback complete.
7 rows selected.
8 rows selected.
REPFOOTER:-
SQL*Plus displays the constants and variables in the order you specify them,
positioning and formatting each constant or variable as specified by the printspec clauses
that precede it.
REPHEADER:-
SQL*Plus displays the constants and variables in the order you specify, positioning and
formatting each constant or variable as specified by the printspec clauses that precede it.
RUN:-
RUN causes the last line of the SQL buffer to become the current line.
The slash command (/) functions similarly to RUN, but does not list the command in the
SQL buffer on your screen. The SQL buffer always contains the last SQL statement or PL/SQL
block entered.
SAVE:-
If you do not specify an extension, SQL*Plus assumes the default command-file
extension (normally SQL).
SET:-
SET CMDSEP + TTITLE LEFT 'SECTIONS' + COLUMN Sections FORMAT $99,999
SELECT Department,Sections FROM SIET WHERE Sections>6;
Show:-
SPOOL:-
Stores query results in a file, or optionally sends the file to a printer.
Represents the name of the file to which you wish to spool. SPOOL followed by
file_name begins spooling displayed output to the named file. If you do not specify an extension,
SPOOL uses a default extension (LST or LIS on most systems).
OFF
Stops spooling.
OUT
Stops spooling and sends the file to your host computer's standard (default) printer. This
option is not available on some operating systems.
TIMING:-
Records timing data for an elapsed period of time, lists the current timer's name and
timing data, or lists the number of active timers.
WHENEVER OSERROR:-
Performs the specified action (stops the current script by default) and returns focus to the
Input area if an operating system error occurs.
If you do not enter the WHENEVER OSERROR command, the default behavior of
SQL*Plus is to continue and take no action when an operating system error occurs.
Example:
The commands in the following script cause SQL*Plus to exit and COMMIT any pend-
ing changes if a failure occurs when reading from the output file:
Screen icon
WHENEVER SQLERROR:-
Performs the specified action (exits SQL*Plus by default) if a SQL command or PL/SQL
block generates an error.
Usage:
The WHENEVER SQLERROR command is triggered by SQL command or PL/SQL
block errors, and not by SQL*Plus command errors.
Example:
The commands in the following script cause SQL*Plus to exit and return the SQL error
code if the SQL UPDATE command fails:
Keyboard icon
BREAKS
BUFFER
COLUMNS
COMPUTES
SCREEN
SQL
TIMING:
Resets or erases the current value or setting for the specified option.
Terms:
Refer to the following list for a description of each term or clause:
BREAKS:
BUFFER:
Clears text from the buffer. CLEAR BUFFER has the same effect as CLEAR SQL, un-
less you are using multiple buffers (see the SET BUFFER command in Appendix C, "Obsolete
SQL*Plus Commands").
COLUMNS:
Resets column display attributes set by the COLUMN command to default settings for all
columns. To reset display attributes for a single column, use the CLEAR clause of the COL-
UMN command. CLEAR COLUMNS also clears the ATTRIBUTEs for that column.
COMPUTES:
Removes all COMPUTE definitions set by the COMPUTE command.
SCREEN:
Clears your screen.
SQL:
Clears the text from SQL buffer. CLEAR SQL has the same effect as CLEAR BUFFER,
unless you are using multiple buffers (see the SET BUFFER command in Appendix C, "Obso-
lete SQL*Plus Commands").
TIMING:
Deletes all timers created by the TIMING command.
Examples
To clear breaks, enter
Keyboard icon
CLEAR BREAKS:
To clear column definitions, enter
Keyboard icon
CLEAR COLUMNS:
COLUMN:-
Enter COLUMN followed by column or expr and no other clauses to list the current dis-
play attributes for only the specified column or expression. Enter COLUMN with no clauses to
list all current column display attributes.
Usage:
You can enter any number of COLUMN commands for one or more columns. All col-
umn attributes set for each column remain in effect for the remainder of the session, until you
turn the column OFF, or until you use the CLEAR COLUMN command. Thus, the COLUMN
commands you enter can control a column's display attributes for multiple SQL SELECT com-
mands.
When you enter multiple COLUMN commands for the same column, SQL*Plus applies
their clauses collectively. If several COLUMN commands apply the same clause to the same
column, the last one entered will control the output.
Examples:
To make the LAST_NAME column 20 characters wide and display EMPLOYEE NAME
on two lines as the column heading, enter
Keyboard icon
To format the SALARY column so that it shows millions of dollars, rounds to cents, uses
commas to separate thousands, and displays $0.00 when a value is zero, enter
Keyboard icon
COLUMN SALARY FORMAT $9,999,990.99
To assign the alias NET to a column containing a long expression, to display the result in a dol-
lar format, and to display <NULL> for null values, you might enter
Keyboard icon
ACCEPT:-
To display the prompt "Enter weekly salary: " and place the reply in a NUMBER vari-
able named SALARY with a default of 000.0, enter
Keyboard icon
To display the prompt "Enter date hired: " and place the reply in a DATE variable named
HIRED with the format "dd/mm/yyyy" and a default of "01/01/2001", enter
Keyboard icon
APPEND:-
To append a comma delimiter, a space and the column name CITY to the first line of the
buffer, make that line the current line by listing the line as follows:
Keyboard icon
1
Screen icon
1* SELECT DEPARTMENT_ID
Now enter APPEND:
Keyboard icon
APPEND , CITY
1
Screen icon
1* SELECT DEPARTMENT_ID, CITY
ARCHIVE LOG:-
Starts or stops automatic archiving of online redo log files, manually (explicitly) archives
specified redo log files, or displays information about redo log files.
To start up the archiver process and begin automatic archiving, using the archive destina-
tion specified in LOG_ARCHIVE_DEST, enter
Keyboard icon
Keyboard icon
Creating table:-
Syntax:-
Dropping table:-
Syntax:-
DROP TABLE table_name;
Altering table:-
Syntax:-
ALTER TABLE table_name ADD column_name datatype;
Syntax:-
CREATE VIEW view_name AS SELECT column1, column2, ...
View created.
10 rows selected.
View created.
Dropping of views:-
Syntax:-
Constraints;-
unique constraint:-
column level:-
SQL> /
Enter value for regno: 501
Enter value for name: Devi
Enter value for year: 2
old 1: insert into Department (Regno,Name,Year) values (&Regno,'&Name',&Year)
new 1: insert into Department (Regno,Name,Year) values (501,'Devi',2)
Table
level:-
3 Name varchar2(10),
4 Branch varchar2(5),
5 unique(Admno,Regno));
Table created.
1 row created.
SQL> /
Enter value for admno: 101
Enter value for regno: 401
Enter value for name: Radha
Enter value for branch: ECE
old 1: insert into College (Admno,Regno,Name,Branch) values
(&Admno,&Regno,'&Name','&Branch')
new 1: insert into College (Admno,Regno,Name,Branch) values(101,401,'Radha','ECE')
1 row created.
SQL> /
Enter value for admno: 101
Enter value for regno: 501
Enter value for name: Kumar
Enter value for branch: CSE
old 1: insert into College (Admno,Regno,Name,Branch) values
(&Admno,&Regno,'&Name','&Branch')
new 1: insert into College (Admno,Regno,Name,Branch) values
(101,501,'Kumar','CSE')
Primary key:-
3 Rating number(3),
4 Age number(3,1));
Table created.
1 row created.
SQL> /
Enter value for sid: 22
Enter value for sname: Lubber
Enter value for rating: 8
Enter value for age: 25.5
old 1: insert into Sailors(Sid,Sname,Rating,Age) values (&Sid,'&Sname',&Rating,&Age)
new 1: insert into Sailors(Sid,Sname,Rating,Age) values (22,'Lubber',8,25.5)
SQL> /
Enter value for sid:
Enter value for sname: Horatio
Enter value for rating: 9
Enter value for age: 34.5
old 1: insert into Sailors(Sid,Sname,Rating,Age) values (&Sid,'&Sname',&Rating,&Age)
new 1: insert into Sailors(Sid,Sname,Rating,Age) values (,'Horatio',9,34.5)
Table created.
1 row created.
SQL> /
Enter value for sid: 65
Enter value for bid: 102
Enter value for day: 09-Aug-17
old 1: insert into Reserves(Sid,Bid,Day) values (&Sid,&Bid,'&Day')
SQL> /
Enter value for sid: 31
Enter value for bid: 106
Enter value for day: 25-Aug-17
old 1: insert into Reserves(Sid,Bid,Day) values (&Sid,&Bid,'&Day')
new 1: insert into Reserves(Sid,Bid,Day) values (31,106,'25-Aug-17')
Check constraint:-
2 Name varchar2(10),
3 CD number(3) check(CD between 0 and 100),
4 DBMS number(3) check(DBMS between 0 and 100),
5 OS number(3) check(OS between 0 and 100));
Table created.
1 row created.
SQL> /
Enter value for sno: 502
Enter value for name: Swamy
Enter value for cd: 81
Enter value for dbms: 102
Enter value for os: 56
old 1: insert into Marksmemo(Sno,Name,CD,DBMS,OS) values
(&Sno,'&Name',&CD,&DBMS,&OS)
new 1: insert into Marksmemo(Sno,Name,CD,DBMS,OS) values (502,'Swamy',81,102,56)
Default constraint:-
Table created.
1 row created.
SQL> /
Enter value for sno: 502
Enter value for name: Rani
old 1: insert into Studentinfo(Sno,Name) values (&Sno,'&Name')
new 1: insert into Studentinfo(Sno,Name) values (502,'Rani')
1 row created.
Queries on joins:-
Inner joins:-
11 rows selected.
Outer joins:-
11 rows selected.
16 rows selected.
Cross join:-
44 rows selected.
Self join:-
Sub-Queries:-
in operator:-
Find the names of sailors who have reserved a boat number 103.
SQL> select S.Sname from Sailors s where s.Sid in (select r.Sid from Reserves r
where r.Bid=103);
SNAME
------------------------------
Dustin
Lubber
Horatio
SQL> select s.Sname from Sailors s where s.Sid in (select r.Sid from Reserves r,Boats b
where r.Bid=b.Bid and b.Colour='Red');
SNAME
------------------------------
Dustin
Lubber
Horatio
Bob
not in operator:-
Find the names of sailors who have not reserved a red boat.
SQL> select s.Sname from Sailors s where s.Sid not in (select r.Sid from Reserves r
where r.Bid in(select b.Bid from Boats b where b.Colour='Red'));
SNAME
------------------------------
Bretus
Andy
Rusty
Zorba
Horatio
Art
6 rows selected.
exists operator:-
Find the names of sailors who have reserved a boat number 103
SNAME
------------------------------
Dustin
Lubber
Horatio
Find the names of the sailors who have not reserved a boat number 103.
SQL> select s.Sname from Sailors s where not exists (select * from Reserves r
where s.Sid=r.Sid and r.bid=103);
SNAME
------------------------------
Bretus
Andy
Rusty
Horatio
Zorba
Art
Bob
7 rows selected.
op any:-
Find the sid's of sailors where rating is better than some sailors called Horatio.
SQL> select s1.Sid from Sailors s1 where s1.Rating>any (select s2.Rating from Sailors
s2 where Sname='Horatio');
SID
----------
58
71
74
31
32
op all:-
Find the sailors whose rating is better than every sailor called Horatio.
SQL> select s1.Sid from Sailors s1 where s1.Rating>all (select s2.Rating from Sailors s2
where Sname='Horatio');
SID
----------
58
71
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
OUTPUT:-
DECLARE
v_Name Student.Name%TYPE;
BEGIN
SELECT Name INTO v_Name FROM Student WHERE sno = 503;
DBMS_OUTPUT.PUT_LINE (v_Name);
END;
/
OUTPUT:-
DECLARE
a number := 17;
b number := 42;
BEGIN
dbms_output.put_line('Before swap');
dbms_output.put_line( 'a = ' || a );
dbms_output.put_line( 'b = ' || b );
SELECT a, b INTO b, a FROM dual;
dbms_output.put_line('After swap');
dbms_output.put_line( 'a = ' || a );
dbms_output.put_line( 'b = ' || b );
END;
/
OUTPUT:-
OUTPUT:-
declare
c_stmt constant varchar2(100) := 'select sysdate from ~t';
v_stmt varchar2(200);
v_date date;
begin
v_stmt := replace(c_stmt, '~t', 'dual');
dbms_output.put_line(v_stmt);
execute immediate v_stmt into v_date;
dbms_output.put_line('Today date is:'|| v_date);
end;
/
OUTPUT:-
declare
Total number;
Average number;
cursor c is select * from Student;
s Student %ROWTYPE;
begin
open c;
dbms_output.put_line('Name Sno CD DBMS OS Total Average Grade');
loop
fetch c into s;
Total:=s.CD+s.DBMS+s.OS;
Average:=floor(Total/3);
if(c % notfound)then
exit;
else
if(s.CD=90 and Average<=100)then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'S');
elsif(Average>=80 and Average=70 and Average<90)then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'A+');
elsif(Average>=70 and Average<80) then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'B');
elsif(Average>=60 and Average<70) then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'C');
else
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'D');
end if;
end if;
end loop;
close c;
end;
/
OUTPUT:-
DECLARE
S_id Student.Sno%type := 506;
S_name Student.Name%type;
S_DBMS Student.DBMS%type;
BEGIN
SELECT Name,DBMS INTO S_name, S_DBMS FROM Student WHERE Sno = S_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| S_name);
DBMS_OUTPUT.PUT_LINE ('DBMS: ' || S_dbms);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such STUDENT!');
END;
/
OUTPUT:-
declare
type Student_list is table of Student.Sno%type;
Students Student_list;
Student_name Student.Name%type;
Student_id Student.Sno%type;
begin
Students := Student_list(501,503,505);
for i in Students.first .. Students.last loop
select Name,Sno into Student_name,Student_id from Student where
Student.Sno=Students(i);
DBMS_OUTPUT.PUT_LINE (TO_CHAR(Students(i)) || ': ' || Student_name || ', '
|| Student_id );
END LOOP;
END;
/
OUTPUT:-
In PL/SQL there are three types of conditional control : IF, ELSIF and CASE
IF – THEN Statement:
This is the most basic kind of a conditional control and has the following structure.
If Condition Then
Statement 1;
…. Statement 2;
End If;
The reserved word IF marks the beginning of the IF statement.
Example:
Write a PL/SQL block to swap two numbers when the first number is greater than second
number ?
SQL> declare
a number(10) := &a;
b number(10) := &b;
c number(10);
begin
dbms_output.put_line('a value ='||a||' b value ='||b);
if a>b then
c := a;
a := b;
b := c;
end if;
dbms_output.put_line('a value ='||a||' b value ='||b);
end;
/
OUTPUT:-
IF – THEN – ELSE:
This statement enables you to specify two groups of statements One group of statements
is executed when the condition evaluates to TRUE and the other group of statements is executed
when the condition evaluates to FALSE.
If Condition Then
Statement 1;
ELSE
Statement 2;
End If;
Statement 3;
Example:
Q) Write a PL/SQL block to test whether the given number is odd or even.
SQL> declare
a number(10) := &a;
begin
if mod(a,2)=0 then
dbms_output.put_line('a value is even');
else
dbms_output.put_line('a value is odd');
end if;
end;
/
OUTPUT:-
ELSIF Statement:
If Condition 1 Then
Statement 1;
ELSIF Condition 2 Then
Statement 2;
ELSIF Condition 3 Then
Statement 3;
…
ELSE
Statement 4;
END IF;
Example:
Q) Write a PL/SQL block to find the grade of sailor for a given sid
10, 9, 8 – Grade A
7, 6, 5 – Grade B
other – Grade C.
SQL> declare
a number(10) := &a;
c number(10);
begin
select Rating into c from Sailors where Sid = a;
if c in (10,9,8) then
dbms_output.put_line('Sailor '||a||' has grade A');
elsif c in (7,6,5) then
dbms_output.put_line('Sailor '||a||' has grade B');
else
dbms_output.put_line('Sailor '||a||' has grade C');
end if;
end;
/
OUTPUT:-
CASE:
A case statement has the following structure:
CASE SELECTOR
WHEN EXPRESSION 1 STATEMENT 1;
WHEN EXPRESSION 1 STATEMENT 1;
…..
WHEN EXPRESSION 1 STATEMENT 1;
ELSE STATEMENT N+1;
END CASE;
The reserved word CASE marks the beginning of the case statement. A selector is a
value that determines which WHEN clause should be executed.
Example:
Q)Write a PL/SQL block to print the day name for a given date?
SQL> declare
a date := '&a';
b char(10);
begin
b := to_char(a,'D');
case b
when '1' then
dbms_output.put_line('today is sunday');
when '2' then
dbms_output.put_line('today is monday');
when '3' then
dbms_output.put_line('today is thuesday');
when '4' then
dbms_output.put_line('today is wednesday');
when '5' then
dbms_output.put_line('today is thrusday');
when '6' then
dbms_output.put_line('today is friday');
when '7' then
dbms_output.put_line('today is saturday');
end case;
end;
/
OUTPUT:-
ITERATIVE CONTROL:
In PL/SQL there are three types of loops : Simple LOOP, WHILE loops and Numeric FOR loop
A simple loop, as you can see from its name, is the most basic kind of loop and has the
following structure:
LOOP
STATEMENT 1;
STATEMENT 2;
…….
STATEMENT N;
END LOOP;
The reserved word LOOP marks the beginning of the simple loop. Statement 1 through N are a
sequence of statements that is executed repeatedly.
EXIT statement causes a loop to terminate when exit condition evaluates to TRUE.
Note: here numbers are printed 1 to 6 because this loop acts as do-while so it executes the statements
and then check the condition next.
LOOP
STATEMENT 1;
STATEMENT 2;
EXIT WHEN CONDITION;
…….
STATEMENT N;
END LOOP;
SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value'||a);
exit when a>5 ;
end loop;
end;
/
OUTPUT:-
WHILE LOOPS:
Example:
Q)Write a PL/SQL block to print number from 1 to 5 using while loop statements
SQL> declare
a number:=1;
begin
while a<5 loop
dbms_output.put_line('a value'||a);
a := a+1;
end loop;
end;
/
OUTPUT:-
SQL> DECLARE
num number(5);
rem number(5);
sm number(5):=0;
num1 number(5);
BEGIN
num :=#
num1 :=num;
while(num>0) loop
rem :=mod(num,10);
sm :=sm+rem;
num :=num/10;
end loop;
dbms_output.put_line('SUM OF DIGITS OF '||num1||' IS: '||sm);
end;
/
OUTPUT:-
A numeric FOR loop is called numeric because it requires an integer as its terminating value. Its
structure is as follows.
Example:
Q)Write a PL/SQL block to print number in reverse from 1 to 5 using for loop statements
SQL> begin
for a in reverse 1..5 loop
dbms_output.put_line('a value'||a);
end loop;
end;
/
OUTPUT:-
Modular code :
A PL/SQL module is any complete logical unit of work. There are four types of PL/SQL
modules:
1) anonymous blocks that are run with a text script( you have used until now),
2) Procedures,
3) Functions,
4) Packages.
There are two main benefits to using modular code: 1) it is more reusable and 2) it is
more manageable.
A procedure is a module performing one or more actions: it does not need to return any
value. The syntax for creating a procedure is
Example:
Create a procedure to add two number and call the block with a PL/SQL block?
SQL> declare
a number := &a;
b number := &b;
begin
sum(a,b);
end;
/
OUTPUT:-
FUNCTION:
The function does not necessarily have any parameters, but it must have a RETURN value
declared in the header, and it must return values for all the varying possible execution streams.
Create a function to add two number and return the value to a PL/SQL block.
OUTPUT:-
declare
a number:=10;
c number;
begin
c := f(a);
dbms_output.put_line('c value'||c);
end;
/
OUTPUT:-
PACKAGES:
We can use package as a method to bundle your functions and procedures, the first being that a
well designed package is a logical grouping of objects – such as functions, procedures, global variables
and cursors.
This contains information about the contents of the package, but not the code for the procedures
or functions. It also contains declarations of global/public variables. Anything placed in the declarative
section of a Pl/SQL block may be coded in a package specification.
The package body contains the actual executable code for the objects described in the package
specification. The package body contains code for all procedures and functions described in the
specification and may additionally contain code for objects not declared in the specification.
Use the following notation when calling packaged elements from outside of the package:
package_name.elements.
Example:
Create a package which contains a procedure and a function which will add two numbers?
Creating package:
SQL> create or replace package ex
as
procedure sum3(a in number,b in number);
function f1(a in number) return number;
end ex;
/
OUTPUT:-
Executing package:
SQL>declare
a number := &a;
c number;
begin
c := ex.f1(a);
ex.sum3(a,20);
dbms_output.put_line('c value'||c);
end;
/
OUTPUT:-
DECLARE
S_id Student.Sno%type := 506;
S_name Student.Name%type;
S_DBMS Student.DBMS%type;
BEGIN
SELECT Name,DBMS INTO S_name, S_DBMS FROM Student WHERE Sno = S_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| S_name);
DBMS_OUTPUT.PUT_LINE ('DBMS: ' || S_dbms);
EXCEPTION
OUTPUT:-
declare
type Student_list is table of Student.Sno%type;
Students Student_list;
Student_name Student.Name%type;
Student_id Student.Sno%type;
begin
Students := Student_list(501,503,505);
for i in Students.first .. Students.last loop
OUTPUT:-