SQL Note2003
SQL Note2003
Example: Employee name, Salary of employees are individually known as one object. INFORMATION Organized collection of related data of n object is known as information through which an object can clearly identified. DATAFILE Organized collection of related information of a particular group is known as a data file Example: - Sales Department. , Purchase Department, Admin Department of particular company maintains their data file. DATABASE Database is nothing but the organized collection of related database or information. *Note:- Though data is raw fact through which an object cannot be identified but is minimum requirement to build a database. WHY DATBASE Database is required to keep track on object on day-to-day transaction. Database has no scope. It can be implemented on small-scale industry to large-scale corporate house. MEDIA TO MAINTAIN DATABASE Database can be maintained using 3 different medias. 1. 2. 3. DBMS DBMS or Database Management System is a software which is helpful to store , retrieve and modify the data of a database on users request. Till date computer world has seen 4 types of database to store the data. 1. 2. 3. 4. Network Database Hierarchical Database Relational Database Object Relational Database Paper or cabinet file Spread sheet DBMS
The job of above type of database are same to store the data or to hold the data But they are categorized in 4 different types depending on the way they stored the data inside the database is different.
If database is categorized in 4 different types likewise DBMS is also categorized in 4 different types depending on its supports. If DBMS supports to store retrieve and modify the data of network database then it will be termed as NDBMS Likewise if DBMS supports hierarchal, relational or object relational database to manipulate them, then they will be termed as HDBMS, RDBMS, ORDBMS, respectively . RDBMS Data Information Datafile Database : : : : Attribute Tupple or Row Table Databank/Data warehouse
It is basically a concept which is developed by a scientist by John E.F.Cord in 1970 June . In his concept code prescribes 12 different rules known as 12 cord Rule. If any database software fulfills 6 or more than 6 rules of cord rules of Cord that will be termed as RDBMS types Software and if any database software fulfills less than 6 rules then they will termed as DBMS. Greater Than 6(RDBMS) Oracale 6,7 Access SQL Server DB2 Informix Ingiris A relational Model of Data For Large Shared Databank It is book when 12 cord rules are described and it is a foreign edition. RDBMS RDBMS is nothing but the collection of 2 dimensional table or relation. Lessthan 6(DBMS) Foxpro Dbase Foxbase Paradox
Department Dept No. Dname Loc Employee 10 Sales CTC 20 Purchase BBSR 30 Admin RKL
1 X 5000 10
2 Y 6000 10
3 Z 7000 20
The above graphics shows the relational model of architecture where both the tables are related using a common attribute called Dept No. In relational model of architecture always the data is represented in different modules where each modules is known as table and each table has a relationship with another one Data Modularity has 2 advantages. 1. 2. ORDBMS It is the extended version of RDBMS. The extra feature is the object feature. Any thing stored in Object relational Database will be treated as one object. **Note : The advantages of Object Relational Database over a relational database is memory management is proper and coding is less. Feature of RDBMS Class, Object, Abstraction, Encapsulation, Polymorphism. Inheritance Class Class is nothing but a template style of a blueprint which does not have its physically existence. It is nothing but the collection of properties & behaviors of similar types of object. Object It is nothing but instance of a class which has its physical existence having some properties and behaviors. Abstraction This is a concept through which one object essential features will be represented hiding the background details. It leads to data hiding which leads data security. Encapsulation This is a concept through which the data member and the member function will be rapped up, under one module where each module is known as a class. Polymorphism This is a concept through which one object can act differently in different different circumstances. Inheritance Data Redundancy will be less Data Security will be high
This is a concept through which one object property and behavior can be reused in another object . Advantages of ORDBMS over RDBMS 1. 2. 3. 4. Support for User Defined Datatype. Supports for Multimedia. High Quality Server Feature Fully Relational As because object relational database supports object features. It supports user defined data type that means user can declare its own data type and used it inside the programme. Object relational database supports multimedia files such as Jpg file,Gif, Bmp, Avi, etc. That means object relational database not only stress conventional types of data rather than it stores multimedia data type. Object relational database is popular for its high quality server features. It supports 3 level security 1. Client Level 2. Network Level 3. Server Level Apart from that object related database supports 512 petabytes data. As because object related database is based on relational database. It supports maximum rules. So it is known as fully relational. Eg:- Oracle 8, Oracle 8i, Oracle 9i
Oracle 9i
Oracle provides two different languages to manipulate its database. (1) (2) SQL (Structure Query Language) PL SQL (Procedural Language Extension of SQL)
Though oracle provides two different languages to manipulate its database but none of these languages belongs to oracle because. (1) SQL is an ANSI standard language which is required to manipulate the database interactivity. Interactivity means one command can be extended at one point of time. As because SQL is an ANSI Standard Language it is not only meant to manipulate Oracle Database rather than it is meant to manipulate any type of database currently available.
(2) Where as through PL SQL is pronounced as a language rather than it is a mechanism or technology implemented on ORACLE Server to manipulate the database programme i.e using SQL commands.
SQL
It is not a single language of its own rather than it is a combination of 5 different Sub languages . Namely 1. 2. 3. 4. 5. DQL This is a sub language which is helpful to retrieve the data from table and show to the user. Otherwise it is known as Data Retrieval Language. It provides a statement Called Select. DDL It is otherwise known as (OML) Object Manipulate Language , which is required to create and manipulate the object in the Oracle Database. Oracle provides 5 different types of Object for customized DBMS. Table, View, Synonyms, Sequence, Index. To create and manipulate above object . DDL Provides five different statements , Create, Alter, Drop, Truncate , Rename,. DML DML otherwise is known as Record Manipulate Language (RML), Which is required to manipulate the record of tables. To accomplish the job DML provides different statements. Insert, Update, Delete. TCL This sub language is required to control the transaction (Insert, Update , Delete) made by the user. When ever any transaction is made in Oracle table those record will never be permanent unless or until a save command is issued or discard command is issued . To accomplish the job TCL provides 3 different statements. 1. 2. 3. DCL Commit Rollback Savepoint DQL (Data Query Language) DDL (Data Definition Language) DML (Data Manipulate Language) TCL (Transaction Control Language) DCL (Data Control Language)
Oracle supports user concept or schema concept to protect the object from invalid users . To create and manipulate those users DCL provides different statements. 1. 2. Grant Revoke
*Note :- Schema :- It is nothing but logical area which holds some physical object protected by a password. Oracle provides a environment which acts as an interface between the user and the database and the interface i.e. known as SQL * PLUS. Whenever a command is issued from SQL * Plus , it goes to database and database will process the data command and send the output back to SQL *Plus.
SQL * PLUS
SQL> OUTPUT
ORCALE 9I
*Note : The difference between an editor and the environment is the editors are the application which are require to edit the text and doesnt have its own command . Where as an environment is an application which is required to manipulate other application as well as has its own command itself. When ever an user log on to Oracle . It shows a logon screen having 3 different options . 1. User name 2. Password 3. Host String Host string is an option which is required when ever an user working on multi Server Architecture. Select It is a power full query statements which is helpful to extract the data from one table or more than one table. Syntax of Select Statement Select b [Distinct] b <* | Col1, Col2, Col3.n> from b <T.Name>
Select Statement can perform 2 jobs . 1. Selection 2. Projection Projection can be posed in two different manner.
1. Column wise Projection / Column Restriction 2. Row wise Projection / Row Restrictions Column Restriction is a concept through which , those column are displayed which are specified in the column list. Eg: - select empno, ename,sal from emp; What Where
Where as row restriction is a concept through which those record are displayed when a condition is satisfied. *Note : - * represents for all column of a table and each individual SQL commands re terminated by ; . Working with Column Alias (Duplicate Name of an Object) Column is a concept though which an user can provide a duplicate name to an existing column. Column Alias can be given in three different manner. Consider the EMP table in Scott Login. 1. 2. 3. SELECT EMPNO NO,ENAME NAME,SAL SALARY FROM EMP SELECT EMPNO AS NO,ENAME AS NAME,SAL AS SALARY FROM EMP SELECT EMPNO NO,ENAME NAME,SAL SALARY FROM EMP. *Note :- When ever an alias is represented in multiple words it has to put in double quotes ( ). COLUMN CONCATENATION 1. 2. 3. SELECT EMPNO || JOB FROM EMP SELECT EMPNO || JOB AS JOBPROFILE FROM EMP SELECET EMPNO || IS WORKING AS || JOB AS JOBPROFILE FROM EMP. *Note:- In oracle string type of values and date type of values are always represented through ( )single quote. ARITHMETIC OPERATION THROUGH SELECT STATEMENT OR WORKING WITH VIRTUAL COLUMN. Select Statements supports arithmetic operators to implement formula concept .The outcome of formula is basically known as a virtual column which does not have its physical existence. Eg. 1) SELECT EMPNO,ENAME,SAL,SAL*1,SAL*.11,SAL*.12 FROM EMP
SQL*PLUS
When ever a valid SQL Statement is issued from SQl prompt, it never goes to database directly rather than it passes through a temporary memory to database and the temporary memory is known as a BUFFER. BUFFER Buffer is nothing but an active temporary memory in client side RAM, which holds a statement for a temporary period unless or until another statement is issued by the user or the memory is explicitly deleted by the user.
SQL>
BUFFER
(NOTEPAD) (AFIEDT.BU F)
SERVER Database
Editor or Ed The above commands are required to open the buffer memory through default editor called NOTEPAD. RUN or /
The above command is used to run buffer memory. SAVE To save a statement in a file permanently Syntax :- SAVE b <Filename> Eg.- SAVE b END An user can store statement for a permanent period in form file those filr a re basically known as SCRIPTFILES . The extension of these type of files are known as .SQL. START To execute the script file. Syntax : - START b <FILENAME> Or @ b <FILENAME> The above command is used to run a script file. START command can perform 2 jobs. 1. 2. GET The above command required to load the statement from the hard disk to the buffer memory. Syntax: Get <filename> Clear Clear the buffer Syntax : Clear Buffer or Cl Buff Show Show the Current Username Syntax : Show User. Host It is a SQL * Plus command required to jump from SQL * Plus to DOS Envirnmnet. SAVE Save a file in different location Syntax : Save d:\aa.sql(Path Location) Difference Between SQL and SQL * Plus SQL 1. It is an Ansii Standard Language required to manipulate the database SQL*PLUS 1.It is an environment proprietary of Oracle Load the statement from the hard disk to buffer RUN the buffer.
2. SQL Commands cannot be abbreviated 3.SQl Command always terminated by a ; 4. SQL Command always passes through the buffer to database for execution.
3.These commands can be abbreviated Eg: Clear screen (Cl scr ) 3. No optional character is used to terminate SQL *PLUS Commands. 4. No buffer memory is used fro SQL * Plus commands
ROW RESTRICTION THROUGH SELECT STATEMENT It is a concept implemented on select statement to restrict the record depending on a condition . To implement condition select statement provides a clause called WHERE. Syntax of SELECT using WHERE Select <EXPR>
From <Table Name> [Where <Condition>]; To restrict records depending on a condition Oracle provides 3 different types of operators. 1. 2. 3. Eg : Arithmetic Operator Relational Or Comparison Operator.(>,<,>=,<=,<>,=,!=) Logical Operator(And, Or, Not) SELECT * FROM EMP SAL>2000 AND SAL<3000 SELECT * FROM EMP JOB = MANAGER AND JOB= SALESMAN **Note : Select statement is neither case sensitive nor syntactical sensitive but the column value compared with column is always case sensitive . Eg : SELECT * FROM EMP WHERE JOB= Salesman The above statement , will display no row selected . ROW AND COLUMN RESTRICTION THROUGH SELECT STATEMENT Eg: SELECT EMPNO, ENAME,SAL,DEPTNO FROM EMP WHERE DEPTNO!=30 The above example has shown the concept of conventional relational operator to restrict the record depending on a condition. Apart from that Oracle provides 4 exclusive relational operators to restrict the record and those are 1. 2. 3. 4. BETWEEN AND IN LIKE IS NULL It is a operator which is required to display the output between a given range of values .This operator is only used in NUMBER and DATE type of values. It is extended version of Greater than and smaller than . *Note : This operator is inclusive of lower bound and Upper Bound values. Eg: SELECT * FROM EMP WHERE SAL BETWEEN 2000 AND 3000; IN (OR) This is otherwise known as INLIST operator. IN operator is advance version of OR. This operator is meant for any type of values. Eg: SELECT * FROM EMP
BETWEEN AND
WHERE JOB IN (SALESMAN,ANALYST,..,) LIKE It is a powerful query operator, which is required to extract the data from the table, depending upon a character position. This operator is meant for character types of values or date types of values. It provides the wild card character to accomplish the job. Wild Card Character % - It represents multiple characters _(Underscore):- It represents a single character. Eg : 2. 3. 4. SELECT * FROM EMP WHERE ENAME LIKE S%; (First Character) SELECT * FROM EMP WHERE ENAME LIKE %S (Last Character) SELECT * FROM EMP WHERE ENAME LIKE S% OR ENAME LIKE %S SELECT * FROM EMP WHERE ENAME LIKE __ i %H (3rd character i and last character H NOT LIKE Eg : 1. 2. IS NULL Null is a special kind of value which is Unassigned or Inapplicable To extract the value from a table depending upon the NULL value . Oracle provides an operator called Is Null. Eg: SELECT * FROM EMP WHERE COMM IS NULL; SELECT * FROM EMP WHERE ENAME NOT LIKE S% AND ENAME LIKE %S DATE LIKE %82 DATE LIKE %FEB
JOIN
It is a mechanism or a technology implemented on select statement to extract the data from multiple tables. To extract the data from multiple tables ,the tables must have a
relationship depending upon the relationship of tables JOIN is categorized in 4 different types. 1. 2. 3. 4. 1. Equi Join Non Equi Join Self Join/Inner Join Outer Join EQUI JOIN It is a type of join , which will extract the data from multiple tables when a common attribute is available. TABLE EMP (CHILD) EMPNO 1 2 3 4 5 TABLE DEPT (MASTER) DEPT NO 10 20 30 40 DNAME SALES PUR ADMIN FIN LOC CTC BBSR RKL BPD NAME X Y Z A B SAL DEPTNO 20 10 20 30 10
The above graphic shows both the tables have a common attribute called DEPTNO . To extract the data from above tables the user can use EQUI-JOIN. Syntax SELECT TBLE1.COL,TABLE1.COL,TABLE2.COL,TABLE 2.COL..N FROM TABLE1,TABLE2 WHERE TABLE1.COL=TABLE2.COL Eg: SELECT EMP.EMPNO,EMP.ENAME,EMP.SAL, DEPT.DNAME,DEPT.LOC FROM EMP ,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO; **Note : A table name preferred with the column name is optional in nature , but is mandatory when ever a common attribute is extracted. Eg. SELECT EMPNO,ENAME,SAL,DANME,LOC,DEPT.DEPTNO,
FROM EMP,DEPT WHERE EMP.DEPT NO=DEPT.DEPTNO OUTER JOIN It is a type of join which will extracted the data from multiple tables weather the condition is satisfied or not satisfied . In other words Outer Join is a type of join which will extract all the data from multiple tables. Eg. : Write a statement which will display empno,name ,sal , deptno, and location of those who is working in a particular department as well as display those department information under which no person are working. SELECT EMPNO,ENAME,SAL,DNAME,LOC, FROM EMP, DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO; NON EQUI JOIN It is type of join which will extract the data from multiple tables when ever no common attribute is available but there must be a relationship. EMPNO 1 2 3 4 5 NAME X Y Z A B SAL 7500 2500 950 3800 850 DEPTNO GARDE 1 2 3 4 5 LSAL 700 1201 2001 5001 8001 HSAL 1200 2000 5000 8000 9999
The above graphics shown both the tables have no common attributes but there is an internal relationship using High salary and Low Salary . High salary of salgrade table to extract the data from above tables the user can use non equi join. Eg. Write a statement to display empno, ename, salary, grade SELECT EMPNO,ENAME,SAL,GRADE,DNAME,LOC FROM EMP ,SALGRADE,DEPT WHERE SAL BETWEEN LOSAL AND HISAL 2. Write a statement which will display empname,salary,grade,deptname,and loc of those employee whose job is salesman SELECT EMPNO,ENAME,SAL,GRADE,DNAME,LOC FROM EMP ,SALGRADE,DEPT WHERE SAL BETWEEN LOSAL AND HISAL AND EMP.DEPTNO = DEPT.DEPTNO
AND JOB= SALESMAN; WORKING WITH TABLE ALIAS It is a concept or mechanism required to provide a duplicate name to an existing table. Table alias is meant to provide short name instead of using object. This concept only implemented for JOIN statement. Eg: SELECT E.EMPNO,E.ENAME,E.SAL,D.DNAME,D.LOC FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO; SELF JOIN OR INNER JOIN Self join is a concept or mechanism where a table is joined with itself to get the output. EMPNO 1 2 3 4 5 From this table Y is the manger of X, Z is manager of Y, Z is manager of A, A is manager of B, Z has no manager (Head) Eg. 1. SELECT W.NAME || IS WORKING|| M.NAME FROM EMP W, EMP M WHERE W.MGR=E.EMPNO; 2. SELECT EMP.EMPNO, EMP.ENAME, EMP.SAL, EMP.DNAME, EMP.LOC FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO; 3. Deficiency (+) or Child table SELECT EMPNO, ENAME,SAL,GRADE,DNAME,SAL FROM EMP,SALGARDE,DEPT WHERE SAL BETWEEN LOSAL AND HISAL AND EMP.DEPTNO(+) = DEPT.DEPTNO; NAME X Y Z A B MGR(EMPNO) 2 3 3 4 DEPTNO -
1. 2.
SINGLE ROW MULTI ROW It is a function which will accept one value as a argument & returns one value per
SINGLE ROW row. MULTI ROW Where as multi row function are those functions which will accepts multiple values as an argument and returned one value per row. FUNCTION
SINGLE ROW
MULTI ROW
CHRACTER
NUMBER
DATE
CONVERSION
CHARACTER MANIPULATION
This function are required to convert a character or a string from one cas to another . The functions are LOWER ( ) UPER ( ) INITCAP ( ) Eg. : 1. 2. SELECT LOWER(ENAME) FROM EMP; Column name Static Value as an argument **Note : The user can pass 2 types of values as an argument in a single row function
**Note : When ever a static value is passed to single row function , the output will be displayed that may no of times , the no of records available inside the table. Eg : SELECT LOWER (ORISSA) FROM EMP;
Here the output will display 14 no of times. Test a single row function oracle provides a predefined tba;e called dual , which is having one column DOMY one value as X Eg: SELECT LOWER(ORISSA) FROM DUAL;
CHARACTER MANIPULATION These functions are required to manipulate the character type of values or string type of values and the functions are 1. 2. 3. 4. 5. 6. CONCAT ( ) SUBSTR ( ) INSTR ( ) LTRIM ( ) RTRIM ( ) LENGTH ( )
CONCAT ( ) This function is required to concatenation 2 strings or 2 columns. Eg. : SELECT CONCAT (ENAME,JOB) FORM EMP SELECT CONCAT (ENAME, CONCAT(WORKING AS,JOB)) FROM EMP; SUBSTR This function is required to extract the specific no of characters from a specified string (String character include no of characters) Syntax: Eg: SELECT (STRING |COLUMN ,STARING POINT OF STRING | [NO OF CHARACTERS] ); SELECT SUBSTR(ORISSA,2,4) FORM DUAL;
INSTR (Inside the string) This function is required to display a character position inside a specific string. If the character is not available it will return 0 and if it is redundant, it will display first character position. Synatx : LENGTH ( ) It will display the length of a string or length of a column values. Eg : SELECT LENGTH (ORISSA) FROM DUAL; INSTR(STRING | COL, SINGLE CHARACTER)
LTRIM ( ) /RTRIM ( ) This features are always require to truncate the blank space from left and right side of the string. Eg: SELECT LENGTH (LTRIM(ORISSA))FROM DUAL;
NUMBER FUNCTION These functions are required to manipulate numeric values. 1. 2. 3. ROUND TRUNCATE MOD
ROUND This is a function required to round a floating values. Eg: SELECT ROUND (45.378) FROM DUAL; 45, IF THE NUMBER AFTER DECIMAL IS <5 THEN NUMBER+1 SELECT ROUND (46.678, 2) FROM DUAL; IF STEP OF DIGIT SPECIFY.THEN AFTER DECIMAL GO TO THE SPTEP OF DIGIT THEN CHECK <5 OR >=5 , IF <5 THEN REMAIN SAME OR VICE VERSA. TRUNCATE This function is required to truncate a floating no of digit. Eg: SELECT TRUNC (45.557) FROM DUAL; HERE AFTER DECIMAL ALL THE NUMBERS ARE CHOPPED. SELECT TRUNC (45.557,2)FROM DUAL; MOD It is a function required to display the reminder of the divisor.
DATE FUNCTION
This function required to manipulate the date type of values or column from the table. 1. 2. 3. 4. 5. 6. ADD_MONTHS ( ) MONTHS_BETWEEN ( ) LAST_DAY ( ) SYSDATE ( ) CURRENT_DATE ROUND ( )
7.
MONTHS_BETWEEN ( ) This function is required to display approx month difference between two specify dates. Eg: SELECT MONTHS_BETWEEN (25-SEP-05,25-AUG-05) FROM DUAL;
LAST_DAY ( ) It is a function to view the last day of months date. Eg: SELECT LAST_DAY(25-AUG-05)FROM DUAL;
NEXT_DAY This is a function is required to display next day of the week date. Eg: SELECT NEXT_DAY(25-AUG-05, FRIDAY) FROM DUAL;
SYSDATE SELECT SYSDATE FROM DUAL; SELECT CURRENT_ DATE FROM DUAL ROUND This function is required to round a date month wise or year wise. If the date is rounded by month , it will check the day part. If the date is rounded by Year , it will check the month part. Eg: SELECT ROUND(TO_DATE(25-AUG-05), MONTH)FROM DUAL; *Note : To_date is conversion function which is required to convert a string date to actual date. >=JULY 1ST DAY OF 1ST MONTH OF NEXT YEAR <JULY 1ST DAY OF 1ST MONTH OF SAME YEAR >=16- 1ST DAY OF NEXT MONTH <16 1ST DAY OF SAME MONTH TRUNCATE This is a function required to truncate a date month wise or year wise.
Eg:
SELECT TRUNC (TO_DATE( 25-AUG-05 ), MONTH)FROM DUAL; SELECT TRUNC (TO_DATE( 25-AUG-05 ), YEAR)FROM DUAL;
CONVERSION FUNCTION It is a type of function which is required to convert a value from one data type to another data type. TO_NUM ( ) NUMBER TO_CHAR( ) TO_CHAR ( ) This function is required to convert date to character or number to character. Syntax : To_Char (Date | Number , FMT); Date to Character Date to character formatting strings are : DY DAY DD DDTH DDTHSP MM MON MONTH YY YYYY Eg: : : : : : : : : : : Abbreviated Character form of the Day of the Week. Full character form of the day of the week Numeric representation of the day of the month between 1 to 31st Numeric representation of the day of the month in the period Character representation of the day of month dth format. Numeric representation of month between 1 to 12 Abbreviated character of the month Full character form of the month Display the Year Part Display the year in centurion format. TO_DATE ( ) CHARACTER DATE TO_CHAR( )
SELECT TO_CHAR (TO_DATE (22-JAN-05),DDTH-MON-YY)FROM DUAL; Number to Character: $ 9. , . L : : : : : Prefix $ as a symbol Represents the no in character format Thousand separator Decimal Notation Prefix as a local currency style.
TO_NUMBER This function is required to convert string number to actual number Eg: SELECT 10 FROM DUAL; SELECT TO_NUMBER(10) FROM DUAL; MULTI-ROW FUNCTION This function is a type of function which will accept multiple values as an argument & return one value per garoup & the functions are 1. 2. 3. 4. 5. Eg: SUM ( ) MAX ( ) MIN ( ) AVG ( ) COUNT ( ) SELECT SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP; The above example will display sum(sal), max(sal), min(sal), and avg(sal) of employee table where employee table is treated as a group. WORKING WITH GROUP BY CLAUSE Group by clause is a clause of select statement used to logically segregate the table data in different different block. This clause is only implemented for group functions (Multi-Row Functions).
The above example is an example of single column wise grouping WORKING WITH MULTICOLUMN WISE GROUPING Eg: SELECT DEPTNO, JOB, SUM(SAL), MAX(SAL), MIN(SAL) FROM EMP GROUP BY DEPTNO, JOB.; The above example will display sum(sal), max(sal) & min(sal).
COUNT ( )
This function is required to count the no of records of a group or no of values of a column. Count function can accept 2 types of argument (i) (ii) Eg: Count (*) Count (Col.name) Select count(*) from emp; Select count(ename) from emp; Question: Ans. Write a statement which will display department , job, sum (sal), min(sal), max(sal) & the no of the persons working under each group. SELECT DEPTNO,JOB,SUM(SAL),MIN(SAL), MAX(SAL),COUNT(*) FROM EMP GROUP BY DEPTNO,JOB ; WORKING WITH HAVING CLAUSE HAVING clause is a clause of select statement which is required to restricted the group depending on a condition. The difference between WHERE & HAVING is where meant for row restriction where as HAVING is meant for group restriction. SYNTAX OF SELECT USING HAVNING CLAUSE SELECT <EXP> FROM <T_NAME> [WHERE <CONDITION>] [GROUP BY <COL._NAME>] [HAVING < GROUP CONDITION>] *Note : Select statement is nether case sensitive nor syntactical sensitive but select statement is clause sensitive always. Eg: SELECT DEPTNO , JOB, MAX(SAL), MIN(SAL), COUNT(*) FROM EMP WHERE DEPTNO <30 GROUP BY DEPTNO,JOB HAVING MAX(SAL)>2000; WORKING WITH ORDER BY CLAUSE
ORDER BY clause is last of select statement which is required to arrange the records in a proper manner either ascending or descending wise . To accomplish the job it provides 2 pseudo columns. Ascending & Descending. The default order is ascending. Eg: SELECT * FROM EMP ORDER BY DEPTNO; SELECT * FROM EMP ORDER BY DEPTNO,SAL DESC; The above example is an example of column wise ordering. SYNTAX OF FULL FLEDGE SELECT STATEMENT SELECT <EXP> FROM <T_NAME> [WHERE <CONDITION>] [GROUP BY <COLUMN_NAME>] [HAVING <GROUP_CONDITION>] [ORDER BY <COL_NAME> [ASC | DESC]];
SUB-QUERY
Sub query is a mechanism or technology implemented on select statement whenever a condition value to an known to an user. The advantage of sub query is to display the output whenever a condition value is to known. Sub query has two different parts. (i) (ii) Inner Query Outer Query Inner query is query which is always executed first to evaluate the condition value & provide the value to the outer query for the processing. Where as outer query is a query which is responsible to accept the value from inner query & display the output. Depending on the value return from inner query to outer query sub query is categorized in 2 different types. 1. 2. Single Row Sub Query Multi Row Sub Query
Single Row Sub Query It is type of sub query where the inner query return one value to alter query for processing. Eg: Display those record whose salary is greater than Blakes Salary. Where as multi row sub query is a sub query where inner query return more than one value to outer query for processing.
Eg:
Where as multi row sub query is a sub query where inner query return more than one value to outer query for processing. Eg; Display those record whose salary is greater than all salary of department 30.
Syntax Of Subquery
SELECT <EXPRESSION> FROM <T_NAME> WHERE <COL_NAME>OPERATOR (SELECT COL.NAME FROM <T_NAME> WHERE <CONDITION>); *Note: The syntax of single row subquery and multi row subquery is same but the user can identify the subquery from its operator . The single row subquery operators are >, < , <=, >=, < >, = Multi row subquery operators are :IN, >ANY, <ANY, = ANY,>ALL, <ALL FOR SINGLE ROW SUBQUERY Eg; 1. 2. Write a statement which will display those records whose salary is greater than blakes salary. SELECT * FROM EMP WHERE SAL >(SELECT SAL FROM EMP WHERE ENAME=BLAKE; SELECT * FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE ENAME=ALEN) AND ENAME <> ALEN; 3. Write a statement which will display those record whose salary is greater than smiths salary & job must be same as ford. SELECT * FROM EMP WHERE SAL >(SELECT SAL FROM EMP WHERE ENAME=SMITH) AND JOB = (SELECET JOB FROM EMP WHERE ENAME=FRD); 4. Write a statement which will display those records whose salary is greater than SMITHs salary & less than BLAKE. SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME =SMITH) AND SAL < (SELECT SAL FROM EMP WHERE ENAME=BLAKE); FOR MULTI ROW SUBQUERY 1. Write a statement which will display those records whose salary is greater than all salary of department 30.
SELECT * FROM EMP WHERE SAL >ALL(SELECT SAL FROM EMP WHERE DEPTNO=30); 2. Write a statement which will display the records whose job is same as any job of Deptno 30. SELECT * FROM EMP WHERE JOB =ANY(SELECT JOB FROM EMP WHERE DEPTNO=30) AND DEPTNO<>30; *Note Any operator is same as IN Operator 3. Write a statement which will display records whose salary is greater than ANY salary of deptno 30. SELECT * FROM EMP WHERE SAL >ANY(SELECT SAL FROM EMP ` WHERE DEPTNO=30) **Note : >any means >(Minimum Value of List) <any means <(maximum value of list) SELECT * FROM EMP WHERE SAL >(SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30) **Note : The user cant write order by clause in the inner query.
WORKING WITH SUBSTITUTION VARIABLES:Substitution Variable is type of variable in SQL which is automatically declared and automatically destroyed by the system itself Advantage of it to make a statement dynamic . Oracle provides 2 types of substitution variable. 1. 2. Statement Type. Session Type. Statement Type substitution variable is a variable which is automatically declared whenever a statement starts execution and automatically destroyed once the statement is executed. This type of variable is identified by &DEPTNO. DEPTNO & : : Variable Substitution Variable
Where as session type substitution variable is a variable once it is declared and assigned by a value , it will return the value unless and until, the user quit from SQL * PLUS or the variable is explicitly destroyed by the user itself , This type of variable is identified by the && . Examples:
1.
SESSION TYPE SUBSTITUTION VARIABLE : 1. SELECT * FROM EMP WHERE DEPTNO=&&DEPNO Once assigned cannot be changed It can be changed by UNDEFINE DNO Reassign the session substitute variable DEFINE DEPNO=20 **Note : Define and undefine are 2 SQL * PLUS command required to reassign and destroy a session type substitution variable. REPORTING THROUGH SELECT STATEMENT:Reporting is nothing but customized representation of data. In SQL reporting can be possible in 2 different manners. 1. Column Wise Formatting 2. Table wise Formatting Examples : Column ename heading name Column sal heading Salary Column comm heading commission
DDL
ALTER Syntax to Alter a Table (Add or Modify) ALTER TABLE <T_NAME> ADD | MODIFY (COL_NAME DATATYPE (SIZE),[COL_NAME DATATYPE (SIZE),..N]); Example 1. ALTER TABLE MYEMP ADD (JOB VRCHAR2(20)); 3. ALTER TABLE MYEMP MODIFY (NAME VARCHAR2(40));
**Note :- To add a new column , to delete an existing column or to change the size of a column the table may or ,may not contain the data, But to change the data type of a column , the column must be blank.
DELETE Syntax : ALTER TABLE <T_NAME> DROP COLUMN <COL _NAME>; The above syntax required to delete a single column from the existing table structure Delete Multiple Column ALTER TABLE <T_NAME> DROP (COL1,COL2,..N) Example 1. ALTER TABLE MYEMP DROP COLUMN JOB; 2. ALTER TABLE MYEMP DROP (NAME ,SAL);
Deleting a table from database physically :Syntax : DROP TABLE <T_NAME>; In Oracle 8i Once Table is deleted from system we can range the table in proper manner by using the following statement. @DEMO BLD Deleting all records physically from a table remains structure using truncate. Syntax Example : Truncate table systab; Renaming a table using Rename : TRUNCATE TABLE <T_NAME>
Syntax
CONSTRAINT
Constraint are nothing but rules or restrictions imposed on individual column to avoid invalid data entry. Oracle provides 5 different types of constraints to avoid invalid data entry. 1. Primary Key 2. Not Null 3. Unique 4. Check 5. Foreign Key Primary Key Not Null Unique Check Foreign Key : : : : :
Enforces No Null and No Duplicate Value to a column Enforces No Null value to column but it can accept duplicate Value. Enforces no duplicate value to a column but can accept Null Value. This always checks a condition before entering value to a column. The constraint which is helpful to make a relationship between two or more tables using common attribute. Foreign key always references to same tables primary key or another tables primary key to make a relationship. Foreign Key is just opposite of primary key i.e. it can accept duplicate values as well as Null Values. Foreign Key supports the concept of Referential integrity.
Imposement Of Constraints
A constraint can be exposed to individual column during design in two different levels 1. Column Level
2.
Table Level :
Column Level
Column Level constraints are those constraints which are imposed on those columns just after the column defining. Table Level : It is those constraints which are imposed on individual column after all column definition during table design. **Note : The difference between column Level and Table Level constraints i.e
In column level maximum one constraint can be imposed to a single column and not null can be used here. In Table Level multiple constraints can be imposed on a single column. Here we cannot use the Not Null. COLUMN LEVEL CONSTRAINT Syntax :
CREATE TABLE <T_NAME> (COLUMN NAME DATATYPE(SIZE) [CONSTRAINT <CONST_NAME>] <C_TYPE>, COLUMN NAME DATATYPE(SIZE) [CONSTRAINT <CONST_NAME>] <C_TYPE>, -------------------------------------------N);
:-
Example Q1.
: Design the following table having the following attribute and constraint. T_NAME Constraints
EMPNO NAME SAL JOB : : : : NUMERIC(4) PRIMARY KEY VARCHAR2(20) NOT NULL NUMERIC(7,2) CHECK (SAL BETWEEN 2000 AND 5000) VARCHAR2(20) UNIQUE
MYEMP
Ans.
CREATE TABLE MYEMP (EMPNO NUMBER(4) CONSTRAINT MYEMP_EMPNO_PK PRIMARY KEY, NAME VARCHAR2(20) CONSTRAINT MYEMP_NAME_NT NOT NULL, SAL NUMBER (7,2) CONSTRAINT MYEMP_SAL_CHK CHECK (SAL BETWEEN 2000 AND 5000), JOB VARCHAR2(20) CONSTRAINT MYEMP_JOB_UK UNIQUE );
N CONSTRAINT <C_NAME> <C_TYPE> (COL_NAME), CONSTRAINT <C_NAME><C_TYPE> (COL_NAME); .N; Example : T_NAME
EMPNO NAME SAL JOB
:
: : : :
MYEMP
NUMERIC(4) PRIMARY KEY VARCHAR2(20) NOT NULL NUMERIC(7,2) CHECK (SAL BETWEEN 2000 AND 5000) VARCHAR2(20) UNIQUE
CONSTRAINTS
Q1.
Design the above table with same attribute using table level.
CREATE TABLE MYEMP (EMPNO NUMBER(4), NAME VARCHAR2(20) CONSTRAINT MYEMP_NAME_NT NOT NULL, SAL NUMBER(7,2), JOB VARCHAR2(20), CONSTRAINT MYEMP_EMPNO_PK PRIMARY KEY(EMPNO), CONSTRAINT MYEMP_SAL_CK CHECK(SAL BETWEEN 2000 AND 5000), CONSTRAINT MYEMP_JOB_UK UNIQUE(JOB))
FOREIGN KEY
Syntax : CREATE TABLE <T_NAME> (COL_NAME DATATYPE(SIZE), COL_NAME DATATYPE(SIZE) ..(N) CONSTRAINT <C_NAME> FOREIGN KEY (COL_NAME) REFERENCES <T_NAME>(COL_NAME)),.;
:
: : : : : : MYDEPT NUMBER (4) VARCHAR2(20) VARCHAR2(20) MYEMP NUMBER(4)
: : : :
: : :
PRIMARY KEY NOT NULL CHECK (SALES,PURCAHSE,ADMIN) NOT NULL CHECK (CTC,BBSR,RKL)
2.
: : : : : :
PRIMARY KEY NOT NULL NOT NULL CHECK (2000 -10,000) FOREIGN REFERENCES MYEMP(EMPNO) FOREIGN REFERENCES MYDEPT(DEPTNO)
TABLE CREATION
1.
CREATE TABLE MYDEPT (DEPTNO NUMBER(4), DNAME VARCHAR2(20) CONSTRAINT MYDEPT_DNAME_NT NOT NULL, LOC VARCHAR2(20) CONSTRAINT MYDEPT_LOC_NT NOT NULL, CONSTRAINT MYDEPT_DEPTNO_PK PRIMARY KEY(DEPTNO), CONSTRAINT MYDEPT_DNAME_CK CHECK(DNAME IN('SALES','PURCHASE','ADMIN')), CONSTRAINT MYDEPT_LOC_CK CHECK(LOC IN('CUTTACK','BHUBANESWAR','ROURKELA')))
2.
CREATE TABLE MYEMP (EMPNO NUMBER(4), NAME VARCHAR2(20) CONSTRAINT MYEMP_NAME_NT NOT NULL, SAL NUMBER(7,2) CONSTRAINT MYEM_SAL_NT NOT NULL, MGR NUMBER(4), DEPTNO NUMBER(4), CONSTRAINT MYEMP_EMPNO_PK PRIMARY KEY(EMPNO), CONSTRAINT MYEMP_SAL_CK CHECK(SAL BETWEEN 2000 AND 10000), CONSTRAINT MYEMP_MGR_FK FOREIGN KEY (MGR) REFERENCES MYEMP(EMPNO), CONSTRAINT MYEMP_DEPTNO_FK FOREIGN KEY(DEPTNO) REFERENCES MYDEPT(DEPTNO))
DATA DICTIONARY / SYSTEM CATALOG 1. 2. To see the name of the existing tables in the current user login SELECT TABLE _NAME FROM USER_TABLES To see the structure of the existing tables DESC USER_TABLES
3. 4.
To see the name of the existing constraints in the current user login SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS To see the name of the constraints with the table name SELECT CONSTRAINT_NAME,TABLE_NAME FROM USER_CONSTRAINTS
5.
To see the name of the constraints with the table name and status SELECT CONSTRAINT_NAME,TABLE_NAME,STATUS FROM USER_CONSTRAINTS
6.
7.
Want to see the range of check constraint SELECT CONSTRAINT_NAME,TABLE_NAME,SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE TABLE_NAME='MYEMP'
DML/RML
Required to manipulate records of a table to accomplish the job DML provides 3 statements 1. 2. 3. 1. INSERT UPDATE DELETE INSERT Syntax : INSERT INTO <T_NAME>[OL1,COL2N] VALUES(VALUE1,VALUE2,N); The above example is a simple insertion where the user remember the column name and their sequences.
Insertion Of Null Value to a Column 1. 2. Explicitly Implicitly Explicitly using NULL key word
Null value can be entered to a column in two different manners. Implicitly using column specification. : : INSERT INTO MYEMP VALUES(1,AAA,NULL); INSERT INTO MYEMP(EMPNO,NAME)VALUES (1,AAA); INTERACTIVE INSERTION :
INSERT INTO MYEMP VALUES(&EMPNO,&NAME,&SAL); UPDATING A RECORD USING UPDATE Syntax : UPDATE <T_NAME> SET COL_NAME =VALUE [,COL_NAME=VALUEN] [WHERE <CONDITION>] Example : UPDATE MYEMP SET SAL =500 WHERE SAL IS NULL; **Note : If where clause is omitted from the update statement , it will update a the values of specific columns. Question : Write a statement which will updated the employee salary of employee no 3 to Blake salary of employee table. Answer : UPDATE MYEMP SET SAL= (SELECT SAL FROM EMP WHERE ENAME = BLAKE WHERE EMPNO=3; :
UPDATING MULTIPLE COLUMN VALUE :Example : UPDATE MYEMP SET NAME= kkk, SAL =5000 WHERE EMPNO=4; DELETE SYNTAX : : DELETE FROM <T_NAME> [WHERE <CONDITION>]; If where clause is omitted from delete statement , it will delete all the records from the table. Example : DELETE FROM MYEMP WHERE EMPNO=4; CREATING A TABLE USING QUERY STATEMENT Example : CREATE TABLE SYSTAB AS SELECT * FROM EMP; **Note : Whenever a table is copied using query statement only not null constraint is copied to the destination table not all constraints. COPY THE STRUCTURE OF TABLE EXCEPT DATA Example : Create table system as select * from emp where 1=2;
TCL
In oracle database whenever a transaction is made , the transaction will never be save permanently unless and until a save command is issued or discard command is issued. To do so TCL provides 3 statements. 1. Commit (Save)
2. 3.
SQL * PLUS
TCL MECHANISM Whenever a DML command is issued from SQL prompt, just before the DML operation is made , automatically a temporary memory is created inside the server whihjc is known as ROLLBACK SEGMENT and the table on which DML operation is going to be made will be copied temporary to the roll back segment which is known as SNAPSHOT. Whenever a commit command I issued in SQl prompt , the roll back segment along with the snap shot will be deleted and records transacted t the main table will ve permanent. If a Roll Back command is issued from SQL prompt, the snapshot available in Roll Back segment will again be copied to its original location with the old data by deleting the Roll back Segment. **Note : The data once committed cannot be Roll Back and once rolled back cannt be committed. Example : INSERT INTO MYEMP VALUES(..); COMMIT; INSERT INTO MYEMP VALUES(..); ROLLBACK; ROWID Example : Required to manipulate duplicate record. :
SELECT ROWID FROM EMP; SAVE POINT Savepoint is nothing but a logical pointer which is given to individual transaction or group of transaction made by an user. Savepoint is only applicable for rollback purpose. Rollback to a particular point does not mean, the above transactions are committed. Rollback to a particular point excluding of that point. Example Empno 1 : Name AAA Sal 7800
INSERT INTO MYEMP VALUES (2,BBB,5000) SAVEPOINT A; INSERT INTO MYEMP VALUES (3,CCC,8000) SAVEPOINT B; INSERT INTO MYEMP VALUES (4,DDD,6000) SAVEPOINT C; ROLLBACK TO B ROLLBACK /*DISCARD C*/ /*DISCRAD A & B*/
IMPLICIT COMMIT & IMPLICIT ROLLBACK The above example shows explicit commit and explicit rollback of data. In sme cases the data is automatically committed or automatically rolled bak by the servers itself which is basically known as AUTO COMMIT & AUTO ROLLBACK. In the following circumstances the data is automatically committed; 1. 2. 1. 2. Whenever an user exit out of SQl * Plus normally after any transaction. Whenever a DDL or DCL command is used after any DML operation. In the following circumstances the data is automatically Rolled Back; Whenever an user exit out of SQL *PLUS abnormally after any transaction. During system Crash.
SET AUTOCOMMIT ON : Valid upto 1. 2. Whenever user exit of SQL * plus Set Autocommit Off : Buffer Stores the SQl Statement Client side
Difference Between Rollback Segment & Buffer Rollback Segment 1. 2. Stores the table called snapshot Server side
OBJECT
VIEW
1. 2. 3. 4. 5.
View is nothing but a logical subset of a data which is based on one table or more than one tables. The advantages of view is to protect the table structure from invalid users. View is otherwise known as virtual table The table based on which the view is created is known as the Base table. Depending on the base table view is categorized into 2 different types. I. II. Simple View Complex View
Simple View is a type of view which is based on a single table or whose base table is one. Complex View is a type of view which is based on multiple table or whose base table is multiple. Syntax : CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW <V_NAME> AS <SELECT STATEMENT>
[WITH CHECK OPTION] [WITH READ ONLY]; **Note : View neither contains the structure nor data of a table rather than it contains only select statement of the base table. But the structure cannot be manipulated by the user. Example : CREATE OR REPLACE VIEW MY VIEW AS SELECT * FROM MYEMP; The above example create a simple view which is based on myemp table. Any record can be inserted, updated, deleted or selected through the view to the base table.
Readonly views are those views thorough which the data can be selected but no DML operation is made through the view to the base table. This type of view is basically meant for reporting purposes. Example : CREATE OR REPLACE MYVIEW AS SELECT * FROM MYEMP WITH READ ONLY;
SYNONYM
Synonyms are nothing but a duplicate name of an existing object. The advantage of a synonyms name is to provide a short object name. Synonyms name is a schema object it doesnt hold the data of an object rather than holds the references of an object. Synonym is basically 2 types 1. 2. Private Synonym Public Synonym Private synonym is a type of synonym once it is given to an object, it can be accessed in a specified user , where as public synonym is a type of synonym once it is given to an object can be accessed in any user.
FOR MYEMP; The above example will create a private synonym which is only access in a particular user where the synonym is created. To see the names of existing synonyms Syntax : SELECT SYNONYM_NAME, TABLE_NAME FROM USER_SYNONYMS; PUBLIC SYNONYM Example : CREATE PUBLIC SYNONYM ME FOR MYEMP **Note : A public synonym can only be created being present in a super user. We can create a synonym of a existing synonym.
INDEX
It is nothing but a schema object which is required to arrange the records in proper manner using references. The advantage of index is to make the query access faster. If no index is created for a particular column, during data search the total table scan occurs. In oracle index is categorized in 2 different types : 1. 2. Unique Index / Implicit Index Non-unique / Explicit Index Unique Index is a type of index which is automatically created by the oracle Server whenever primary key or unique key constraints are exposed on particular columns. Where as Non Unique indexes are those indexes which are explicitly created by an user on those columns, the columns which have hugely duplicate values. Syntax : CREATE INDEX <T_NAME> ON <T_NAME> (COL_NAME); Example : CREATE INDEX MYEMP_COPMIDX
ON MYEMP(DEPTNO,ENAME) Required whenever an user search the data multi condition wise. To see the output SELECT * FROM EMP WHERE DEPTNO=20 AND ENAME= SMITH; UNIQUE INDEX Whenever an unique index will be created automatically by the system , the name of the index will be same as the constraint name given by the user or given by the system. **Note : An index file can be deleted in 2 different manners. 1. 2. Explicitly using drop command Implicitly whenever a table is dropped.
SEQUENCE
It is nothing but a schema object required to generate a linear no . It may be in ascending order or descending . Syntax : CREATE SEQUENCE <S_NAME> [INCREMENT BY <VALUE>] [START WITH <VALUE>] [MAXVALUE N | NO MAXVALUE] [MINVALUE N | NO MINVALUE] [CYCLE | NOCYCLE] [CACHE N | NOCACHE] Note : Sequence is schema object which is only meant for insert purpose Example : CREATE SEQUENCE MYLINE; The above example will create a sequence whose initial value is 1, each incremented by 1 and generate infinite values.
CYCLE CACHE 3 The above example will create a sequence whose initial value will be 1 each time incremented by 1 and generate 5 nos and do the same for thrice.
Descending Sequence
Example : CREATE SEQUENCE MYLINE INCREMENT BY -1 MAXVALUE 10 MINVALUE 1
Modification Of Sequence
Example : CREATE SEQUENCE MYLINE MAXVALUE 5; ALTER SEQUENCE MYLINE MAXVALUE 10; ALTER SEQUENCE MYLINE NOMAXVALUE; **Note : Any clause of a sequence can be alter except start with clause
DCL
Oracle supports user concept and schema concept to protect the object from invalid user. To create and manipulate schema Oracle provides a super user called system identifier by manager.
To Create A User :
Syntax : CREATE USER <U_NAME> IDENTIFIED BY <P_WORD> Example : CREATE USER ORISSA IDENTIFIED BY BBSR;
SYSTEM PRIVILEGE
System privileges are those privileges which are given to individual user , what can be done and what cant be .
OBJECT PRIVILEGE
Object privileges are those privileges are given to object, what can be done and what cant be. System Privileges are 1. 2. 3. 4. 5. 6. 7. Create Session Create Table Create View Create Synonym Create Sequence Create Index Create Procedure
*Note : Among the above privileges Create Session privileges is the primary privilege requires to activate n user by creating session Id.
To impose or revoke the above privileges from an user or from object DCL provides 1. 2. Grant Revoke
PL SQL
Though PL SQL is pronounced as a language, but it is not a language typically rather than it is a mechanism or technology implemented on Oracle Server to manipulate the Database programmatically using SQL Commands . Every Programming Language uses four different Blocks to develop an application and those are : 1. 2. 3. 4. Declare Input Process Output In some programming language the above blocks are physically in nature and they are identified by some keywords. Those types of languages are basically known as Block Structure Language. Eg: COBOL. Where as in some programming language the above blocks are logical in nature and only they follow rule. Those types of languages are Unblock Structure Language. Eg. C, C++, etc. PL SQL is an example of Block Structure Language, where the total program is divided into 3 different Blocks. 1. 2. Declare Begin Optional Mandatory (Program Construct)
Exception 3. End ;
Optional Mandatory
DECLARATION
Declaration block is a block which is responsible for declaration of identifier types, cursors to be used in PL SQL. This block is identified by declare keyword. This Block is optional in nature.
BEGIN/END
This block is responsible for input, process and output in Pl SQL programme. Pl SQl always starts execution from begin and end with end. This is mandatory.
EXCEPTION
This block is meant for error handling in PL SQL. Whenever an error occurs at PL SQL automatically system control will navigate the exception block and thus the execute the program normally, identified by the keyword exception. This is optional in nature. The minimum requirement of a language is an identifier , and identifiers minimum requirement is data types. PL SQL provide 2 types of data type : 1. 2. SCALAR DATA TYPE COMPOSITE DATA TYPE Scalar Data Type is a data type which can store one value at one point of time in form of one variable. Composite Data Type is a data type which can store multiple values at one point of time in form of one variable. SCALAR DATA TYPE CHAR, VARCHAR2, NUMBER, DATE, BOOLEAN Scalar Data Type provides an Attribute %type. COMPOSITE DATA TYPE User defined data type or type declaration. It %rowtype. provides an attribute called
Declaring A Variable
Syntax : DECLARE V_NAME DATATYPE(SIZE); A NUMBER (4); V_NAME DATATYPE(SIZE):=<VALUE>
A NUMBER(4):= 10; Note : In PL SQL assignment operators is := . Each and individual statement in PL SQL are to be terminated by ; .
To Display Output
DBMS_OUTPUT.PUT_LINE( ); It will work after declaring SET SERVEROUTPUT ON before declaration block. *Note : To use DBMS_OUTPUT.PUT_LINE( ) a related SQL * PLUS command is required known as SET SERVER OUTPUT ON, which allows the Server to display the output in client console. The default behavior is OFF .
Anonymous Block is a type of programme whose programme code is stored inside client hard disk in form of .SQL file . Where as Sub Programme is a type of program whose program code is stored inside Database server in form of Object. *Note : The job of anonymous block and sub programme is same to manipulate the database programmatically, but divided into 2 category depending on their security.
INTO VEMPNO, VNAME,VSAL, VJOB FROM EMP WHERE ENAME= BLAKE; DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.NO : || VEMPNO) DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.NAME : || VNAME) DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.SAL : || VSAL) DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.JOB : || VJOB) END; / Dynamic Input Where Ename = &name ;
END; /
SET SERVEROUTPUT ON CLEAR SCREEN SET VERIFY OFF DECLARE TYPE MYTYPE IS RECORD (VEMPNO EMP.EMPNO%TYPE, VNAME EMP.ENAME%TYPE, VSAL EMP.SAL%TYPE, VJOB EMP. JOB%TYPE); A MYTYPE; BEGIN SELECT EMPNO,ENAME,SAL,JOB INTO A FROM EMP WHERE ENAME='&NAME'; DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VEMPNO); DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VNAME); DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VSAL); DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VJOB); END; / In the above example MYTYPE is a structure where as A is a Variable of Mytype.
Syntax of IF
STATEMENT; ELSE STATEMENT; ENDIF; Syntax of Nested IF : IF <CONDITION> THEN STATEMENT; STATEMENT; ELSIF <CONDITION> THEN STATEMENT; STATEMENT; ELSIF <CONDITION> THEN STATEMENT; STATEMENT; ELSE STATEMENT; END IF;.
OR
IF <CONDITION> THEN STATEMENT; STATEMENT; ELSE IF <CONDITION> THEN STATEMENT; STATEMENT; ELSE IF <CONDITION> THEN STATEMENT; STATEMENT; ELSE ENDIF; ENDIF; ENDIF;
first then it checks the condition . In this type of looping the statement must be executed once. Syntax : LOOP STATEMENT; STATEMENT; STATEMENT; EXIT [WHEN <CONDITION>]; END LOOP; Example : DECLARE I NUMBER(4):=1; BEGIN LOOP DBMS_OUTPUT.PUT_LINE(I); I:=I+1; EXIT WHEN I>10; END LOOP; END; / Syntax Of While LOOP : This is a type of looping where the condition is checked first then it will execute the statement. If the condition is set to false the system control will move to the very next statement after looping. Syntax : WHILE <CONDITION> LOOP STATEMENT; STATEMENT; ------------------; ------------------; END LOOP; Example : SET SERVEROUTPUT ON
DECLARE I NUMBER(4):=1; BEGIN WHILE I<=10 LOOP DBMS_OUTPUT.PUT_LINE(I); I:=I+1; END LOOP; END; / Syntax For FOR LOOP : For loop is otherwise known as an iterative loop. The advantage of for loop is the initialization and the incrimination done automatically by system itself. Syntax : FOR <COUNTER> IN [REVERSE] LBOUND..UBOUND LOOP STATEMENT; STATEMENT; END LOOP; Example DECLARE I NUMBER(4); BEGIN FOR I IN 1..10 LOOP DBMS_OUTPUT.PUT_LINE(I); END LOOP; END; / :
CURSOR
When ever a PL SQL programme is executed automatically a temporary memory will be created inside the server where a SQL Statement is dumped, executed and once the statement is executed automatically the memory is deleted from the server. The memory which is accomplished the above is basically known as CURSOR. CURSOR is nothing but a private sequel area where SQL statement is stored, executed
and once the execution is done automatically cursor memory will be deleted from the SERVER. Cursor is basically categorized in 2 different types 1. 2. Implicit Cursor (Automatically) Explicit (Create By Own)
Cursor ha s4 different stages namely 1. 2. 3. 4. DECLARE OPEN FETCH CLOSE DECLARATION of a cursor means the memory will be declared inside the srver and the statement will be dumped inside the memory. OPENING of a cursor means the statement available inside the temporary memory starts execution and the output returned by the statement will be stored inside the same memory. FETCHING of a cursor means the output available inside the temporary memory will be transport one by one to the respective variable. CLOSING of a cursor means the memory will be deallocated once the processing is over.
IMPLICIT CURSOR is a type of cursor where all the above jobs are being dump implicitly by the system itself but the disadvantages of implicit cursor is it can store one record at one point of time. Where as EXPLICIT CURSOR is a type of cursor where all the above jobs are done by explicitly by the user itself but the advantage of an explicit cursor is it can store multiple records at one point of time for the processing purpose. Cursor has four different attributes to manipulate itself. 1. 2. 3. 4. given by the system. Declaring An Explicit Cursor Syntax : DECLARE CURSOR <C_NAME> IS <SELECT STATEMENT>; Opening Explicit Cursor Syntax : BEGIN OPEN <C_NAME> ; Fetching An Explicit Cursor Syntax : FETCH <C_NAME> INTO <V_NAME>; Closing An Explicit Cursor Syntax : CLOSE <C_NAME> END; / Simple Cursor Using Basic Loop Example : %FOUND %NOTFOUND %ISOPEN %ROWCOUNT
The above attributes are always suffixed with the cursor name either given by the user or
SET SERVEROUTPUT ON DECLARE CURSOR C1 IS SELECT EMPNO,ENAME,SAL,JOB FROM EMP WHERE JOB='MANAGER'; A C1%ROWTYPE; BEGIN OPEN C1; LOOP FETCH C1 INTO A; EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :'|| A.EMPNO); DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME :'|| A.ENAME); DBMS_OUTPUT.PUT_LINE('EMPLOYEE SALARAY :'|| A.SAL); DBMS_OUTPUT.PUT_LINE('EMPLOYEE JOB :'|| A.JOB); DBMS_OUTPUT.PUT_LINE('----------------------');
END LOOP; CLOSE C1; END; / The above example is an example of simple cursor using basic loop. **Note : Open is a key word which can perform 2 jobs 1. 2. 1. 2. Execute the statement and stores the output inside the same memory Set the pointer to the 1st record of the record set. Fetch the current record into the variable Skip the pointer to the nest record of the record set.
<SELECT STATEMENT>; BEGIN FOR <V_NAME> IN <C_NAME> LOOP STATEMENT; STATEMENT; -----------------; END LOOP; END; / Example : SET SERVEROUTPUT ON DECLARE CURSOR C1 IS SELECT EMPNO,ENAME,SAL,JOB FROM EMP WHERE JOB='MANAGER'; BEGIN FOR A IN C1 LOOP DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :'|| A.EMPNO); DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME :'|| A.ENAME); DBMS_OUTPUT.PUT_LINE('EMPLOYEE SALARAY :'|| A.SAL); DBMS_OUTPUT.PUT_LINE('EMPLOYEE JOB :'|| A.JOB); DBMS_OUTPUT.PUT_LINE('----------------------'); END LOOP; END; /
Example
:
SET SERVEROUTPUT ON DECLARE CURSOR C1(VJOB VARCHAR2) IS SELECT EMPNO, ENAME, SAL , JOB FROM EMP WHERE JOB=VJOB; BEGIN FOR A IN C1('&VJOB')LOOP DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :'|| A.EMPNO); DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME :'|| A.ENAME); DBMS_OUTPUT.PUT_LINE('EMPLOYEE SALARAY :'|| A.SAL); DBMS_OUTPUT.PUT_LINE('EMPLOYEE JOB :'|| A.JOB); DBMS_OUTPUT.PUT_LINE('----------------------');
SUBPROGRAMS
Subprograms has to be physical existence inside the server inform of object . Subprograms are otherwise known as NAME BLOCK when any other block otherwise known as UNAME BLOCK. The advantages of subprograms, it is more secured than anonymous block. Subprograms is categorized in 2 different types. 1. 2. STORED PROCEDURE STORED FUNCTION
Creating A Procedure
Syntax :
CREATE [OR REPLACE] PROCEDURE <P_NAME> [(ARG DATATYPE)] IS/AS IDENTIFIER DECLARATION TYPE DECLARATION CURSOR DECLARATION BEGIN STATEMENT; STATEMENT; ; END <P_NAME> Example :
PACKAGE
Package is nothing but a container which contains related procedure and function to be used by one user or different users. The advantage of a package is to make the procedure & function execution faster. Package has 2 different parts or blocks.
1. 2.
Package Specification block is a block where all procedure & functions are to be declared or specified to be used inside a package where as Package Body is a block where all the procedure and function are to be designed which are developed in the Specification block. **Note : Procedure & Function specified in the specification block may or may not be designed in the body block but the procedures & functions designed in the body block have to be specified in the specification block. Syntax Of Package Specification Syntax : CREATE [OR REPLACE] PACKAGE <PA_NAME> IS / AS PROCEDURE <P_NAME > [(ARG DATATYPE)]; PROCEDURE <P_NAME > [(ARG DATATYPE)]; PROCEDURE <P_NAME > [(ARG DATATYPE)]; -------------------------------------------------------------N; END <PA_NAME>; / Syntax Of Package Body : :