This document outlines experiments to be conducted using Oracle's relational database management system software. It includes instructions for installing Oracle Database 10g, creating tables, inserting and updating records, modifying table structures, and performing various queries, functions, and operations. The goal is for students to learn relational database concepts and skills through hands-on practice of the listed 27 experiments.
This document outlines experiments to be conducted using Oracle's relational database management system software. It includes instructions for installing Oracle Database 10g, creating tables, inserting and updating records, modifying table structures, and performing various queries, functions, and operations. The goal is for students to learn relational database concepts and skills through hands-on practice of the listed 27 experiments.
This document outlines experiments to be conducted using Oracle's relational database management system software. It includes instructions for installing Oracle Database 10g, creating tables, inserting and updating records, modifying table structures, and performing various queries, functions, and operations. The goal is for students to learn relational database concepts and skills through hands-on practice of the listed 27 experiments.
This document outlines experiments to be conducted using Oracle's relational database management system software. It includes instructions for installing Oracle Database 10g, creating tables, inserting and updating records, modifying table structures, and performing various queries, functions, and operations. The goal is for students to learn relational database concepts and skills through hands-on practice of the listed 27 experiments.
The document discusses general instructions for students in a lab manual, hardware requirements for Oracle installation, list of experiments for RDBMS lab, and components of PL/SQL packages.
The minimum hardware requirements listed are 1GB RAM, requirement for swap space based on RAM size, 400MB free space in /tmp directory, 1.5-3.5GB free space for Oracle software, and 1.5GB free space for new Oracle database.
The different types of experiments covered in the RDBMS lab are installation of Oracle, creating and modifying tables, inserting and updating records, select command, querying tables using clauses, indexes, functions, joins, dates, sequences, synonyms, views, integrity constraints and PL/SQL.
SANKETIKA POLYTECHNIC COLLEGE
DIPLOMA IN COMPUTER ENGINEERING
CME II YEAR III SEMESTER LAB MANUAL FOR RELATIONAL DATABASE MANAGEMENT SYSTEM C-09
SANKETIKA POLYTECHNIC COLLEGE AFFILIATED TO STATE BOARD OF TECHNICAL EDUCATION AND TRAINING HYDERABAD
SANKETIKA POLYTECHNIC COLLEGE
1. Students should be regular and come prepared for the lab practice. GENERAL I NSTRUCTI ONS TO STUDENTS 2. In case a student misses a class, it is his/her responsibility to complete that missed experiment(s).
3. Students should bring the observation book, lab journal and lab manual. Prescribed textbook and class notes can be kept ready for reference if required.
4. They should implement the given experiment individually.
5. While conducting the experiments students should see that their programs would meet the following criteria:
Programs should be interactive with appropriate prompt messages, error messages if any, and descriptive messages for outputs. Programs should perform input validation (Data type, range error, etc.) and give appropriate error messages and suggest corrective actions. Comments should be used to give the statement of the problem and every function should indicate the purpose of the function, inputs and outputs Statements within the program should be properly indented Use meaningful names for variables and functions. Make use of Constants and type definitions wherever needed.
6. Once the experiment(s) get executed, they should show the program and results to the instructors and copy the same in their observation book.
7. Questions for lab tests and exam need not necessarily be limited to the questions in the manual, but could involve some variations and / or combinations of the questions.
SANKETIKA POLYTECHNIC COLLEGE
MINIMUM HARDWARE REQUIREMENTS At least, your system should meet the following requirements: 1GB RAM Requirement for swap space in Oracle installation is as follows: o Available RAM Swap Space Required o Between 1 GB and 2 GB 1.5 times the size of RAM o Between 2 GB and 8 GB Equal to the size of RAM o More than 8 GB .75 times the size of RAM 400MB free space in /tmp directory Depending on type of the installation, 1.5-3.5 GB free space for Oracle Software 1.5GB free space if new Oracle Database is created
SANKETIKA POLYTECHNIC COLLEGE
RDBMS LAB Subject Title : RDBMS LAB
Subject Code : CM- 309
Periods per week : 03
Periods per Semester : 45
1. Know installation of Oracle List of experiments 2. Exercise on creating tables 3. Exercise on inserting records 4. Exercise on updating records 5. Exercise on modifying the structure of the table 6. Exercise on Select command 7. Exercise on querying the table using clauses like WHERE, ORDER, IN, AND, OR, NOT 8. Exercise on creating and deleting of indexes 9. Exercise on various group functions 10. Exercise on Number functions, character functions, conversion functions and date functions 11. Exercise on set operators 12. Exercise on sub queries 13. Exercise on Joins 14. Exercise on various date and number format models 15. Exercise on Sequences 16. Exercise on synonyms 17. Exercise on views 18. Exercise on creating tables with integrity constraints 19. Write programs using PL/SQL control statements SANKETIKA POLYTECHNIC COLLEGE
20. Exercise on PL/SQL cursors 21. Exercise on PL/SQL exception handling 22. Exercise on Procedures 23. Exercise on Functions 24. Exercise on Recursion 25. Exercise on Triggers 26. Exercise on Packages 27. Exercise on Database Backup.
SANKETIKA POLYTECHNIC COLLEGE
To access data from database a query language is required. For this purpose in mid 1970s IBM developed a query language called as SEQUEL for its SYSTEM-R project. later it was renamed as SQL because the previous name is chosen by an aircraft company. INTRODUCTION Later in 1979 oracle corporation introduced the commercially available implementation of SQL. In 1986,ANSI standardized the SQL as a query language for RDBMS because SQL works with one specific type of database, called a relational database. SQL means Structured Query Language. It acts as an interface between oracle database and the user. SQL is an integral part of a database management system, a language and a tool for communicating with the RDBMS. SQL is not really a complete computer language like COBOL, C, C++, or J ava SQL is very easy to learn as it comprises of simple English words. SQL is not case sensitive language.
SANKETIKA POLYTECHNIC COLLEGE
SNO: 1 EXPERIMENT-1 DATE:
AIM Using the Oracle Universal Installer, you install the Oracle Database 10g software and create a database. Installing Oracle Database 10g on Windows To install the Oracle software, you must use the Oracle Universal installer. 1. For this installation you need either the DVDs or a downloaded version of the DVDs. In this tutorial, you install from the downloaded version. From the directory where the DVD files were unzipped, double- click setup.exe.
2. The Oracle Universal Installer starts.
SANKETIKA POLYTECHNIC COLLEGE
3. You will perform a basic installation with a starter database. Enter orcl for the Global Database Name and oracle for the Database Password and Confirm Password. Then click Next.
4. The installer now verifies that the system meets all the minimum requirements for installing and configuring the chosen product. Please correct any reported errors (warnings are OK) before continuing. When the check successfully completes (with or without warnings), click Next.
5. If you received any warnings, you can proceed. Click Yes. SANKETIKA POLYTECHNIC COLLEGE
6. Review the Summary window to verify what is to be installed. Then, click Install.
7. The progress window appears.
8. The Configuration Assistants window appears. SANKETIKA POLYTECHNIC COLLEGE
9. Your database is now being created.
10. When the database has been created, you can unlock the users you want to use. Click Password Management.
11. Unlock SH, OE and HR users by clicking on the check mark in the Lock Account? column. Enter the same name as the user in the New Password and Confirm Password fields. For example, to unlock SH user, enter SH in the New Password and Confirm Password fields. Then, click OK. SANKETIKA POLYTECHNIC COLLEGE
12. Click OK again.
13. Click Exit.
14. Click Yes to confirm exit. SANKETIKA POLYTECHNIC COLLEGE
SNO: 2 EXPERIMENT-2 DATE:
AIM EXERCISE ON CREATING TABLES DESCRIPTION The CREATE TABLE statement is used to create a table in a database. The data type specifies what type of data the column can hold. The empty table can be filled with data with the INSERT INTO statement. SYNTAX CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... ) PROGRAM CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), SANKETIKA POLYTECHNIC COLLEGE
City varchar(255) ) OUTPUT Table created. SQL>Select * from Persons P_Id LastName FirstName Address City
SNO: 3 EXPERIMENT-3 DATE:
AIM EXERCISE ON INSERTING RECORDS DESCRIPTION The INSERT INTO statement is used to insert new records in a table. It is also possible to only add data in specific columns. SYNTAX It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1, value2, value3,...) The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
PROGRAM INSERT INTO Persons VALUES (1,'Hansen', 'Ola', 'Timoteivn 10, 'Sandnes') SANKETIKA POLYTECHNIC COLLEGE
INSERT INTO Persons VALUES (2,'Svendson', 'Tove', Borgvn 23, 'Stavanger') OUTPUT
P_Id LastName Firstname Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Stavanger
SNO: 4 EXPERIMENT-4 DATE: AIM EXERCISE ON UPDATING RECORDS DESCRIPTION The UPDATE statement is used to update existing records in a table. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated. SYNTAX UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value PROGRAM UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='J akob' OUTPUT P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Stavanger 3 Tjessem J akob Nissestien 67 Sandnes If we had omitted the WHERE clause SANKETIKA POLYTECHNIC COLLEGE
PROGRAM UPDATE Persons SET Address='Nissestien 67', City='Sandnes'
AIM EXERCISE ON MODYFYING THE STRCTURE OF THE TABLE DESCRIPTION The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. SYNTAX To add a column in a table, use the following syntax ALTER TABLE table_name ADD column_name datatype To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column) ALTER TABLE table_name DROP COLUMN column_name
To change the column name in a table, use the following syntax
ALTER TABLE table_name RENAME COLUMN t.c1_newtype TO c1
PROGRAM SANKETIKA POLYTECHNIC COLLEGE
ALTER TABLE Persons ADD DateOfBirth date OUTPUT P_Id LastName FirstName Address City DateOfBirth 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
DROP COLUMN to delete the column named "DateOfBirth" in the "Persons" table DROP COLUMN is used. PROGRAM ALTER TABLE Persons DROP COLUMN DateOfBirth OUTPUT P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Stavanger 3 Tjessem J akob Nissestien 67 Sandnes
SANKETIKA POLYTECHNIC COLLEGE
SNO: 6 EXPERIMENT-6 DATE:
AIM EXERCISE ON SELECT COMMAND DESCRIPTION The SELECT statement is used to select data from a database. SYNTAX to select the content of the columns SELECT column_name(s) FROM table_name
to select all the columns from the "Persons" table. SELECT * FROM table_name
PROGRAM SELECT LastName,FirstName FROM Persons OUTPUT LastName FirstName Hansen Ola SANKETIKA POLYTECHNIC COLLEGE
Svendson Tove Tjessem J akob
To select all the columns from the "Persons" table. PROGRAM SELECT * FROM Persons OUTPUT P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Stavanger 3 Tjessem J akob Nissestien 67 Sandnes
SNO: 7 EXPERIMENT-7 DATE:
AIM EXERCISE ON QUERYING THE TABLE USING CLAUSES LIKE WHERE, ORDER, IN, OUT, AND, OR, NOT DESCRIPTION The WHERE clause is used to extract only those records that fulfill a specified criterion. The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY keyword sorts the records in ascending order. to sort the records in a descending order, you can use the DESC keyword. The IN operator allows you to specify multiple values in a WHERE clause. The AND operator displays a record if both the first condition and the second condition are true. The OR operator displays a record if either the first condition or the second condition is true. This operator negates a Boolean input. It could be used to reverse output of any other logical operator WHERE : SYNTAX SELECT column_name(s) FROM table_name WHERE column_name operator value PROGRAM SANKETIKA POLYTECHNIC COLLEGE
SELECT * FROM Persons WHERE City='Sandnes' OUTPUT P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Tjessem J akob Nissestien 67 Sandnes
ORDER BY SYNTAX SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC PROGRAM SELECT * FROM Persons ORDER BY LastName OUTPUT P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Stavanger 3 Tjessem J akob Nissestien 67 Sandnes
To sort the persons descending by their last name. PROGRAM SELECT * FROM Persons ORDER BY LastName DESC OUTPUT P_Id LastName FirstName Address City 3 Tjessem J akob Nissestien 67 Sandnes 2 Svendson Tove Borgvn 23 Stavanger 1 Hansen Ola Timoteivn 10 Sandnes
SYNTAX IN: SANKETIKA POLYTECHNIC COLLEGE
SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...) PROGRAM SELECT * FROM Persons WHERE LastName IN ('Hansen','Svendson') OUTPUT P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Stavanger SYNTAX AND: SELECT * FROM table_name WHERE column_name operator value AND column_name operator value PROGRAM SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson' OUTPUT P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Stavanger SYNTAX OR: SELECT * FROM table_name WHERE column_name operator value OR column_name operator value
PROGRAM SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola' OUTPUT SANKETIKA POLYTECHNIC COLLEGE
P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Stavanger SELECT column_name1,column_name2------column_namen FROM table_name WHERE NOT column_name operator value NOT: PROGRAM SELECT P_Id,LastName FROM Persons WHERE NOT city= 'Sandnes; OUTPUT P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Stavanger
SNO: 8 EXPERIMENT-8 DATE:
AIM EXERCISE ON CREATING AND DELETING OF INDEXES DESCRIPTION An index can be created in a table to find data more quickly and efficiently. The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading the whole table. Indexes, tables, and databases can easily be deleted/removed with the DROP statement. The DROP INDEX statement is used to delete an index in a table. SYNTAX CREATE INDEX index_name ON table_name (column_name) PROGRAM To create an index on a single column SANKETIKA POLYTECHNIC COLLEGE
create index custsity on customer(cust_city);
OUTPUT
To create an index on a combination of columns, you can list the column names within the parentheses, separated by commas: PROGRAM CREATE INDEX custcity_country<br> ON customer(cust_city,cust_country); OUTPUT
DROP INDEX The DROP INDEX statement is used to delete an index in a table.
SYNTAX
ALTER TABLE table_name DROP INDEX index_name PROGRAM CREATE INDEX emp_id_ind ON Orders ([Employee ID]); DROP INDEX Orders.emp_id_ind;
OUTPUT Index deleted
SANKETIKA POLYTECHNIC COLLEGE
SNO: 9 EXPERIMENT-9 DATE:
AIM EXERCISE ON VARIOUS GROUP FUNCTIONS DESCRIPTION SQL has many built-in functions for performing calculations on data. SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions: AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum AVG() FUNCTION SANKETIKA POLYTECHNIC COLLEGE
DESCRIPTION The AVG() function returns the average value of a numeric column. SYNTAX SELECT AVG(column_name) FROM table_name PROGRAM SELECT AVG(OrderPrice) AS OrderAverage FROM Orders OUTPUT OrderAverage 950
To find the customers that have an OrderPrice value higher than the average OrderPrice value. PROGRAM
SELECT Customer FROM Orders WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)
OUTPUT
Customer Hansen
Nilsen J ensen
COUNT() FUNCTION DESCRIPTION The COUNT() function returns the number of rows that matches a specified criteria. SYNTAX SQL COUNT(column_name) Syntax The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name SANKETIKA POLYTECHNIC COLLEGE
SQL COUNT(*) Syntax The COUNT(*) function returns the number of records in a table SELECT COUNT(*) FROM table_name SQL COUNT(DISTINCT column_name) Syntax The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column SELECT COUNT(DISTINCT column_name) FROM table_name PROGRAM SQL COUNT(column_name) SELECT COUNT(Customer) AS CustomerNilsen FROM Orders WHERE Customer='Nilsen' OUTPUT CustomerNilsen 2 SQL COUNT(*) SELECT COUNT(*) AS NumberOfOrders FROM Orders
Output NumberOfOrders 6
SQL COUNT(DISTINCT column_name) SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders
Output
NumberOfCustomers 3 FIRST() FUNCTION DESCRIPTION The FIRST() function returns the first value of the selected column. SANKETIKA POLYTECHNIC COLLEGE
SYNTAX SELECT FIRST(column_name) FROM table_name PROGRAM SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders if FIRST() function is not supported: SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1
OUTPUT ORDERPRICE 1000
LAST() FUNCTION DESCRIPTION The LAST() function returns the last value of the selected column. SYNTAX SELECT LAST(column_name) FROM table_name PROGRAM SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders If LAST() function is not supported SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1 OUTPUT LastOrderPrice 100 MAX() FUNCTION DESCRIPTIOM The MAX() function returns the largest value of the selected column. SYNTAX SANKETIKA POLYTECHNIC COLLEGE
SELECT MAX(column_name) FROM table_name PROGRAM SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders OUTPUT LargestOrderPrice 2000
MIN() FUNCTION DESCRIPTION The MIN() function returns the smallest value of the selected column. SYNTAX SELECT MIN(column_name) FROM table_name PROGRAM SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders OUTPUT SmallestOrderPrice 100
SUM() FUNCTION DESCRIPTION The SUM() function returns the total sum of a numeric column. SYNTAX SELECT SUM(column_name) FROM table_name PROGRAM SELECT SUM(OrderPrice) AS OrderTotal FROM Orders OUTPUT
SANKETIKA POLYTECHNIC COLLEGE
OrderTotal 5700
SNO: 10 EXPERIMENT-10 DATE: AIM EXERCISE ON NUMBER FUNCTIONS,CHARACTER FUNCTIONS, CONVERSION FUNCTIONS, AND DATE FUNCTIONS DESCRIPTION SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. It performs an operation and returns a single value.. SQL supports many functions. All the functions are categorized into 2 types. i. Single row functions. ii. Multiple row functions. 1) Single row functions: They work with data of a single row at a time. They are also called
scalar functions. The types of single row functions are: Numeric functions Character functions Date functions Conversion functions
Numeric functions: These functions operates on numeric data. They are: ABS MOD CEIL POWER SANKETIKA POLYTECHNIC COLLEGE
FLOOR ROUND LN SQRT LOG TRUNC We use dummy table called dual to perform these functions ABS DESCRIPTION It returns an absolute value of a given number.i.e; a positive number. SYNTAX ABS(expression) PROGRAM SELECT ABS(-17.36) FROM dual; OUTPUT
CEIL() FUNCTION DESCRIPTION This SQL CEIL() will rounded up any positive or negative decimal value within the function upwards. SYNTAX CEIL(expression) PROGRAM SELECT(CEIL(17.36)) FROM dual;
OUTPUT SANKETIKA POLYTECHNIC COLLEGE
FLOOR() FUNCTION DESCRIPTION The SQL FLOOR() rounded up any positive or negative decimal value down to the next least integer value. SYNTAX FLOOR(expression) PROGRAM SELECT FLOOR(17.36) FROM dual; OUTPUT
LN() FUNCTION DESCRIPTION The SQL LN() function returns the natural logarithm of n, where n is greater than 0 and its base is a number equal to approximately 2.71828183. SYNTAX LN(expression) PROGRAM SELECT LN(65) "natural_log of 65" FROM dual;
OUTPUT SANKETIKA POLYTECHNIC COLLEGE
MOD() FUNCTION DESCRIPTION This SQL MOD() function returns the remainder from a division. SYNTAX MOD( dividend, divider ) PROGRAM SELECT MOD(25,7) FROM dual; OUTPUT
LOG() FUNCTION DESCRIPTION LOG returns the logarithm, base m, of n. The base m can be any positive value other than 0 or 1 and n can be any positive value. SYNTAX LOG(X,Y) PROGRAM SELECT LOG(10,100) FROM DUAL;
OUTPUT
LOG(10,100)
SANKETIKA POLYTECHNIC COLLEGE
2 POWER() FUNCTION DESCRIPTION This SQL POWER() function returns the value of a number raised to another, where both of the numbers are passed as arguments. Syntax POWER( base, exponent ) PROGRAM SELECT POWER(2,3) FROM dual;
OUTPUT
ROUND() FUNCTION DESCRIPTION Returns the numeric value rounded off to the next value specified. SYNTAX ROUND(number, number of places) PROGRAM Select round(3.4573,2) from dual; OUTPUT
round(3.4573,2)
3.46
SQRT() FUNCTION SANKETIKA POLYTECHNIC COLLEGE
DESCRIPTION The SQL SQRT() returns the square root of given value in the argument. SYNTAX SQRT( expression ) PROGRAM SELECT SQRT(36) FROM dual; OUTPUT
TRUNC() FUNCTION
DESCRIPTION
The trunc function returns a number truncated to a certain number of decimal places
SYNTAX trunc( number, [ decimal_places ] )
PROGRAM select trunc(3.4573,2) from dual; OUTPUT
trunc
3.45
CHARACTER FUNCTIONS DESCRIPTION A character or string function is a function which takes one or more characters or numbers as parameters and returns a character value. LOWER() FUNCTION SANKETIKA POLYTECHNIC COLLEGE
DESCRIPTION The SQL LOWER() function is used to convert all characters of a string to lower case. SYNTAX LOWER(string) PROGRAM SELECT LOWER('TESTING FOR LOWER FUNCTION') AS Testing_Lower FROM dual;
OUTPUT
UPPER() FUNCTION DESCRIPTION The SQL UPPER() function is used to convert all characters of a string to uppercase. SYNTAX UPPER(string) PROGRAM SELECT UPPER('testing for upper function') AS Testing_Upper FROM dual;
OUTPUT
TRIM() FUNCTION DESCRIPTION SANKETIKA POLYTECHNIC COLLEGE
The SQL TRIM() removes leading and trailing characters(or both) from a character string. SYNTAX TRIM( [ [{LEADING | TRAILING | BOTH}] [removal_char] FROM ] target_string [COLLATE collation_name]) PROGRAM 1. SELECT TRIM(TRAILING '1' FROM 1234567896541) 2. AS TRAILING_TRIM 3. FROM dual; OUTPUT
LENGTH() FUNCTION DESCRIPTION LENGTH returns the number of characters in char. SYNTAX LENGTH (char)
PROGRAM select length(mohammed sami) from dual; OUTPUT LENGTH 13 LPAD DESCRIPTION Left pads a given string with a given character upto n number of characters. SYNTAX LPAD(char1,n [,char2]) SANKETIKA POLYTECHNIC COLLEGE
PROGRAM select lpad(ename,10,*) from emp; OUTPUT
Ename
*****Smith
******John
**Mohammed
LTRIM DESCRIPTION Trims a given string from left. SYNTAX LTRIM(char [, set]) PROGRAM select ltrim(GEORGE BUSH,GEORGE) from dual; OUTPUT Ltrim -------------- BUSH
RPAD DESCRIPTION Right pads a given string with a given character to n number of characters. SYNTAX RPAD(char1,n [,char2 ]) PROGRAM SANKETIKA POLYTECHNIC COLLEGE
DESCRIPTION Conversion functions convert a value from one datatype to another. The first datatype is the input datatype. The second datatype is the output datatype. To_char To_date To_char DESCRIPTION This function converts a date or number to a character string. SYNTAX to_char( value, [ format_mask ], [ nls_language ] )
PROGRAM to_char(sysdate, 'Month DD, YYYY'); OUTPUT TO_CHAR(SYSDATE, 'MONTH DD, YYYY'); --------------------------- J uly 09, 2003' THE TO_CHAR FUNCTION CONVERTS A NUMBER PROGRAM select to_char(12345.67,'99,999.9900') from dual; OUTPUT SANKETIKA POLYTECHNIC COLLEGE
TO_CHAR(1234 ------------ 12,345.6700 TO_DATE FUNCTION DESCRIPTION To_date function converts a string to a oracle date. SYNTAX TO_DATE ( String, [Format], [Optional Setting] ) PROGRAM SELECT TO_DATE('99-J AN-05','YY-MON-DD') FROM dual; OUTPUT 2099 01 05 00:00:00 MISCELLANEOUS FUNCTIONS DESCRIPTION Miscellaneous means mixed or heterogeneous. Nvl Decode Nvl DESCRIPTION It will substitute any null values in a table with a user defined value. SYNTAX NVL( string1, replace_with ) PROGRAM select empno,ename,sal,comm from emp; OUTPUT EMPNO ENAME SAL COMM --------- ---------- - -------- --------- SANKETIKA POLYTECHNIC COLLEGE
7369 SMITH 800 7499 ALLEN 1600 300 7521 WARD 1250 500 7566 JONES 2975 7654 MARTIN 1250 1400 7698 BLAKE 2850 7782 CLARK 2450 7788 SCOTT 3000 7839 KING 5000 9 rows selected. Except for empno 7499,7521,7654,7844 ,the commission for others are null.so to place commission as 100 in all places where there is null,we use nvl ( ) function. PROGRAM select empno,nvl(comm,100) from emp; OUTPUT EMPNO NVL(COMM,100) --------- - ------------ 7369 100 7499 300 7521 500 7566 100 7654 1400 7698 100 7782 100 Decode: Decode is a very useful and handy function for Oracle queries.see the following explanation to understand this function. It substitute values by using if-else-then logic. PROGRAM SANKETIKA POLYTECHNIC COLLEGE
PROGRAM SQL> select empno,decode(deptno,10,'computer',20,'ece',30,'eee','none') from employee;
OUTPUT EMPNO DECODE(D)
452 Computer 584 Ece 642 eee
DATE FUNCTIONS ADD_MONTHS(date,n) LAST_DAY(date) MONTHS_BETWEEN(date1 , date2) NEXT_DAY(date,day) ADD_MONTHS DESCRIPTION The add_months function returns a date plus n months. SYNTAX add_months( date1, n ) PROGRAM Select add_months(1-jan-05,5) from dual; OUTPUT ADD_MONTH
01-JUN-05
SANKETIKA POLYTECHNIC COLLEGE
LAST_DAY FUNCTION DESCRIPTION It returns the date of the last day of the month for a given date. SYNTAX last_day( date ) PROGRAM SQL>select LAST_DAY ('12-J AN-99') from dual; OUTPUT LAST_DAY
31-JAN-99
MONTHS_BETWEEN FUNCTION DESCRIPTION Function calculates the number of months between two dates and returns that difference as a number. SYNTAX months_between( date1, date2 ) PROGRAM SQL>select MONTHS_BETWEEN ('31-MAR-1995', '28-FEB-1994') from dual; OUTPUT MONTHS_BETWEEN('31-MAR-1995','28-FEB-1994') ----------------------------------------------------------------------- 13 NEXT_DAY DESCRIPTION This function returns the date of the first day after the specified date which falls on the specified day of the week. SANKETIKA POLYTECHNIC COLLEGE
SYNTAX PROGRAM NEXT_DAY(date,day) SQL>select NEXT_DAY ('15-AUG-2010','FRIDAY') from dual; OUTPUT NEXT_DAY --------- 20-AUG-10
SNO: 11 EXPERIMENT-11 DATE: AIM EXERCISE ON SET OPERATORS DESCRIPTION SET OPERATORS combines 2 or more queries into one result. The datatypes of corresponding columns must be same. The set operators are: UNION, INTERSECT, MINUS. UNION DESCRIPTION The UNION operator is used to combine the result-set of two or more SELECT statements.
SYNTAX SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 PROGRAM SANKETIKA POLYTECHNIC COLLEGE
SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA OUTPUT
INTERSECT DESCRIPTION Intersect only returns the rows that are found in all select statements. SYNTAX SELECT column_name(s) FROM table_name1 INTERSECT SELECT column_name(s) FROM table_name2; PROGRAM E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Scott, Stephen SANKETIKA POLYTECHNIC COLLEGE
SELECT E_Name FROM Employees_vizag INTERSECT SELECT E_Name FROM Employees_chennai; OUTPUT E_Name Stephen MINUS: DESCRIPTION The SQL MINUS query returns all rows in the first SQL SELECT statement that are not returned in the second SQL SELECT statement. Each SQL SELECT statement within the SQL MINUS query must have the same number of fields in the result sets with similar data types. SYNTAX SELECT column_name(s) FROM table_name1 MINUS SELECT column_name(s) FROM table_name2; PROGRAM SELECT E_Name FROM Employees_vizag MINUS SELECT E_Name FROM Employees_chennai; OUTPUT E_Name tom harry Peter
SNO: 12 EXPERIMENT-12 DATE: AIM EXERCISE ON SUB QUERIES SANKETIKA POLYTECHNIC COLLEGE
DESCRIPTION A query within another quey. A select statement whose output is substituted in the condition of another select statement .(A query is a statement written for returning specific data). The subquery is executed only once. A subquery is enclosed in parenthesis. There are three broad divisions of subquery: Single-row subqueries : The single-row Multiple-row subqueries : These subqueries return sets of rows. subquery returns one row. Correlated subqueries SINGLE-ROW SUBQUERIES DESCRIPTION The single-row subquery returns one row. PROGRAM SQL>select * from emp where sal =(select min(sal) from emp);
OUTPUT
EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO 7369 SMITH CLERK 7902 17-DEC-80 2800 20
MULTIPLE ROW SUB QUERY
DESCRIPTION These subqueries return sets of rows.
PROGRAM SQL>select empno,ename,job,sal,deptno from emp where deptno in (select deptno from dept where loc ='CHICAGO'); OUTPUT EMPNO ENAME JOB SAL DEPTNO 7499 ALLEN SALESMAN 3600 30 7524 WARD SALESMAN 3225 30 7654 MARTIN SALESMAN 3222 30 SANKETIKA POLYTECHNIC COLLEGE
3 rows selected.
SNO: 13 EXPERIMENT-13 DATE: AIM SANKETIKA POLYTECHNIC COLLEGE
EXERCISE ON JOINS Description The J OIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. Types of J OIN and the differences between them: JOIN: Return rows when there is at least one match in both tables LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table FULL JOIN: Return rows when there is a match in one of the tables INNER JOIN The INNER J OIN keyword returns rows when there is at least one match in both tables. SYNTAX SELECT column_name(s) FROM table_name1 INNER J OIN table_name2 ON table_name1.column_name=table_name2.column_name PROGRAM SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER J OIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName OUTPUT LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 SANKETIKA POLYTECHNIC COLLEGE
Pettersen Kari 77895 Pettersen Kari 44678 LEFT JOIN The LEFT J OIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2). SYNTAX SELECT column_name(s) FROM table_name1 LEFT J OIN table_name2 ON table_name1.column_name=table_name2.column_name PROGRAM SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT J OIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName OUTPUT LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 Pettersen Kari 44678 Svendson Tove RIGHT JOIN The RIGHT J OIN keyword returns all the rows from the right table (table_name2), even if there are no matches in the left table (table_name1). SYNTAX SELECT column_name(s) FROM table_name1 RIGHT J OIN table_name2 ON table_name1.column_name=table_name2.column_name SANKETIKA POLYTECHNIC COLLEGE
PROGRAM SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT J OIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName OUTPUT LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 Pettersen Kari 44678 34764 FULL JOIN The FULL J OIN keyword return rows when there is a match in one of the tables. SYNTAX SELECT column_name(s) FROM table_name1 FULL J OIN table_name2 ON table_name1.column_name=table_name2.column_name PROGRAM SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL J OIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName OUTPUT LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 SANKETIKA POLYTECHNIC COLLEGE
Pettersen Kari 44678 Svendson Tove 34764
SNO: 14 EXPERIMENT-14 DATE: SANKETIKA POLYTECHNIC COLLEGE
AIM EXERCISE ON VARIOUS DATE AND NUMBER FORMAT MODELS DESCRIPTION A format model is a character literal that describes the format of datetime or numeric data stored in a character string. A format model does not change the internal representation of the value in the database. In SQL statements, you can use a format model as an argument of the to_char and to_date functions to specify: The format for Oracle to use to return a value from the database The format for a value you have specified for Oracle to store in the database NUMBER FORMAT MODELS A number format model is composed of one or more number format elements. The number format models in the following functions: TO_CHAR TO_NUMBER TO_BINARY_FLOAT TO_BINARY_DOUBLE TO_CHAR FUNCTION DESCRIPTION To_char function converts a number or date to a string. SYNTAX to_char( value, [ format_mask ], [ nls_language ] )
PROGRAM SELECT to_char(21, '000099') FROM dual; OUTPUT 000021 TO_NUMBER DESCRIPTION The to_number function converts a string to a number. SYNTAX SANKETIKA POLYTECHNIC COLLEGE
PROGRAM SELECT to_number('546', '999') FROM dual; OUTPUT 546 TO_BINARY_FLOAT DESCRIPTION It returns a single-precision floating-point number. SYNTAX SELECT TO_BINARY_FLOAT(number) FROM table_name; PROGRAM SELECT dec_num, TO_BINARY_FLOAT(dec_num) FROM float_point_demo;
DATE FORMAT MODELS In the To_ datetime functions to translate a character value that is in a format other than the default format into a datetime value. The to_ datetime functions are TO_CHAR, TO_DATE, TO_TIMESTAMP, TO_TIMESTAMP_TZ TO_CHAR PROGRAM SELECT to_char(sysdate, 'Month DD, YYYY') FROM dual; OUTPUT J uly 09, 2003 TO_DATE The to_date function converts a string to a date. SYNTAX to_date( string1, [ format_mask ], [ nls_language ] ) PROGRAM SELECT to_date('2003/07/09', 'yyyy/mm/dd') FROM DUAL; OUTPUT SANKETIKA POLYTECHNIC COLLEGE
JULY 9,2003 TO_TIMESTAMP The to_timestamp function converts a string to a timestamp. SYNTAX to_timestamp( string1, [ format_mask ] [ 'nlsparam' ] ) PROGRAM SELECT to_timestamp('2003/12/13 10:13:18', 'YYYY/MM/DD HH:MI:SS') FROM DUAL;
OUTPUT 13-DEC-03 10.13.18.000000000 AM TO_TIMESTAMP_TZ Convert a character string to a value of TIMESTAMP WITH TIME ZONE SYNTAX to_timestamp_tz( string1 , [ format_mask ] [ 'nlsparam' ] )
PROGRAM SELECT TO_TIMESTAMP_TZ('1999-12-01 11:00:00 -8:00','YYYY-MM-DD HH:MI:SS TZH:TZM') FROM DUAL;
OUTPUT
TO_TIMESTAMP_TZ('1999-12-0111:00:00-08:00','YYYY-MM-DDHH:MI:SSTZH:TZM') -------------------------------------------------------------------- 01-DEC-99 11.00.00.000000000 AM -08:00
SNO: 15 EXPERIMENT-15 DATE: SANKETIKA POLYTECHNIC COLLEGE
AIM EXERCISE ON SEQUENCES DESCRIPTION Sequences are frequently used in databases because many applications require each row in a table to contain a unique value, and sequences provide an easy way to generate them. It is an object in oracle.It generates a series of numbers. It can generate unique sequential numbers for using a primary key column of a table. SYNTAX CREATE SEQUENCE [schema_name . ] sequence_name [ AS [ built_in_integer_type | user-defined_integer_type ] ] [ START WITH <constant>] [ INCREMENT BY <constant>] [ { MINVALUE [ <constant>] } | { NO MINVALUE } ] [ { MAXVALUE [ <constant>] } | { NO MAXVALUE } ] [ CYCLE | { NO CYCLE } ] [ { CACHE [ <constant>] } | { NO CACHE } ] [ ; ]
PROGRAM SQL>create sequence ss minvalue 1 maxvalue 10 start with 1 increment by 1;
OUTPUT Sequence created. PROGRAM SQL>select ss.nextval from dual; OUTPUT NEXTVAL --------- 1
SQL> select ss.nextval from dual; NEXTVAL --------- 2 SQL> select ss.nextval from dual; NEXTVAL SANKETIKA POLYTECHNIC COLLEGE
--------- 3 SQL> select ss.currval from dual; CURRVAL --------- 3 SQL> select ss.nextval from dual; NEXTVAL --------- 4 SQL>alter sequence ss 2 maxvalue 5; Sequence altered. PROGRAM SQL>select ss.nextval from dual; OUTPUT NEXTVAL --------- 5 PROGRAM SQL>select ss.nextval from dual; OUTPUT select ss.nextval from dual * ERROR at line 1: ORA-08004: sequence SS.NEXTVAL exceeds MAXVALUE and cannot be instantiated
PROGRAM SQL>drop sequence ss; OUTPUT Sequence dropped. PROGRAM SANKETIKA POLYTECHNIC COLLEGE
SQL>create sequence ss minvalue 1 maxvalue 5 start with 1 increment by 1; OUTPUT Sequence created. PROGRAM SQL>create table sports(spid number,spname varchar2(20)); Table created. SQL>insert into sports values(ss.nextval,'cricket'); 1 row created. SQL> insert into sports values(ss.nextval,'chess'); 1 row created. SQL> insert into sports values(ss.nextval,'tennis'); 1 row created. SQL> insert into sports values(ss.nextval,'football'); 1 row created. SQL> insert into sports values(ss.nextval,'hockey'); 1 row created. PROGRAM SQL> insert into sports values(ss.nextval,'volleyball'); OUTPUT insert into sports values(ss.nextval,'volleyball') * ERROR at line 1: ORA-08004: sequence SS.NEXTVAL exceeds MAXVALUE and cannot be instantiated SANKETIKA POLYTECHNIC COLLEGE
PROGRAM SQL>select * from sports; OUTPUT SPID SPNAME --------- -------------------- 1 cricket 2 chess 3 tennis 4 football 5 hockey SQL>drop sequence ss; OUTPUT Sequence dropped.
SNO: 16 EXPERIMENT-16 DATE: SANKETIKA POLYTECHNIC COLLEGE
AIM EXERCISE ON SYNONYMS DESCRIPTION A synonym is an alias or alternate name for a table, view, sequence, or other schema object. They are used mainly to make it easy for users to access database objects owned by other users. PROGRAM SQL>create synonym workers for emp; OUTPUT Synonym created. PROGRAM SQL>create synonym employees for workers; OUTPUT Synonym created. PROGRAM SQL>select * from workers; OUTPUT EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- ------------------------------------------- 7369 SMITH CLERK 7902 17-DEC-80 2800 20 7499 ALLEN SALESMAN 7698 20-FEB-81 3600 300 30 7521 WARD SALESMAN 7698 22-FEB-81 3250 500 30 7566 J ONES MANAGER 7839 02-APR-81 4975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 3250 1400 30 7698 BLAKE MANAGER 7839 01-MAY-81 4850 30 7782 CLARK MANAGER 7839 09-J UN-81 4450 10 7788 SCOTT ANALYST 7566 19-APR-87 5000 20 7839 KING PRESIDENT 7-NOV-81 7000 10 SANKETIKA POLYTECHNIC COLLEGE
PROGRAM SQL> drop synonym workers; OUTPUT Synonym dropped. PROGRAM SQL> select * from employee; OUTPUT select * from employee * ERROR at line 1: ORA-00942: table or view does not exist
SNO: 17 EXPERIMENT-17 DATE: SANKETIKA POLYTECHNIC COLLEGE
AIM EXERCISE ON VIEWS DESCRIPTION A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be seen. Views do not contain data of their own. They are used to restrict access to the database or to hide data complexity. A view is stored as a SELECT statement in the database. DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original table upon which the view is based. SYNTAX CREATE VIEW view_name AS SELECT column_list FROM table_name [WHERE condition]; PROGRAM CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS; View can also be queried as a table. SELECT * FROM CUSTOMERS_VIEW; OUTPUT | name | age | -------------------- | Ramesh | 32 | | Khilan | 25 | | kaushik | 23 | | Chaitali | 25 | | Hardik | 27 | | Komal | 22 | | Muffy | 24 |
UPDATE A VIEW PROGRAM UPDATE CUSTOMERS_VIEW SET AGE =35 SANKETIKA POLYTECHNIC COLLEGE
WHERE name='Ramesh'; OUTPUT
| ID | NAME | AGE | ADDRESS | SALARY | ------------------------------------------------------------ | 1 | Ramesh | 35 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ DELETING ROWS FROM A VIEW PROGRAM DELETE FROM CUSTOMERS_VIEW WHERE age =22; OUTPUT | ID | NAME | AGE | ADDRESS | SALARY | | 1 | Ramesh | 35 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ DROP A VIEW to drop the view if it is no longer needed. SYNTAX DROP VIEW view_name; PROGRAM DROP VIEW CUSTOMERS_VIEW;
OUTPUT View dropped
SANKETIKA POLYTECHNIC COLLEGE
AIM EXERCISE ON CREATING TABLES WITH INTEGRITY CONSTRAINTS DESCRIPTION Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement). We will focus on the following constraints: NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT By default, a table column can hold NULL values. SQL NOT NULL Constraint The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. SYNTAX (Column_name [data type] [NOT NULL], OR (Column_name data type [Constraint <name>] NOT NULL,
PROGRAM SQL>create table persons(pid number not null,lastname varchar2(20) not null,firstname varchar2(20)); OUTPUT Table created. PROGRAM SQL>insert into persons values(&pid,'&lastname','&firstname'); Enter value for pid: 1 SNO: 18 EXPERIMENT-18 DATE: SANKETIKA POLYTECHNIC COLLEGE
Enter value for lastname: priya Enter value for firstname: sri old 1: insert into persons values(&pid,'&lastname','&firstname') new 1: insert into persons values(1,'priya','sri') OUTPUT 1 row created. SQL> / Enter value for pid: Enter value for lastname: kavya Enter value for firstname: sri old 1: insert into persons values(&pid,'&lastname','&firstname') new 1: insert into persons values(,'kavya','sri') insert into persons values(,'kavya','sri') * ERROR at line 1: ORA-00936: missing expression
PROGRAM SQL> select * from persons; OUTPUT PID LASTNAME FIRSTNAME --------- -------------------- -------------------- 1 priya sri SQL 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. SYNTAX [Constraint <name>] UNIQUE (<column_name>); PROGRAM SQL>create table persons(pid number not null unique,lastname varchar2(20) not null,firstname SANKETIKA POLYTECHNIC COLLEGE
2 varchar2(20)); OUTPUT Table created. PROGRAM SQL> desc persons; OUTPUT Name Null? Type ----------------------------------------------------- -------- ----------------------------------- PID NOT NULL NUMBER LASTNAME NOT NULL VARCHAR2(20) FIRSTNAME VARCHAR2(20) PROGRAM SQL>insert into persons values(&pid,'&lastname','&firstname'); Enter value for pid: 1 Enter value for lastname: priya Enter value for firstname: sri old 1: insert into persons values(&pid,'&lastname','&firstname') new 1: insert into persons values(1,'priya','sri') OUTPUT 1 row created. SQL> / Enter value for pid: 1 Enter value for lastname: kavya Enter value for firstname: sri old 1: insert into persons values(&pid,'&lastname','&firstname') new 1: insert into persons values(1,'kavya','sri') insert into persons values(1,'kavya','sri') SANKETIKA POLYTECHNIC COLLEGE
* ERROR at line 1: ORA-00001: unique constraint (SCOTT.SYS_C001261) violated PROGRAM SQL> select * from persons; PID LASTNAME FIRSTNAME --------- -------------------- -------------------- 1 priya sri SQL 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. Each table should have a primary key, and each table can have only ONE primary key. SYNTAX (Column_name data type [Constraint <name>] PRIMARY KEY, PROGRAM SQL> create table persons(pid number primary key,lastname varchar2(20) not null,firstname 2 varchar2(20)); OUTPUT Table created. PROGRAM SQL> desc persons; OUTPUT Name Null? Type ----------------------------------------------------- -------- ----------------------------------- PID NUMBER LASTNAME NOT NULL VARCHAR2(20) SANKETIKA POLYTECHNIC COLLEGE
FIRSTNAME VARCHAR2(20) PROGRAM SQL>insert into persons values(&pid,'&lastname','&firstname'); Enter value for pid: 1 Enter value for lastname: priya Enter value for firstname: sri old 1: insert into persons values(&pid,'&lastname','&firstname') new 1: insert into persons values(1,'priya','sri') OUTPUT 1 row created. SQL> / Enter value for pid: 1 Enter value for lastname: kavya Enter value for firstname: sri old 1: insert into persons values(&pid,'&lastname','&firstname') new 1: insert into persons values(1,'kavya','sri') insert into persons values(1,'kavya','sri') * ERROR at line 1: ORA-00001: unique constraint (SCOTT.SYS_C001261) violated SQL> select * from persons; PID LASTNAME FIRSTNAME --------- -------------------- -------------------- 1 priya sri SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in another table. PROGRAM SANKETIKA POLYTECHNIC COLLEGE
SQL>create table persons(pid number(5) primary key,pname varchar2(20),city varchar2(20)); OUTPUT Table created. PROGRAM SQL>create table orders(oid number(5),orderno number(5),pid number(5),constraint fk_persons foreign key(pid) references persons(pid)); OUTPUT Table created. PROGRAM SQL>insert into persons values(&pid,'&pname','&city'); Enter value for pid: 1 Enter value for pname: madhu Enter value for city: delhi old 1: insert into persons values(&pid,'&pname','&city') new 1: insert into persons values(1,'madhu','delhi') OUTPUT 1 row created. SQL> 2 SP2-0226: Invalid line number SQL> / Enter value for pid: 2 Enter value for pname: nitish Enter value for city: kolkata old 1: insert into persons values(&pid,'&pname','&city') new 1: insert into persons values(2,'nitish','kolkata') OUTPUT 1 row created. SANKETIKA POLYTECHNIC COLLEGE
SQL> / Enter value for pid: 3 Enter value for pname: kamal Enter value for city: chennai old 1: insert into persons values(&pid,'&pname','&city') new 1: insert into persons values(3,'kamal','chennai') 1 row created. PROGRAM SQL> select * from persons; OUTPUT PID PNAME CITY --------- -------------------- -------------------- 1 madhu delhi 2 nitish kolkata 3 kamal Chennai
SANKETIKA POLYTECHNIC COLLEGE
PL/SQL INTRODUCTION The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL and the Oracle relational database. Following are notable facts about PL/SQL: PL/SQL is a completely portable, high-performance transaction-processing language. PL/SQL provides a built-in interpreted and OS independent programming environment. PL/SQL can also directly be called from the command-line SQL*Plus interface. Direct call can also be made from external programming language calls to database. PL/SQL's general syntax is based on that of ADA and Pascal programming language. Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.
FEATURES OF PL/SQL PL/SQL has the following features: PL/SQL is tightly integrated with SQL. It offers extensive error checking. It offers numerous data types. It offers a variety of programming structures. It supports structured programming through functions and procedures. It supports object oriented programming. It supports developing web applications and server pages. ADVANTAGES OF PL/SQL PL/SQL has the following advantages: SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications. PL/SQL give high productivity to programmers as it can query, transform, and update data in a database. PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object-oriented data types. Applications written in PL/SQL are fully portable. PL/SQL provides high security level. PL/SQL provides access to predefined SQL packages. PL/SQL provides support for Object-Oriented Programming. PL/SQL provides support for Developing Web Applications and Server Pages
SANKETIKA POLYTECHNIC COLLEGE
SNO: 19 EXPERIMENT-19 DATE: AIM WRITE A PROGRAM USING PL/SQL CONTROL STATEMENTS DESCRIPTION Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. PL/SQL programming language provides following types of decision making statements. IF - THEN statement IF-THEN-ELSE statement IF-THEN-ELSIF statement Case statement IF - THEN STATEMENT DESCRIPTION The IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. If the condition is TRUE, the statements get executed and if the condition is FALSE or NULL then the IF statement does nothing. SYNTAX: IF condition THEN S; END IF; PROGRAM DECLARE a number(2) :=10; BEGIN a:=10; -- check the boolean condition using if statement IF( a <20 ) THEN -- if condition is true then print the following dbms_output.put_line('a is less than 20 ' ); END IF; dbms_output.put_line('value of a is : ' || a); END; / OUTPUT a is less than 20 value of a is : 10
The IF-THEN-ELSIF statement allows you to choose between several alternatives SYNTAX IF(boolean_expression 1)THEN S1; -- Executes when the boolean expression 1 is true ELSIF( boolean_expression 2) THEN S2; -- Executes when the boolean expression 2 is true ELSIF( boolean_expression 3) THEN S3; -- Executes when the boolean expression 3 is true ELSE S4; -- executes when the none of the above condition is true END IF; PROGRAM DECLARE a number(3) :=100; BEGIN IF ( a =10 ) THEN dbms_output.put_line('Value of a is 10' ); ELSIF ( a =20 ) THEN dbms_output.put_line('Value of a is 20' ); ELSIF ( a =30 ) THEN dbms_output.put_line('Value of a is 30' ); ELSE dbms_output.put_line('None of the values is matching'); END IF; dbms_output.put_line('Exact value of a is: '|| a ); END; / OUTPUT None of the values is matching Exact value of a is: 100
PL/SQL procedure successfully completed.
CASE STATEMENT DESCRIPTION The CASE statement selects one sequence of statements to execute.
SYNTAX CASE selector WHEN 'value1' THEN S1; WHEN 'value2' THEN S2; WHEN 'value3' THEN S3; ... ELSE Sn; -- default case END CASE;
PROGRAM DECLARE grade char(1) :='A'; BEGIN SANKETIKA POLYTECHNIC COLLEGE
CASE grade when 'A' then dbms_output.put_line('Excellent'); when 'B' then dbms_output.put_line('Very good'); when 'C' then dbms_output.put_line('Well done'); when 'D' then dbms_output.put_line('You passed'); when 'F' then dbms_output.put_line('Better try again'); else dbms_output.put_line('No such grade'); END CASE; END; / OUTPUT Excellent
PL/SQL procedure successfully completed.
LOOP STATEMENTS DESCRIPTION A loop statement allows us to execute a statement or group of statements multiple times. PL/SQL provides the following types of loop to handle the looping requirements. WHILE LOOP FOR LOOP WHILE LOOP DESCRIPTION A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true. SYNTAX WHILE condition LOOP sequence_of_statements END LOOP; PROGRAM DECLARE a number(2) :=10; BEGIN WHILE a <20 LOOP dbms_output.put_line('value of a: ' || a); a :=a +1; END LOOP; END; / SANKETIKA POLYTECHNIC COLLEGE
OUTPUT value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
PL/SQL procedure successfully completed. FOR LOOP DESCRIPTION A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax: FOR counter IN initial_value .. final_value LOOP sequence_of_statements; END LOOP;
PROGRAM
DECLARE a number(2) ; BEGIN FOR a IN REVERSE 10 .. 20 LOOP dbms_output.put_line('value of a: ' || a); END LOOP; END; / OUTPUT value of a: 20 value of a: 19 value of a: 18 value of a: 17 value of a: 16 value of a: 15 value of a: 14 value of a: 13 value of a: 12 value of a: 11 value of a: 10
PL/SQL procedure successfully completed.
SANKETIKA POLYTECHNIC COLLEGE
SNO: 20 EXPERIMENT-20 DATE:
AIM EXERCISE ON PL/SQL CURSORS DESCRIPTION Oracle creates a memory area, known as context area, for processing an SQL statement, which contains all information needed for processing the statement, for example, number of rows processed etc. A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set. You can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors: Implicit cursors Explicit cursors
IMPLICIT CURSORS DESCRIPTION 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. PROGRAM 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; / OUTPUT 6 customers selected SANKETIKA POLYTECHNIC COLLEGE
PL/SQL procedure successfully completed.
EXPLICIT CURSOR DESCRIPTION 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. SYNTAX CURSOR cursor_name IS select_statement; PROGRAM 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; dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr); EXIT WHEN c_customers%notfound; END LOOP; CLOSE c_customers; END; / OUTPUT 1 Ramesh Ahmedabad 2 Khilan Delhi 3 kaushik Kota 4 Chaitali Mumbai
PL/SQL procedure successfully completed.
SANKETIKA POLYTECHNIC COLLEGE
SNO: 21 EXPERIMENT-21 DATE:
AIM EXERCISE ON EXCEPTION HANDLING DESCRIPTION An error condition during a program execution is called an exception in PL/SQL. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are two types of exceptions: Systen-defined exceptions User-defined exceptions
SYNTAX
DECLARE <declarations section> BEGIN <executable command(s)> EXCEPTION <exception handling goes here > WHEN exception1 THEN exception1-handling-statements WHEN exception2 THEN exception2-handling-statements WHEN exception3 THEN exception3-handling-statements ........ WHEN others THEN exception3-handling-statements END; PROGRAM DECLARE c_id customers.id%type :=&cc_id; c_name customers.name%type; c_addr customers.address%type;
-- user defined exception ex_invalid_id EXCEPTION; BEGIN IF c_id <=0 THEN RAISE ex_invalid_id; ELSE SELECT name, address INTO c_name, c_addr SANKETIKA POLYTECHNIC COLLEGE
FROM customers WHERE id =c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name); DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); END IF; EXCEPTION WHEN ex_invalid_id THEN dbms_output.put_line('ID must be greater than zero!'); WHEN no_data_found THEN dbms_output.put_line('No such customer!'); WHEN others THEN dbms_output.put_line('Error!'); END; /
OUTPUT Enter value for cc_id: -6 (let's enter a value -6) old 2: c_id customers.id%type :=&cc_id; new 2: c_id customers.id%type :=-6; ID must be greater than zero!
PL/SQL procedure successfully completed.
SANKETIKA POLYTECHNIC COLLEGE
SNO: 22 EXPERIMENT-22 DATE: AIM EXERCISE ON PROCEDURES DESCRIPTION Procedures these subprograms do not return a value directly, mainly used to perform an action. A procedure is created with the CREATE OR REPLACE PROCEDURE statement. SYNTAX CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN <procedure_body > END procedure_name;
PROGRAM DECLARE a number; b number; c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS BEGIN IF x <y THEN z:=x; ELSE z:=y; END IF; END;
BEGIN a:=23; b:=45; findMin(a, b, c); dbms_output.put_line(' Minimum of (23, 45) : ' || c); END; /
OUTPUT Minimum of (23, 45) : 23
SANKETIKA POLYTECHNIC COLLEGE
PL/SQL procedure successfully completed.
PROGRAM DECLARE a number; PROCEDURE squareNum(x IN OUT number) IS BEGIN x :=x * x; END; BEGIN a:=23; squareNum(a); dbms_output.put_line(' Square of (23): ' || a); END; /
OUTPUT Square of (23): 529
PL/SQL procedure successfully completed.
SANKETIKA POLYTECHNIC COLLEGE
SNO: 23 EXPERIMENT-23 DATE:
AIM EXERCISE ON FUNCTIONS DESCRIPTION A function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure and a function is, a function must always return a value, but a procedure may or may not return a value. A standalone function is created using the CREATE FUNCTION statement.
SYNTAX
CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] RETURN return_datatype {IS | AS} BEGIN <function_body > END [function_name];
PROGRAM DECLARE a number; b number; c number; FUNCTION findMax(x IN number, y IN number) RETURN number IS z number; BEGIN IF x >y THEN z:=x; ELSE Z:=y; END IF;
RETURN z; END; BEGIN a:=23; b:=45;
c :=findMax(a, b); SANKETIKA POLYTECHNIC COLLEGE
dbms_output.put_line(' Maximum of (23,45): ' || c); END; /
OUTPUT Maximum of (23,45): 78
PL/SQL procedure successfully completed.
SANKETIKA POLYTECHNIC COLLEGE
SNO: 24 EXPERIMENT-24 DATE:
AIM EXERCISE ON RECURSION DESCRIPTION A program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion. PROGRAM DECLARE num number; factorial number;
FUNCTION fact(x number) RETURN number IS f number; BEGIN IF x=0 THEN f :=1; ELSE f :=x * fact(x-1); END IF; RETURN f; END;
BEGIN num:=6; factorial :=fact(num); dbms_output.put_line(' Factorial '|| num || ' is ' || factorial); END; / OUTPUT Factorial 6 is 720
PL/SQL procedure successfully completed.
SANKETIKA POLYTECHNIC COLLEGE
SNO: 25 EXPERIMENT-25 DATE: AIM EXERCISE ON TRIGGERS DESCRIPTION Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are in fact, written to be executed in response to any of the following events: A database manipulation (DML) statement (DELETE, INSERT, or UPDATE). A database definition (DDL) statement (CREATE, ALTER, or DROP). A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). Triggers could be defined on the table, view, schema, or database with which the event is associated 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; PROGRAM 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; SANKETIKA POLYTECHNIC COLLEGE
/ OUTPUT Trigger created.
TRIGGERING A TRIGGER PROGRAM INSERT statement which will create a new record in the table: INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti', 22, 'HP', 7500.00 ); OUTPUT Old salary: New salary: 7500 Salary difference: UPDATE statement which will update an existing record in the table: UPDATE customers SET salary =salary +500 WHERE id =2; OUTPUT Old salary: 1500 New salary: 2000 Salary difference: 500
SANKETIKA POLYTECHNIC COLLEGE
SNO: 26 EXPERIMENT-26 DATE:
AIM EXERCISE ON PACKAGES DESCRIPTION PL/SQL packages are schema objects that groups logically related PL/SQL types, variables and subprograms. A package will have two mandatory parts: Package specification Package body or definition SYNATX CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END; PACKAGE SPECIFICATION PROGRAM CREATE PACKAGE cust_sal AS PROCEDURE find_sal(c_id customers.id%type); END cust_sal; / OUTPUT Package created. PACKAGE BODY PROGRAM CREATE OR REPLACE PACKAGE BODY cust_sal AS PROCEDURE find_sal(c_id customers.id%TYPE) IS c_sal customers.salary%TYPE; BEGIN SELECT salary INTO c_sal SANKETIKA POLYTECHNIC COLLEGE
FROM customers WHERE id =c_id; dbms_output.put_line('Salary: '|| c_sal); END find_sal; END cust_sal; / OUTPUT Package body created. USING PACKAGE ELEMENTS DECLARE code customers.id%type :=&cc_id; BEGIN cust_sal.find_sal(code); END; / OUTPUT Enter value for cc_id: 1 Salary: 3000