159
HYDERABAD NAME= “ Shaik Abdul Qader ” “ Shaik Abdul Qader ” ROLL NO=060-09-023 Contact me=9700064061 N izam I nstitute of C omputer S ciences (NICS) ( SQL , PL/SQL PROGRAMMING ) C C ONTENTS ONTENTS ____________________________________ PART-1 ===== PART-1 ===== DBMS DBMS PAGE.NO PAGE.NO Introduction to DBMS………………………………………………………………………. Advantages…………………………………………………………………………………… Data Abstraction…………………………………………………………………………….. Data Models………………………………………………………………………………….. DataBase Facilities…………………………………………………………………………. Structure of a DBMS……………………………………………………………………..… Different Type of Keys…………………………………………………………………..… PART-2 ===== PART-2 ===== SQL SQL . What is SQL………………………………………………………………………………….. SQL Statements…………………………………………………………………………….. 1.DDL , 2.DML , 3.DCL , 4.TCL , 5.DRL Differences between DDL , DML & DCL commands……………………………………………………………………………………. SQL (ALL) commands……………………………………………………………………… (i)SQL*PLUS commands DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I --- DBMS(LAB)RECORD DBMS(LAB)RECORD Page 2

AbdulQader MCA Dbms LAB Record

Embed Size (px)

Citation preview

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

C ONTENTS____________________________________

PART-1 ===== DBMS

PAGE.NO

Introduction to DBMS. Advantages Data Abstraction.. Data Models.. DataBase Facilities. Structure of a DBMS.. Different Type of Keys..

PART-2 ===== SQL.What is SQL.. SQL Statements.. 1.DDL , 2.DML , 3.DCL , 4.TCL , 5.DRL Differences between DDL , DML & DCL commands. SQL (ALL) commands (i)SQL*PLUS commands (ii)PL/SQL commands (iii)SQL commands DATA TYPES of SQL OPERATIONS OF THE SQL STATEMENTSDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

1.DDL , 2 DML , 3 TCL & 4.DRL

Built Functions *Number Function , *Character Function , *Date Function & *Group Function Set Operators Sub Queries (OR) Nested Queries.. Views Advantages Sequence Index Differences between SQL & PL/SQL. Dynamic SQL Embedded SQL

PART-3 ===== PL/SQL.Introduction to PL/SQL. Advantages Block Structure Variable & Constraints.. DataTypes of PL/SQL Architecture Trigger.. Advantages of trigger. Cursor

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

SQL , PL/SQL1.

PROGRAMS

Create a table to represent SB _account of a bank consisting of account_no,customer_name & bal_amount. Write a PL/SQL block to implement deposit & withdraw.Withdraw shoult not be allowed if the balance goes below Rs.1000. Create the following Two tables: College_info, consisting of field s :(college_code,college_name,address) Faculty_info, consisting of fields :-(college_code,faculty_code ,faculty_name ,qualification, experiences_in_no_of_years,address.) The field college_code is foreign key. (A)Design a form to accept the data from the user. (B)Generate queries ti do th following: ( i)List all those faculty members whose experience is greater than or equal to 10years & have M.TECH degree. (ii) List all those faculty members,who have atleast 10years of experience but,do not have M.TECH degree.

2.

3.

4.

Create the following tables for Library Information system: BOOK:(book_no,title,publisher,author,status) . STATUS could be issued,present in the library,sent for binding and cannot be issued. Write a trigger which sets the status of a book to cannot be issued,if it is a published 20years back. Create the BOOK table as in the 3rd program add one field as (data_of_purchase), AND Status could be as same as in that table. (A) Create a form to accept the data from the user with appropriate validation checks. (B) Generate queries to do the following:(i) List all those books which are new arrivals.The books which are acquired during the last 6 months are categorized as new arrivals. (ii) List all those books that cannot be issued and purchased 20 years back (or) ago. Create the following tables:DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

5.

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Introduction to DBMS

data and a set of programs to access that data. The collection of data is usually referred to as database. The primary goal of a database is to provide an environment that is both convenient and efficient to use in retrieving and storing database information. Database systems are designed to manage large bodies of information. The management of data involves both the definition of structures for the storage of information and provision of mechanisms for the manipulation of information. In addition, the database system must provide for the safety of the information stored, despite system crashes or attempts at unauthorized access. If data is stored among several users, the system must avoid possible anomalous results. Database systems overcomes the problems faced in fileoriented system. The database system are controlled by the Database Administrator (DBA) (OR) OR

A database management system (DBMS) consists of an interrelated

What is database? A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose. (OR) OR It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications.

Advantages of DBMS: Reduces Data redundancy (duplicity) and inconsistency of data. Provides data sharing facilities.DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Provides Data Integrity and Security. Provides Data Independence. Resolves concurrent access anomalies. ( SQL , PL/SQLPROGRAMMING

)

DATA ABSTRACTION: A database management system provides users with an abstract view of data, i.e. the system hides certain details of how the data is stored and maintained. This concern has lead to the design of complex data structures for the representation of data in the database. Its complexity is hidden from the users through several levels of abstraction in order to simplify the interaction between the user and the system. Physical Level: The lowest level of abstraction describes the data is actually stored in the database. Conceptual Level: The next-higher level of abstraction describes what data are actually stored in the database and the relationship that exists between them. This level is used by DBA, who must decide what information is to be kept in the database. View Level: The highest level of abstraction describes only a part of the entire database. DATA MODELS:

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) A data model can be defined as a collection of tools for describing data and the relationship between them.Data models can be classified into the following groups. Object oriented logical models. Record based logical models. Physical data models. Object oriented logical models: They are used in describing data at the conceptual and view levels. Some of the widely known models are Entity Relationship model(ER model): is based on real world perception which consists of collection of basic objects called Entities and relationships among these objects. Object oriented model: is based on collection of objects. An object contains instance variables within the object. An object also contains bodies of code that operate on the object, called methods. Record based logical models: They are used in describing data at the conceptual and view levels. As the database is structured in fixed-format records of several types, they are called as record based logical models. Some of the widely known models are: Relational model: represents data and relationships among data by a collection of tables, each of which has a number of columns with unique names. Network model: represents data by collection of records and relationships among data are represented by links which are viewed as pointers. Hierarchical model: represents data by collection of records, which are organized as trees rather than arbitrary graphs and relationships among data are represented by links which are viewed as pointers.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Physical models: They are used in describing data at the lowest level. DATABASE FACILITIES: Two main types of facilities are provided by a DBMS: Data definition facility or Data definition language (DDL). Data manipulation or Data manipulation language (DML). Data definition language (DDL): A database scheme is specified by a set of definitions which are expressed by a special language called Data definition language (DDL).The result of compilation of DDL statements is a set of tables which are stored in a special file called Data Dictionary. The storage structures and access methods used by the database system are specified by a set of definitions in a special type of DDL called Data storage and definition language. The result of compilation of these definitions is a set of instructions to specify the implementation details of the database schemes which are usually hidden from others. Data manipulation language (DML): A Data manipulation language (DML) is a language that enables users to access or manipulate data efficiently. Data manipulation means 1. Retrieval of information stored in the database. 2. Insertion of new information into the database. 3. Deletion of information from the database. 4. Modification of data stored in the database. There two types of DMLS: 1. Procedural DMLs requires a user to specify what data is need and how it get it.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) 2. Non Procedural DMLs requires a user to specify what data is needed without specifying how to get it. Query is a statement requesting the retrieval of information. A portion of a DML that involves retrieval is called query language. STRUCTURE OF A DBMS: The major components of this system are Data definition language compiler: The DDL compiler converts data definition statements into a set of tables. These tables contain metadata concerning the database. Data Manager: The data manager is the central software component of the DBMS.Its function is to convert operation queries coming from query processor or indirectly or an application program from the users logical view to physical file system. The data manager is responsible for interfacing the file system. File Manager: It is responsible for the structure of files and managing the file space and also for locating the block containing required record, requesting this block from the disk manager, and transmitting the required record to the data manager. Disk manager: The disk manager transfers the block containing the data requested by the file manager without the concern of physical characteristics of the underlying storage media.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Query Processor: The query processor is used to interpret the online users query and covert it into an efficient series of operations in a form capable of being sent to the data manager for execution. It uses data dictionary to find the structure of the relevant portion of the database and uses this information in modifying the query. Data Files: Data files contain data portion of the database. Data Dictionary: A data dictionary is a file that contains metadata. i.e. data about data. This file is consulted before actual data is read or deleted in the database system. Different types of Keys: Attribute: An object or an entity is characterized by its properties or attributes, they can also be referred as field.1. Primary key: An attribute to identify a record uniquely without

allowing any null values to be entered into it is called Primary key. Ex: empno attribute in the employee table and deptno attribute in dept table.2. Foreign key: An attribute which is a primary key in its own table and

is used as a reference in another table is called foreign key. 3. Super Key: A primary key with a combination of other attributes for unique identification is called super key. In other words primary key is a minimum super key. Ex: Empno along with ename is super key.4. Candidate Key: The super key for which no proper subset is a super

key such a minimal super key is a candidate key. Ex: Ename is a candidate key . S TRUCTURED Q UERY L ANGUAGE(SQL)

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) What is SQL?ANS:SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database. According to ANSI (American National Standards Institute), it is the standard language for relational database management systems. SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc. Although most database systems use SQL, most of them also have their own additional proprietary extensions that are usually only used on their system. However, the standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used to accomplish almost everything that one needs to do with a database. This tutorial will provide you with the instruction on the basics of each of these commands as well as allow you to put them to practice using the SQL Interpreter. ( SQL , PL/SQLPROGRAMMING

)

(OR) SQL is the official standard language used to access data held in the databases. SQL organizes data as tables , indexes , views etc. SQL is the tool for organizing , managing and retrieving data stored in the database. SQL provides various features like portability , clientserver architecture ,dynamic data definition , multiple views of data etc. (OR)SQL , commonly expanded as Structured Query Language, is a computer language designed for the retrieval and management of data in relational database management systems, database schema creation and modification, and database object access control management.[1][2] SQL (Structured Query Language) is a standard interactive and programming language for getting information from and updating a database. Although SQL is both an ANSI and an ISO standard, many database products support SQL with proprietary extensions to the standard language. Queries take the form of a command language that lets you select, insert, update, find out the location of data, and so forth. There is also a programming interface.

Procedural extensions SQL is designed for a specific purpose: to query data contained in a relational database. SQL is a set-based, declarative query language, not an imperative language such as C or BASIC.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

However, there are extensions to Standard SQL which add procedural programming language functionality, such as control-of-flow construct.

(OR)(Structured Query Language) Pronounced "S-Q-L" or "see-quill," a language used to interrogate and process data in a relational database. Originally developed by IBM for its mainframes, all database systems designed for client/server environments support SQL. SQL commands can be used to interactively work with a database or can be embedded within a programming language to interface to a database. Programming extensions to SQL have turned it into a full-blown database programming language, and all major database management systems (DBMSs) support the language. ANSI standardized SQL, but most database management systems (DBMSs) have some proprietary enhancement, which if used, makes SQL non standard. Moving an application from one SQL database to another may require tailoring to convert some command.

SQL Statements: SQL statements are divided into 1. Data Definition language(DDL) 2. Data Manipulation Language(DML) 3. Data Control Language (DCL) 4. Transaction Processing Language (TPL) 5. Data Retrieval Language (DRL) Data Definition Language (DDL): These statements define the structure of the database. DDL consists of create, alter and drop statements. Data Manipulation Language (DML): These statements are basically required to manipulate the records of the tabled consists of insert, delete, and update statements. Data Control Language (DCL): These statements are basically required to control the tables among several users by giving access or by taking back the access to the tables. DCL consists of grant and revoke statements. Transaction control language (TCL): These statements are basically related to various transactions like insert, delete, and update.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Data retrieval language (DRL): These statements are basically required to retrieve the records for the table. DRL consists of select statements.

What are the difference between DDL, DML and DCL commands?DDLData Definition Language (DDL) statements are used to define the database structure or schema. Some examples:

o o o o o o

CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed COMMENT - add comments to the data dictionary RENAME - rename an object

DMLData Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

o o o o o o o o

SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain MERGE - UPSERT operation (insert or update) CALL - call a PL/SQL or Java subprogram EXPLAIN PLAN - explain access path to data LOCK TABLE - control concurrency

DCLData Control Language (DCL) statements. Some examples:

o o

GRANT - gives user's access privileges to database REVOKE - withdraw access privileges given with the GRANT command

TCLDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

o o o o

COMMIT - save work done SAVEPOINT - identify a point in a transaction to which you can later roll back ROLLBACK - restore database to original since the last COMMIT SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

SQL up Difference between TRUNCATE, DELETE and DROP commands

DML statements can be rollbacked where DDL are autocommit.

DML commands can't beDML commands can't be rollback when a DDL command is executed immediately after a DML. DDL after DML means "auto commit". The changes will return on disk not on the buffer. If the changes return on the buffer it is possible to rollback not from the disk. Let me tell you the difference between DDL,DML,TCL and DCL: DDL COMMANDS: CREATE,ALTER,DROP AND TRUNCATE ARE CALLED DDL COMMANDS. They are called Data Definition since they are used for defining the data. That is the structure of the data is known through these DDL commands. DML COMMANDS: DML commands are used for data manipulation. Some of the DML commands insert,select,update,delete etc. Even though select is not exactly a DML language command oracle still recommends you to consider SELECT as an DML command.

TCL :For revoking the transactions and to make the data commit to the database we use TCL. Some of the TCL commands are: 1. ROLLBACK 2. COMMIT ROLLBACK is used for revoking the transactions until last commit. COMMIT is used for commiting the transactions to the database. Once we commit we cannot rollback. Once we rollback we cannot commit.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQL PROGRAMMING ) Commit and Rollback are generally used to commit or revoke the transactions that are with regard to DML commands.

DCL :Data Control Language is used for the control of data. That is a user can access any data based on the priveleges given to him. This is done through DATA CONTROL LANGUAGE. Some of the DCL Commands are: 1. GRANT 2. REVOKE. SQL statements are often divided into three categories: DML (Data Manipulation Language). These SQL statements are used to retrieve and manipulate data. This category encompasses the most fundamental commands including DELETE, INSERT, SELECT, and UPDATE. DML SQL statements have only minor differences between SQL variations. DML SQL commands include the following:o o o o

DELETE to remove rows. INSERT to add a row. SELECT to retrieve row. UPDATE to change data in specified columns.

DDL (Data Definition Language). These SQL statements define the structure of a database, including rows, columns, tables, indexes, and database specifics such as file locations. DDL SQL statements are more part of the DBMS and have large differences between the SQL variations. DML SQL commands include the following:o o o

CREATE to make a new database, table, index, or stored query. DROP to destroy an existing database, table, index, or view. DBCC (Database Console Commands) statements check the physical and logical consistency of a database.

DCL (Data Control Language). These SQL statements control the security and permissions of the objects or parts of the database(s). DCL SQL statements are also more part of the DBMS and have large differences between the SQL variations. DML SQL commands include the following:o o o

GRANT to allow specified users to perform specified tasks. DENY to disallow specified users from performing specified tasks. REVOKE to cancel previously granted or denied permissions.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

ALL SQL COMMAND DETAILSThe commands are listed in the following order: PL/SQL commands, and then SQL commands. SQL*PLUS COMMANDS:= SQL*Plus commands,

@ ACCEPT BTITLE COLUMN COPY DESCRIBE EXECUTE HELP LIST PROMPT RUNFORM SHOW START UNDEFINE WHENEVER SQLERROR

@@ APPEND CHANGE COMPUTE DEFINE DISCONNECT EXIT HOST PAUSE REMARK SAVE SPOOL TIMING VARIABLE

/ BREAK CLEAR CONNECT DEL EDIT GET INPUT PRINT RUN SET SQLPLUS TTITLE WHENEVER OSERROR

PL/SQL COMMANDS (Statements):=

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)CLOSE Statement GOTO Statement NULL Statement RETURN Statement EXIT Statement IF Statement OPEN Statement

( SQL , PL/SQL

PROGRAMMING

)

FETCH Statement LOOP Statement RAISE Statement

SQL COMMANDS:=

The SQL commands are divided into these categories:

* Data Definition Language commands * Data Manipulation Language commands * Transaction Control commands * Session Control commands * System Control commands

SQL Data Definition Language commands include the following:

ALTER CLUSTER ALTER DATABASE ALTER FUNCTION ALTER INDEX ALTER PACKAGE ALTER PROCEDURE ALTER PROFILE ALTER RESOURCE COST ALTER ROLE ALTER ROLLBACK SEGMENT

ALTER SEQUENCE ALTER SNAPSHOT ALTER SNAPSHOT LOG ALTER TABLE ALTER TABLESPACE ALTER TRIGGER ALTER USER ALTER VIEW ANALYZE AUDIT

COMMENT CREATE CLUSTER CREATE CONTROLFILE CREATE DATABASE CREATE DATABASE LINK CREATE FUNCTION CREATE INDEX CREATE PACKAGE CREATE PACKAGE BODY CREATE PROCEDURE

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)CREATE PROFILE CREATE ROLE CREATE ROLLBACK SEGMENT CREATE SCHEMA CREATE SEQUENCE CREATE SNAPSHOT CREATE SNAPSHOT LOG CREATE SYNONYM CREATE TABLE CREATE TABLESPACE CREATE TRIGGER CREATE USER CREATE VIEW DROP CLUSTER DROP DATABASE LINK DROP FUNCTION DROP INDEX DROP PROCEDURE DROP PROFILE DROP ROLE DROP ROLLBACK SEGMENT DROP SEQUENCE DROP SNAPSHOT DROP SNAPSHOT LOG DROP SYNONYM DROP TABLE DROP TABLESPACE DROP TRIGGER DROP USER DROP VIEW GRANT NOAUDIT RENAME REVOKE TRUNCATE UPDATE

( SQL , PL/SQL

PROGRAMMING

)

SQL Data Manipulation Language commands include the following:

DELETE EXPLAIN PLAN INSERT LOCK TABLE SELECTDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

SQL Transaction Control commands include the following:

COMMIT ROLLBACK SAVEPOINT SET TRANSACTION

SQL Session Control commands include the following:

ALTER SESSION SET ROLE

SQL System Control command (only one command):

ALTER SYSTEM

D ata T ypes in SQL:1.Varchar2(size): It is a variable length string with a max length of size bytes. 2. Char (size): It specifies a fixed length character string. Max size is 255 3. Number (n): It specifies integer type of data with max of n digits. 4.Number(p,s): It specifies floating number with p as total no of digits and specifies the number of digits to the right of decimal points. 5. Date: It specifies the date in DD-MM-YY format.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Data definition language (DDL):( SQL , PL/SQLPROGRAMMING

)

Create statement: It is used to create and define a table. Syntax: Create table ( [column constraints], [column constraints], . . . [column constraints]) ; Column constraints :1. Primary Key: It will not allow null and duplicate values corresponding 2. 3. 4. 5. 6. 7.

to that column. Not Null : It will allow null values corresponding to that column Unique: It will not allow duplicate values corresponding to that column. Check: It will impose the constraints based on the condition being mentioned on the column. Reference( foreign key): It will impose the constraints based on the condition being mentioned on the column Reference (foreign key): It will refer to other column values that are acting as primary key in other table. On delete cascade: It will delete the values in the column in one table, corresponding values in other table will be deleted automatically, and it will work only references only.

Example 1: Create a table employee with employee no as primary key, name field not be left empty, salary greater than 2000,job field not to be left empty,deptno is foreign key taken from dept table.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Example 2: Create dept table with deptno as primary key and dept name as not null. SQL>Create table Dept (Deptno number(3) primary key, Dname varchar2(10) not null); Example 3: Create a customer table. SQL>Create table Customer (Cust_id number(5) primary key, First_name varcahr2(20) not null, Last_name varchar2(20) not null, Address varchar2(40), City varchar2(20), State varchar2(20), Phone_no number(9) unique); Table Level Constraints: Imposing constraints after declaring all the columns of the table, then we call it as table level constraints. Example 4: Create project table. SQL>Create table ProjectM.C.A II/I--D B M S( L A B) R E CO R D

DBMS=LAB-V{NOV/DEC-2009}

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) (Emp_id number(5), Proj_id number(5), Payment number(8), Primary key(Emp_id,Proj_id); Create with Select: To create a table from taking the records from existing table. When creating a table based on existing table then it is going to transfer only not null constraint, other constraints will not be transferred. Example 1: SQL>Create table Emp As select Empno, Ename, Salary from Employee; Create with select using where clause: Example 2: Create a table empno containing the details in deptno 10 only SQL>Create table Empd As select * from Employee Where deptno=10; Alter Statement: It is used to alter the definition of a table in the database Syntax: Alter table Add column_name data_type [Modify column_name data_type ]; Add: is used when ever you want to add a new column to the table. Example 1: Adding Phno as a new field into Employee table SQL>Alter table Employee Add(Phno number(7)); Example 2: Adding empno as primary key to Emp tableDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

( SQL , PL/SQL

PROGRAMMING

)

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

SQL>Alter table Emp Add(Primary key(empno)); Modify: is used to change the size of the column of the same data type.Modify will not decrease the column size.Whenever it comes to increase in the size of column it is going to allow only when the field is empty. Example 1: Modify the salary field by increasing its size. SQL>Alter table Emp Modify(sal number(9,2)); Droping the Constraints: Example1: Dropping Primary key constraint we must see that no references are there from other tables. SQL>Alter table Emp Drop Primary key; Drop command: is used to drop the table. Syntax: Drop table; Example 1: Dropping emp table. SQL>Drop table emp; Describe command: is used to display the structure of the table.Desc can also be used

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Data Manipulation Language (DML): Insert command: is used to add rows(or records) to the table. The number and sequence should match that of columns in the table.If the number of data values is less, then specify the column names into which data is being entered. To insert null values, NULL can be used. Syntax: Insert intovalues(datavalue_1, ..,datavalue_n); Insert into(column_1,column_3) Values(datavalue_1,datavalue_3); Example 1: Insert 100th record into employee table.

SQL>insert into employee Values(100,James,6000,17-Mar-03); Example 2: Inserting 101th record into employee table with salary and date Of joining as null values. SQL>Insert into employee Values(101,James,null,null);DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Example 3: Inserting 1001th record into employee table with only empno and name. SQL>Insert into employee(empno,ename) Values(1001,John); Insert with select: is used to transfer the data from one table to another table. Syntax: Insert into Select , from Where; Example 1: SQL>Insert into emp Select empno,ename,sal from employee Where deptno=10; Delete Command: is used to delete the records from the specified table. Syntax: Delete Where; Example 1: Deleting the employee holding empno1001 SQL> Delete employee where empno = 1001; Example 2 : Delete all the records of the employee table SQL> Delete employee; Example 3: Delete the employees who are working as clerks. SQL> Delete employee where job =clerk Update command: is used to modify the records of the table Syntax: Update Set = , .DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) . . Where ;( SQL , PL/SQLPROGRAMMING

)

Example1: Increase all the employees salary by Rs. 500 SQL> update employee set sal=sal+500; Example2: Give an increment of 20% salary and commission by 5%of salary SQL> update employee set sal = sal* 1.2, comm = (sal* 0.05) +comm; Example3: Promote the manager as director of the company SQL> update employee set job =director where job= manager; Example4: Give an increment of 10% salary whose salary is less than Rs. 1000 SQL> update employee set sal = sal*1.1 where sal insert into employee( empno, ename) values (200, smith); SQL> commit ;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Roll back command: is used to undo the transactions up to the last commit. SQL> Rollback; Savepoint: is used to minimize roll back only to certain transactions Example: SQL> insert SQL> savepoint ins; SQL> update . SQL> savepoint upd SQL> delete . SQL> savepoint del; SQL> Rollback; SQL> commit; SQL> Rollback to del;(Once you commit and then give rollback, will remove all save points) Autocommit command: is used to make all DML transactions to save implicitly after the execution of the command. SQL> set autocommit on; SQL> set autocommit off; To see the status of autocommit we use show command. SQL> show autocommit; Data Retrieval language(DRL); Select command: is used to retrieve the records from the table. Syntax: Select < field_name_1>, .. , from where ;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL Example 1: To display the deptno,dname,loc.PROGRAMMING

)

Example 2: To display all the employee details,who are working as manager. SQL>Select * from emp where job-manager; Logical Operators: And Or Not Example 1: To display the employee information who are working in deptno 10 and salary greater than 2000. SQL>select * from emp Where deptno=10 and sal>2000; Example 2: To display the employee information who are working as manager corresponding to deptno 20. SQL>select * from emp Where job=manager and depno=20; Example 3: To display the employee information who are working in deptno 10,20. SQL>select * from emp Where deptno=10 or dept=20;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Example 4: To display the employee information who are working as managers corresponding to deptno 10 as well as the employees who are receiving salary more than 2000 corresponding to deptno 20. SQL>select * from emp Where job=manager and deptno=10; Special Operators: Is null In Between like is null: is used to check the null values corresponding to the column. Example 1: To display the employee information who are not receiving any commission. SQL>select * from emp Where comm Is null; Between: Whenever we want to frame the condition in the range of values then we use the between operator. Example1: To display the employee information whose salary is greater than 1000 and less than 2000. SQL>select * from emp Where sal between 1000 and 2000; Example 2: To display the employee information for those who are working for deptno 10 with their first alphabet of the name is coming in the range of e to j. SQL>select * from emp Where deptno=10 and(ename between E and J);

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) In: When you have multiple conditions among which any one has to be selected we use in operator. Example 1: To display the employee details who are working as managers ,clerks ,analyst. SQL>select * from emp Where job in(manager,clerk,analyst); Example 2:To display the employee who are working in the deptno 10,20,30. SQL>select * from emp Where deptno in (10,20,30); Like: is used when you want to frame a condition based on a

particular pattern, for which we need wild card characters, which are % and _. % is used to replace any no.of characters in the pattern. _ is used to replace only single characters in the pattern. Example 1: To display the employee details whose names are ending with s. SQL>select * from emp Where ename like%s; Example 2: To diplay the employee names have onlay 5 characters. SQL>select * from emp Where ename like_____; Example 3: To display the employee details whose name has a as second character and r as last character. SQL>select * from emp Where ename like_a%r; Special operators with not: Example1: To display the employee information who are receiving any commission. SQL>select * from empDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Where comm. Is not null;( SQL , PL/SQLPROGRAMMING

)

Example 2:To display employee information for whose who are working as managers and receiving salary other than the range 2000 to 3000. SQL>select * from emp Where job=manager and sal not between 2000 and 3000; Example 3:To display the employee details who are working in dept other than 20,30. SQL>select * from emp Where deptno not in (20,30); Example 4:To display the employee details who are working in deptno 10,20 for their names not ending with s. SQL>select * from emp Where deptno in(10,20) and ename not like %s;

In built functions: Are classified into five types o Number Functions o Character FunctionsDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) o Date functions o Group functions Group Functions: 1. Sum(expr) 4.count(*) 2. avg(expr) 5. Max(expr) 3. count(expr) 6. min(expr)( SQL , PL/SQLPROGRAMMING

)

1. Sum(expr): Is used to find total sum of the attribute or field mentioned. Example 1: Find the sum of total salary being paid to all the employees of the organizations. SQL>select sum(sal) from emp; Example 2: Find the sum of salary and commission paid to the employees of deptno 10. SQL>select sum(sal+comm.) from emp Where deptno=10; 2. avg(expr): Is used to find the average of the attribute being mentioned. Example: Find the average amount salary being paid to each employee. SQL>select avg(sal) from emp; 3.Count(*): Is used to count the no.of records in the table,where the empty record is also counted. Example 1: find the no.of employees working in the organization. SQL>select count(*) from emp; Example 2:find the no.of employees working as managers and clerks in the organization. SQL>select count(*) from emp Where job in(manager,clerk); 4.count(expr): Is used to count the no.of records will the expr is satisfied.If a record has a null value it will not count that record.M.C.A II/I--D B M S( L A B) R E CO R D

DBMS=LAB-V{NOV/DEC-2009}

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Example 1: Find the no.of employees who are receiving the commission. SQL>select count(comm.) from emp; Example 2: Find the no.of employees who are receiving the commission corresponding to deptno.10,20. SQL>select count(comm) from emp Where deptno=10 or deptno=20; 5.max(expr): Is used to find the maximum value for the mentioned numerical attribute. Example 1: Find the employees who is paid the highest salary. SQL>select max(sal) from emp; 6.min(expr): Is used to find the minimum value for the mentioned numerical attribute. Example: find the employees who is paid the least salary. SQL>select min(sal) from emp;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Numerical Functions: abs(n) sqrt(n) power(n) mod(n)( SQL , PL/SQLPROGRAMMING

)

1.abs(n): Is used to find the absolute value of n.dual is dummy table for Temporary manipulation. SQL>select abs(-5) from dual; 2.sqrt(n): Is used to find the square root of n. SQL>select sqrt(36) from dual; 3.power(n): Is used to find the value of m to the power of n. SQL>select power(3,2) from dual; 4.mod(m,n): Is used to find the remainder after dividing m by n. SQL>select mod(5,2) from dual;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

CHARACTER FUNCTIONS: Length(str) Concate(str1,str2) Substr(str,pos,n) Ascii(char) Chr(n) 1. length(str): Returns the length of the string mentioned. SQL>select length(student) from dual; 2. concat(str1,str2): Joints string1 and string2 ot form a new string.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) SQL>select concat(aaaa,bbbb) from dual; 3. substr(str,pos,n): Returns the substring from the string from position pos cut n characters. SQL>select substr(student,3,4) from dual; 4. ascii(char): Returns the ascii value of the mentioned character. SQL>select ascii(a) from dual; 5.chr(n): Returns the character for the ascii value n mentioned. SQL>select chr(68) from dual; 6.lower(str): Converts the given string into lower case. SQL>select lower(AAAA) from dual;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

8. upper(str): Converts the given string into upper case. SQL>select upper(dddd) from dual; DATE FUNCTIONS: 1. add months(date,n): To add or remove given n months to the given data.Sysdate gives the system date. SQL>select sysdate from dual; SQL>select add_month(sysdate,3) from dual;DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

2. months between(date1,date2): Returns the no.of months between the two dates mentioned.Date1 is maximum value and date2 is minimum value.The output of this function is either float or integer value. SQL>select months_between(29-oct-03,29-apr-03) from dual; 3. Last day(date): Returns the last day in the month specified by the date mentioned. SQL>select last_day(sysdate) from dual;

Group by clause: Is used to group a set of repeated values corresponding to a particular column for which we want to apply group function. Example 1: To display the deptno. And total salary in each dept.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) SQL>select deptno,sum(sal) from emp Group by deptno; Example 2: To display the depts highest,lowest salary and no.of employees in each dept. SQL>select deptno,max(sal),min(sal),count(*) from emp group by deptno; Example 3: To display the no.of employees receiving commission corresponding to deptno 10,20 with their deptno. SQL>select deptno,count(comm.) from Emp where deptno=10 or deptno=20 Group by deptno;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) Having Clause: Is used when we want to frame the condition of salary is greater than cannot be used with where clause. Example 1: To display the deptno.s for which total amount of salary is greater than 10,000. SQL>select deptno,sum(sal) from emp Group by deptno Having sum(sal)>10000; Example 2: To display the deptno.s along with their total salary for which total salary is greater than 10,000 corresponding to deptno 10,20. SQL>select deptno,sum(sal) from emp Where deptno in (10,20) Group by deptno Having sum(sal)>10000; Example 3 : To display the jobs along with the no.of employees working ,provided the highest salary corresponding to the job is greater than 3000 as well as the no.of employees working is more than 3. SQL>select job,count(*) from emp Where deptno in (10,20,30) Group by job Having max(sal)>2000 and count(*)>2;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Order by clause: Is used when we want to display the data in a sorted order. 1. Ascending order |asc| (default ordering) 2. Descending |desc| Example 1: To display the employee information in the ascending order of the empno. SQL> select * from emp Oreder by empno; Example 2: To display the employee information in the descending order of the salary. SQL>select * from emp Order by sal desc; Example 3: To display the employee information in the ascending order of the deptno,descending order of salary. SQL>select * from emp Order by deptno,sal desc;DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Example 4: To display the depts along with their total payment corresponding to deptno 10,20,30 for which n0.of employees are working is more than 2 and display based on the descending order of total salary. SQL>select deptno,sum(sal) from emp Where deptno in (10,20,30) Group by deptno Having count(*)>2 Order by sum(sal) desc;

SET OPERATORS: Union Intersection Minus1. union: Is used to take distinct rows from more than one select

statement.By using union all the duplication is not removed.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL Example 1: To display in deptno the jobs. 10 or 20. SQL>select job from emp Where deptno=10 Union Select job from emp Where deptno=20; Example 2: To display the jobs from emp. SQL>select job from emp Where deptno=10 Union all Select job from emp Where deptno=20; 2.intersect: Is used to take common rows from more than one select statement. Example 1: To dispalyb the jobs in deptno. 10 and 20. SQL>select job from emp Where deptno=10 Intersect Select job from emp Where deptno=20; Example 2:To disaply the jobs in deptno. 10 and (20 or 30). SQL>select job from emp Where deptno=10 Intersect (select job from emp Where deptno=20 Union Select job from emp Where deptno=30);2. minus: Is used to select the rows from more than first selectPROGRAMMING

)

statement which are not in the second statement. Example 1: To display the jobs in deptno.10 and not in 20.DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) SQL>select job from emp Where deptno=10 Minus Select job from emp Where deptno=20; Example 2: To list the jobs which are unique to dept 10 as compare to 20 and 30. SQL>(select job from emp Where deptno=20 Union Select job from emp Where deptno=30) Minus (select job from emp Where deptno=10);

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

SUB QUERIES(or)NESTED QUERIES: when we are using more than one select statement to perform particular operation then we will be calling it as a subquery.In subquery the inner statement will be executed first and only noce as compared to the outer statement. Syntax: select ----------From Where(select ------);

Example 1: To display all the employees information whose salary is greater than Smiths salary. SQL>select * from emp Where sal>(select sal from emp Where ename=SMITH);DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Example 2: To display all the employees information who is receiving the highest salary. SQL>select * from employee Where sal=(select max(sal) from emp); Example 3: To display all the employees information whose job is same like Smith at the same time salary greater than Allen. SQL>select * from emp Where job=(select job from emp where ename=SMITH) And sal>(select sal from emp Where ename=ALLEN); Example 4:To display all the employees information who is receiving salary greater than average salary of all the employees. SQL>select * from emp Where sal>(select avg(sal) from emp); Example 5:To display the manager no.alng with the no.of employees working under him should be maximum no.of employees compared with the other members. SQL>select mgr,count(*) from emp Group by mgr Having count(*)=(select max(count(*) from Emp group by mgr); Example 6: To display the employee information under which maximum no.of employees working. SQL>select * from emp Where empno=(select mgr from emp Group by mgr) Having count(*)=(select max(count(*) fom emp group by mgr);DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Example 7: To disaply all the employees information who is receiving the second highest salary. SQL>select * from emp Where sal=(select max(sal) from emp where Saselect * from emp Where sal>all(select sal from emp Where deptno=20);

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Views: Views can be defined as a virtual table because it doesnt exist by itself,unless you are having one or more ordinary table on which it will be based or dependent.The table on which view is based is called as base table of the view.It is possible to insert,update and delete the data in the view in the same way as in the table. Advantages of views: Providing the security for the table. By giving limited access to your table to other users. Complicated queries can be generated by using views a normal simple table creation.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Creation of view: Syntax:( SQL , PL/SQLPROGRAMMING

)

create view As select ------ from ;

Example 1: To create a view for emp table with empno,name,salary. SQL>craerte view empview As select empno,ename,sal from emp; Example 2: To create a view for emp table for dept 10. SQL>create view d10view As select * from emp Where deptno=10; Insert into view: Example 1: Insert a new record into view empview. SQL>insert into empview Values(101,WILLIAM,2000); Viewing the contents of d10view: Example: To display the contents of d10view. SQL>select * from d10view;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Replace: Replace option is used whenever you want to over write the existing select statement with new select statement. Example: To create empview with empno,name,salary and deptno. SQL>replace view empview As select empno,ename,sal,deptno from emp; With check option: When ever you want to restrict the user to insert thr records which are satisfying the where condition of the view then we use with check option. Syntax: create view As select-----from Where With check option; Example : create a view for employee details of deptno. 20DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

SQL>create view d20view As select * from emp Where deptno=20 With check option; If you try to enter deptno other than 20,it will not be accepted into the view. Sequences: Whenever you want to create a object which is going to generate the numbers in a particular order (i.e. interval) then we will be calling a sequence. Syntax: create sequence Start with Increment by Maxvalue Minvalue Cache Cycle; Whenever you want to generate the next number of the sequence then we will be using nextval and when you want to see the current position of the sequence we use currval. Example: SQL>create sequence eno Start with 5 Increment by 1 Minvalue 5 Maxvalue 15 Cache 5 Cycle; This is going to create a sequence with name eno starting with 5,incrementing by 1,minimum value is 5,maximum value is 15,cache is 5 and with cycle. Altering the sequence: whenever you want to change any options relatedt To existing sequence then we will be using Alter. Note:start with cannot be changed using Alter.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Syntax: alter sequence ; Example: SQL>alter sequence eno Increment by 2 Minvalue 10 Maxvalue 100;( SQL , PL/SQLPROGRAMMING

)

Drop sequence: Whenever you want to drop a sequence we use drop statement. Syntax: drop sequence Example: SQL>drop sequence eno; INDEX: Whenever you to retrieve the records faster corresponding to one condition then we will be using Indexing concept. Before going to index,identify the fields which will be using mostly in the where clause then indx on those fields.Apply index when there are more than 500 records are present in a table. There are 3 types of indexes Simple index, Unique index and Concatenated index. Syntax: SQL>create index on ();1. Simple index: Is used when indexing is based on the column of the

table. Example 1: SQL>create index idept on emp(deptno); Example 2: SQL>create index iename on emp(ename):2. Unique index: Is used when indexing is based on implementing

unique constraint along with indexing. Example : SQL>create unique index iph on emp(phno); 3. concatenated index: Is used when indexing is based on more than one column as a combination. Example: SQL>create index ds on emp(deptno,sal);DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Delete index: drop statement is used Example: SQL>drop index idept;( SQL , PL/SQLPROGRAMMING

)

What Is The Difference Between SQL and PL/SQL?There are so many variants of SQL that it is hard sometimes to figure out what to use. Here is a short article that briefly explains the difference between SQL and PL/SQL. LET SEE! What is SQL? SQL (pronounced sequal) stands for Structured Query Language. Withe SQL, you can view data - called Data Definiton Language or DDL and manipulate data - called Data Manipulation Languate or DML. All of the above are just a fancy way to say that with SQL, the user can both view and alter records in the database. To help , here are a couple of queries: DDL or View SELECT * FROM employees View all of the records in the employee table DML or Manipulate UPDATE employees SET employeefirstname = John WHERE employeeid = 101 Find the record for employee ID 101 and change the first name to John What is PL/SQL? The official answer is from the PL/SQL User Guide: PL/SQL, Oracles procedural extension of SQL, is an advanced fourth-generation programming language (4GL). It offers software-engineering features such as data encapsulation, overloading, collection types, exceptions, and information hiding. PL/SQL also supports rapid prototyping and development through tight integration with SQL and the Oracle database. Huh? That is what I thought at the beginning. But at a high level, all this means is that it can do all of the things that regular SQL can do, but also, it is procedural and can be used like a

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQL PROGRAMMING ) programming language (C++, Java, etc.) For instance, you can use loops and If . . . Then statements in your PL/SQL statements (Programs). Here is a definition of PL/SQL from Lewis Cunningham (an Oracle database expert): If I wanted to create my own, very short, definition of PL/SQL it would be this: PL/SQL is the Oracle native programming language that provides database-centric application development. It can natively call static SQL and provides multiple methods of calling dynamic SQL.

DIFFER:SQL is a data oriented language for selecting and manipulating sets of data. PL/SQL is a procedural language to create applications. You dont normally have a SQL application. You normally have an application that uses SQL and a relational database on the back-end. PL/SQL can be the application language just like Java or PHP can. SQL may be the source of data for your screens, web pages and reports. PL/SQL might be the language you use to build, format and display those screens, web pages and reports.

What Is Dynamic SQL?Most PL/SQL programs do a specific, predictable job. For example, a stored procedure might accept an employee number and salary increase, then update the sal column in the emp table. In this case, the full text of the UPDATE statement is known at compile time. Such statements do not change from execution to execution. So, they are called static SQL statements. However, some programs must build and process a variety of SQL statements at run time. For example, a general-purpose report writer must build different SELECT statements for the various reports it generates. In this case, the full text of the statement is unknown until run time. Such statements can, and probably will, change from execution to execution. So, they are called dynamic SQL statements. Dynamic SQL statements are stored in character strings built by your program at run time. Such strings must contain the text of a valid SQL statement or PL/SQL block. They can also contain placeholders for bind arguments. A placeholder is an undeclared identifier, so its name, to which you must prefix a colon, does not matter. For example, PL/SQL makes no distinction between the following strings:'DELETE FROM emp WHERE sal > :my_sal AND comm < :my_comm' 'DELETE FROM emp WHERE sal > :s AND comm < :c'

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQL PROGRAMMING ) To process most dynamic SQL statements, you use the EXECUTE IMMEDIATE statement. However, to process a multi-row query (SELECT statement), you must use the OPEN-FOR, FETCH, and CLOSE statements. (OR)

Dynamic SQL is an extended form of embedded SQL that allows more generalpurpose application. Dynamic SQL is used when part or all of the SQL statement is unknown at compile-time EXECUTE IMMEDIATE PREPARE and EXECUTE Placeholders can be used to pass values to EXECUTE/FETCH statements

The Need for Dynamic SQLYou need dynamic SQL in the following situations:

You want to execute a SQL data definition statement (such as CREATE), a data control statement (such as GRANT), or a session control statement (such as ALTER SESSION). In PL/SQL, such statements cannot be executed statically. You want more flexibility. For example, you might want to defer your choice of schema objects until run time. Or, you might want your program to build different search conditions for the WHERE clause of a SELECT statement. A more complex program might choose from various SQL operations, clauses, etc. You use package DBMS_SQL to execute SQL statements dynamically, but you want better performance, something easier to use, or functionality that DBMS_SQL lacks such as support for objects and collections. (OR) OR

Dynamic SQL:

Static SQL

Allowing access to the database using theM.C.A II/I--D B M S( L A B) R E CO R D

DBMS=LAB-V{NOV/DEC-2009}

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) normal interactive SQL statements, with minor modifications in some cases. The pattern of database access is fixed and can be hard-coded into the program.( SQL , PL/SQLPROGRAMMING

)

Dynamic SQL There are many situations where the pattern of database access is not fixed and is known only at runtime

The basic difference between the two types of embedded SQL is Static SQL does not allow host variables to be used in place of table names or column names For example, in static SQL we can not write: EXEC SQL BEGIN DECLARE SECTION char TableName[20]; EXEC SQL END DECLARE SECTION; EXEC SQL INSERT INTO :TableName VALUES (S1, Simth, 24) EXEC SQL DECLARE cursor1 CURSOR FOR SELECT * FROM :TableName Problems * indicates that all columns from the table, TableName, but the number of columns will vary with the choice of table. Data types of the columns will vary between tables But if we do not know the number and data type, we can not use FETCH statement Dynamic SQL can overcome these problems and allow more general-purpose software to be developed.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

The EXECUTE IMMEDIATE Statement:

For example,

Static SQL: EXEC SQL BEGIN DECLARE SECTION float increment; EXEC SQL END DECLARE SECTION EXEC SQL UPDATE staff SET salary=salary+:increment WHERE staffNo=SL21 Dynamic SQL: EXEC SQL BEGIN DECLARE SECTION; char buffer[100]; EXEC SQL END DECLARE SECTION; sprintf (buffer, UPDATE staff SET salary = salary + %f WHERE staffNo=SL21 , increment); EXEC SQL EXECUTE IMMEDIATE :buffer;Examples of Dynamic SQL for Records, Objects, and CollectionsAs the following example shows, you can fetch rows from the result set of a dynamic multi-row query into a record:DECLARE TYPE EmpCurTyp IS REF CURSOR; emp_cv EmpCurTyp; emp_rec emp%ROWTYPE; sql_stmt VARCHAR2(200); my_job VARCHAR2(15) := 'CLERK'; BEGIN sql_stmt := 'SELECT * FROM emp WHERE job = :j'; OPEN emp_cv FOR sql_stmt USING my_job; LOOP FETCH emp_cv INTO emp_rec; EXIT WHEN emp_cv%NOTFOUND; -- process record END LOOP; CLOSE emp_cv; END;

The next example illustrates the use of objects and collections. Suppose you define object type Person and VARRAY type Hobbies, as follows:CREATE TYPE Person AS OBJECT (name VARCHAR2(25), age NUMBER);DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

CREATE TYPE Hobbies IS VARRAY(10) OF VARCHAR2(25);

Embedded SQLEmbedded SQL statements ISO standard specifies embedded support for Ada, C, COBOL, Fortran, Pascal, PL/1.

Types of embedded SQL:

Static embedded SQL, where the entire SQL statement is known when the program is written Dynamic embedded SQL, which allows all or part of the SQL statement to be specified at runtime Dynamic SQL provides increased flexibility and helps produce more general-purpose software

Simple Embedded SQL Statements

Simplest types of embedded SQL statements are those that do not produce any query results Non-select statement, INSERT, UPDATE, DELETE, CREATE TABLE.

Some comments for the example

Embedded SQL statements start with keyword EXEC SQL Embedded SQL statements end with a terminator thats dependent on host language C, PL/1, Ada ----; COBOL ---- END-EXECDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL An embedded SQL statement can appear anywhere that an executable host language statement can appear The embedded statements are same as ISQLPROGRAMMING

)

Processing Programs with Embedded SQL:-

Embedded SQL Application Running:-

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Retrieving data Using Embedded SQLEmbedded SQL divides queries into two groups: Single-row queries, where the query result contains at most one row of data Multi-row queries, where the query result may contain an arbitrary number of rows, which may be zero, one, more.

PL/SQL ( Procedural Language using sql)DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

PL/SQL can be called the extension of SQL where it is going to support the SQL statement along with the processing statement we will be calling it as Procedural Language. (OR) PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL has many programming language features. Program units written in PL/SQL can be stored in compiled form. PL/SQL code is portable across all operating systems that support Oracle. PL/SQL does not support DDL and DCL. PL/SQL Block A PL/SQL block contains logically related SQL and PL/SQL statements. Three sections in a typical PL/SQL block: declaration (optional): declare identifiers (variables and constants). execution (required): execute SQL and PL/SQL statements. exception (optional): perform error handling. Execute PL/SQL Program Save the program in a file: sample1.sql Execute the program in SQL*Plus SQL> start sample1 Enable output to the screen: SQL> set serveroutput on or place set serveroutput on at the beginning of the PL/SQL program.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) (OR)In Oracle Tools: When it contains the PL/SQL engine, an application development tool can process PL/SQL blocks and subprograms. The tool passes the blocks to its local PL/SQL engine. The engine executes all procedural statements at the application site and sends only SQL statements to Oracle. Thus, most of the work is done at the application site, not at the server site. Furthermore, if the block contains no SQL statements, the engine executes the entire block at the application site. This is useful if your application can benefit from conditional and iterative control. Frequently, Oracle Forms applications use SQL statements merely to test the value of field entries or to do simple computations. By using PL/SQL instead, you can avoid calls to the Oracle server. Moreover, you can use PL/SQL functions to manipulate field entries. ( SQL , PL/SQLPROGRAMMING

)

Advantages of PL/SQLPL/SQL is a completely portable, high-performance transaction processing language that offers the following advantages:

Support for SQL Support for object-oriented programming Better performance Higher productivity Full portability Tight integration with Oracle Tight security

Understanding the Main Features of PL/SQLA good way to get acquainted with PL/SQL is to look at a sample program. The program below processes an order for a tennis racket. First, it declares a variable of type NUMBER to store the quantity of tennis rackets on hand. Then, it retrieves the quantity on hand from a database table named inventory. If the quantity is greater than zero, the program updates the table and inserts a purchase record into another table named purchase_record. Otherwise, the program inserts an out-of-stock record into the purchase_record table

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQL PROGRAMMING ) With PL/SQL, you can use SQL statements to manipulate Oracle data and flow-of-control statements to process the data. You can also declare constants and variables, define procedures and functions, and trap runtime errors. Thus, PL/SQL combines the data manipulating power of SQL with the data processing power of procedural languages. Block Structure PL/SQL is a block-structured language. That is, the basic units (procedures, functions, and anonymous blocks) that make up a PL/SQL program are logical blocks, which can contain any number of nested sub-blocks. Typically, each logical block corresponds to a problem or subproblem to be solved. Thus, PL/SQL supports the divide-and-conquer approach to problem solving called stepwise refinement. A block (or sub-block) lets you group logically related declarations and statements. That way, you can place declarations close to where they are used. The declarations are local to the block and cease to exist when the block completes. The following FIGURE shows, a PL/SQL block has three parts: a declarative part, an executable part, and an exception-handling part. (In PL/SQL, a warning or error condition is called an exception.) Only the executable part is required.

The order of the parts is logical. First comes the declarative part, in which items can be declared. Once declared, items can be manipulated in the executable part. Exceptions raised during execution can be dealt with in the exception-handling part. Variables and Constants PL/SQL lets you declare constants and variables, then use them in SQL and procedural statements anywhere an expression can be used. However, forward references are not allowed. So, you must declare a constant or variable before referencing it in other statements, including other declarative statements.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)Declaring Variables Variables can have any SQL datatype, such as CHAR, DATE, or NUMBER, or any PL/SQL datatype, such as BOOLEAN or BINARY_INTEGER. For example, assume that you want to declare a variable named part_no to hold 4-digit numbers and a variable named in_stock to hold the Boolean value TRUE or FALSE. You declare these variables as follows:part_no NUMBER(4); in_stock BOOLEAN;

( SQL , PL/SQL

PROGRAMMING

)

You can also declare nested tables, variable-size arrays (varrays for short), and records using the TABLE, VARRAY, and RECORD composite datatypes. Assigning Values to a Variable You can assign values to a variable in three ways. The first way uses the assignment operator (:=), a colon followed by an equal sign. You place the variable to the left of the operator and an expression (which can include function calls) to the right. A few examples follow:tax := price * tax_rate; valid_id := FALSE; bonus := current_salary * 0.10; wages := gross_pay(emp_id, st_hrs, ot_hrs) - deductions;

The second way to assign values to a variable is by selecting (or fetching) database values into it. In the example below, you have Oracle compute a 10% bonus when you select the salary of an employee. Now, you can use the variable bonus in another computation or insert its value into a database table.SELECT sal * 0.10 INTO bonus FROM emp WHERE empno = emp_id;

The third way to assign values to a variable is by passing it as an OUT or IN OUT parameter to a subprogram. As the following example shows, an IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller:DECLARE my_sal REAL(7,2); PROCEDURE adjust_salary (emp_id INT, salary IN OUT REAL) IS ... BEGIN SELECT AVG(sal) INTO my_sal FROM emp; adjust_salary(7788, my_sal); -- assigns a new value to my_sal

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)Declaring Constants Declaring a constant is like declaring a variable except that you must add the keyword CONSTANT and immediately assign a value to the constant. Thereafter, no more assignments to the constant are allowed. In the following example, you declare a constant named credit_limit:credit_limit CONSTANT REAL := 5000.00;

( SQL , PL/SQL

PROGRAMMING

)

The above mention parts are now defining: PL/SQL is divided into 3 parts 1.Declaration part: Declaring the variables. 2.Execution part: corresponding to the task all the statements are be written here. 3.Exception part: Errors are to be handled properly.

to

DBMS output.put line(string): Is a function used to print message on the screen.before using this function set serveroutput on. SQL>set serveroutput on; %type: Is used in declaring whenever we want to assign the same datatype and size of one variable to another variable. Example: sall emp.sal%type;/*sall is of same type&size as that of sal field in emp table*/ Syntax: Declare : /*Declaring block*/ Begin : /*Execution block*/ Exception : /*Exception block*/ End;

Example: Write a PL/SQL block which finds area of a circle. SQL>ed area DeclareDBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL R number(2):=10; Pi constant number(4,3):=3.14; A number(7,2); Begin A:=Pi*R*R; DBMS_output.put_line(area is=||to_char(a)); End; / SQL>@area; /* To execute the PL/SQL block*/PL/SQL Boosts Performance:PROGRAMMING

)

PL/SQL DatatypesEvery constant, variable, and parameter has a datatype (or type), which specifies a storage format, constraints, and valid range of values. PL/SQL provides a variety of predefined datatypes. For instance, you can choose from integer, floating point, character, Boolean, date, collection, reference, and LOB types. In addition, PL/SQL lets you define your own subtypes.DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Predefined Datatypes( SQL , PL/SQLPROGRAMMING

)

A scalar type has no internal components. A composite type has internal components that can be manipulated individually. A reference type holds values, called pointers, that designate other program items. A LOB type holds values, called lob locators, that specify the location of large objects (graphic images for example) stored out-of-line.

Number Types

Number types let you store numeric data (integers, real numbers, and floating-point numbers), represent quantities, and do calculations. BINARY_INTEGER You use the BINARY_INTEGER datatype to store signed integers. Its magnitude range is -2**31 .. 2**31. Like PLS_INTEGER values, BINARY_INTEGER values require less storage than NUMBER values. However, most BINARY_INTEGER operations are slower than PLS_INTEGER operations.BINARY_INTEGER Subtypes

A base type is the datatype from which a subtype is derived. A subtype associates a base type with a constraint and so defines a subset of values. For your convenience, PL/SQL predefines the following BINARY_INTEGER subtypes:NATURAL NATURALN POSITIVE POSITIVEN SIGNTYPE

NUMBER The syntax follows:

NUMBER[(precision,scale)]

To declare fixed-point numbers, for which you must specify scale, use the following form:NUMBER(precision,scale) NUMBER Subtypes

You can use the following NUMBER subtypes for compatibility with ANSI/ISO and IBM types or when you want a more descriptive name:DEC DECIMAL DOUBLE PRECISION FLOAT INTEGER INT NUMERIC REAL SMALLINT

PLS_INTEGER You use the PLS_INTEGER datatype to store signed integers. Its magnitude range is -2**31 .. 2**31. PLS_INTEGER values require less storage than NUMBER values.

Character Types

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQL PROGRAMMING ) Character types let you store alphanumeric data, represent words and text, and manipulate character strings. CHAR You use the CHAR datatype to store fixed-length character data. The syntax follows:CHAR[(maximum_size [CHAR | BYTE] )] CHAR Subtype The CHAR subtype CHARACTER

has the same range of values as its base type. LONG and LONG RAW You use the LONG datatype to store variable-length character strings. The LONG datatype is like the VARCHAR2 datatype, except that the maximum size of a LONG value is 32760 bytes. You use the LONG RAW datatype to store binary data or byte strings. LONG RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL. The maximum size of a LONG RAW value is 32760 bytes. RAW You use the RAW datatype to store binary data or byte strings. another. The RAW datatype takes a required parameter that lets you specify a maximum size up to 32767 bytes. The syntax follows:RAW(maximum_size)

ROWID and UROWID Internally, every database table has a ROWID pseudocolumn, which stores binary values called rowids. Each rowid represents the storage address of a row. A physical rowid identifies a row in an ordinary table. A logical rowid identifies a row in an index-organized table.Physical Rowids SQL> SELECT rowid, ename FROM emp WHERE empno = 7788;

might return the following row:ROWID ENAME ------------------ ---------AAAAqcAABAAADFNAAH SCOTT Logical Rowids

Logical rowids provide the fastest access to particular rows.. VARCHAR2 The syntax follows:VARCHAR2(maximum_size [CHAR | BYTE]) VARCHAR2 Subtypes The VARCHAR2 subtypes below have the same VARCHAR is just another name for VARCHAR2. STRING VARCHAR DSINTERVAL_UNCONSTRAINED .

range of values as their base type. For example,

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)PL/SQL ArchitectureThe PL/SQL compilation and run-time system is an engine that compiles and executes PL/SQL blocks and subprograms. The engine can be installed in an Oracle server or in an application development tool such as Oracle Forms. In either environment, the PL/SQL engine accepts as input any valid PL/SQL block or subprogram. Figure shows the PL/SQL engine processing an anonymous block. The PL/SQL engine executes procedural statements but sends SQL statements to the SQL engine in the Oracle database.

( SQL , PL/SQL

PROGRAMMING

)

PL/SQL Engine

THE PL/SQL ENGINE(Processing)

//****> THE PL/SQL ENGINE(Processing)==//

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING ) TRIGGER: Triggers are procedures that are sotored in the database not in the complied form and implicitly fired when an event occurs.Traditionally,triggers guarantee that when a specific operation is performed related actions are performd.Triggers support the execution of a Pl/SQL block when an INSERTed t1 Create or replace trigger eins Before insert on emp for each row Begin If:new.sal>5000 then Raise_application_erroe(-20001,salary above 5000); End if; End; / SQL>@t1

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

Example 2: Create a database Trigger on dept table which prevents the user from updating the deptno or deleting a row from the dept table if dependent rows are existing in the emp table( i.e. if there are any employees belonging to that department). SQL>ed t2 Create or replace trigger updel Before update or delete on dept for each row Begin Declare No number(4); If updating or deleting then Select count(*) no from emp Where deptno=:new.deptno; If (no>1) then Raise_application_erroe(-20001,Records existing in emp table); End if; End if; End; /

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) SQL>@ t2 (OR )( SQL , PL/SQLPROGRAMMING

)

Triggers:Trigger: procedure that starts automatically if specified changes occur to the DBMS. Three parts: Event (activates the trigger) Condition (tests whether the triggers should run) Action (what happens if the trigger runs) Triggers: Example CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS REFERENCING NEW TABLE NewSailors FOR EACH STATEMENT INSERT INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age ed prime.sql Declare N number:=&n; I number:=2; R number(3):=0;DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS) Begin While(i@ prime; OUTPUT:( SQL , PL/SQLPROGRAMMING

)

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

PROGRAM --- (1)AbdulQader(SQL)> create table sb_account(acc_no number(20),cust_name varchar2(17),bal_amount number(6,2));Table created.

For inserting the values:SQL> insert into sb_account values(&acc_no,'&cust_name',&bal_amount); Enter value for acc_no: 111 Enter value for cust_name: SHAIK ABDUL QADER Enter value for bal_amount: 17000 old 1: insert into bank values(&acc_no,'&cust_name',&bal_amount) new 1: insert into sb_account values(123456,'SHAIK ABDUL QADER',15000) 1 row created.

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)SIMILARLY,create some 5 to10 rows. ( SQL , PL/SQLPROGRAMMING

)

PL/SQL CODE:CODE declare 2 ano number(10); 3 cn varchar2(35); 4 ba number(10); 5 re number(10) :=1000; 6 dep number(10); 7 wit number(10); 8 msg varchar2(50); 9 d3 varchar2(50); 10 begin 11 ano :=&accountno; 12 select acc_no,cust_name,bal_amount into ano,cn,ba from sb_account where acc_no=ano; 13 dep :=&enter_for_deposit; 14 update sb_account set bal_amount=dep where acc_no=ano;DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

15 if re < dep 16 then 17 wit :=&withdraw; 18 dep := dep-wit; 19 if dep < 1000 20 then 21 d3 :='your account doesnot have suffisient bal'; 22 else 23 update sb_account set bal_amount=dep where acc_no=ano; 24 d3 :='your transaction has sucessfully completed'; 25 end if; 26 else 27 msg :='YOU CANNOT WITHDRAWN DUE TO INSUFFICIENT BALANCE'; 28 end if; 29 dbms_output.put_line(d3); 30* end;

Output;

DBMS=LAB-V{NOV/DEC-2009}

M.C.A II/I--D B M S( L A B) R E CO R D

Page 2

HYDERABAD

NAME=

Shaik Abdul Qader

ROLL NO=060-09-023

Contact me=9700064061Nizam Institute of Computer Sciences(NICS)( SQL , PL/SQLPROGRAMMING

)

PROGRAM --- (2)

AbdulQader(SQL)>CREATE TABLE COLLEGE_INFO(COLLEGE_CODE