Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
113 views
PL-SQL Book
Uploaded by
storms14112004
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Pl-Sql book For Later
Download
Save
Save Pl-Sql book For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
113 views
PL-SQL Book
Uploaded by
storms14112004
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Pl-Sql book For Later
Carousel Previous
Carousel Next
Save
Save Pl-Sql book For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 111
Search
Fullscreen
| Sr. UNIT-1 Ries — bof. Codd’s Rules, ; —_ 1 fo. DDL Statement ; q _ Bt Integrity Constraints ts 7 4. DML Statements : 6 a 5. Sequences and Synonyms 3 one 6. Built in Functions : 35 aw 1 Aggregate Functions 40 — 8. Clauses Used With Aggregate Functions 2 lo. Char Funetion 46 — 10, Convertion Function 48 a jl. Decode 51 [2 12. Join 2 | en 13 SET Operators 55 —— | 14. Sub queries. 56 oe 15, DCL and TCL Statements 61 | 16. Questions on Unit I 67 | Sr. UNIT - 0 Pg. No. 1 View: 68 2 Types of Views, a 3, Using Object Views a 4. Materialized iews a 3. PL/SQL Programming a > Identifier a © Operators and Expression, cE) © Conditional Statements 2 © Mterative Statement, KL cuestoss nuit = ———unr = 1 Exceptions Handing 107 © Predefnnes Exceptions 108 Users defines Exceptions u3 2. | Cursors 6 Types of Cursors 6.122 | 1 Parameter Passing in Cursors 123 3. | Procedures oy Procedures with Parameters 127 + Granting Permissions 15 4. | Cursors and Procedures. 16 s Questions on Unit I ep ise [_unrr-Ww Fp 1 Fuctions 138 © Advatages Fuctions 142 Purity Levels in Functions Ms Executing Functions 146 fi eta 147 ‘> Types of Trigger 148 ‘> Trigger Predicates 154 © Instead of Triggers 155 Questions on UnitV 159 University Question Paper 160 SS, Unit -1 Important Terminologies Database: Collection of related data is knavm as a database. Database Management System: Database containing interrelated data along with a set of application programs to manage the data stored in database is known as a database management system. B, Relational Database Management System ‘A Database Management System is known as Relational Database “Management System if the database is stored inform of tables. Tables are also known as relations. It consists of Rows and Columns. Like DBMS, RDBMS also has a set of application programs to access the database. (Oracle, Sybase and Infomix are some examples of RDBMS. CODD’s Rules: Dr. E.F. CODD, an IBM Researcher developed a model in 1970 and suggested a set of 12 rules that work as guidelines 10 be followed by an ideal RDBMS. Till date we did not come across a single RDBMS which follows al the rules. 4. Information Rule: This rile is meant for storing information. All the data should be placed in form of tables. 2. Guaranteed Access Rule: If data is stored in a database there should be ' guaranteed access to the data without any ambiguity. This is possible only if we know the name of the table and the name of the column in ‘which the data is stored. 3. Systematic Treatment of NULL values: At times due to unavailability of data it is not possible to make an entry in a field for a specific row. Under such circumstances facility should be available to keep the field entry empty Null values should be allowed as entries. Null entry does not mean an empty string or zero. ‘Nill value ina field can be denied by putting anull constraint fr acolumn. ‘4. Dynamic On-line Catalog based on the relational model: It should be possible to access the structure of a database with the help of same tools {that acess the data A special ables used to store the definition of structre. 5. Comprehensive Data Sublanguage Rule:The database should support «language that can give data definition, data manipulation, data integrity and data transaction control, Databases like oracle, support languages like SQL(Structured query language), Quel ete.Tae Lbs —<—< paeih needed while working with amniil ages = vy the database and database mel ' ut Pate ‘of the way in which : ependeae The seri roavare of he way in whic a 8 ys Dt Indep sco storage device, Changes made ition languare: sea of suring the data shoud nt affet the user with respect to is created it becomes necessary to insert, retrieve and TITTENG reinal of | 49, Lapel Data Independence: logical structure of database changes it comin {OE aft he mane in which dais viewed. ee inner Independence: While etering data it shouldbe ensured that eae at eared by the wseriscoret. The database language La ‘Seakesportconsrains onthe datas entered in column to ensure ‘ssn Frc Sepia sendotveey mallets, Grant: This comand los specified ser topo pcind aint ky tas ‘IL Distribution Independence: A database ii, Revoke : This command cancels previously grante lenied permi- ri son rf ft. Hed be 2 ang be pee reece Ee a 7 en ete ears DCL command cancels previously granted or denied , 12.Non sabversion Ral: We shouldbe able to modify the strcture of | a eit pte — Te ih ye Bs abet madi the suctue Of 8 Operations that are performed on a database are known as transactions oma “Transactions made onthe database canbe saved or canbe undone. Ths is — > OmdeDataase Objects: ssid hy Taracon no ingen baee t i, Commit statement: To make the changes permanent for the current on legal ab chav a and ehavemeto nrc interact rransactions, 7 icenstaautehtetn Gnade Malta women od ale opr ei amt iadeastucexe wa . sample ofa oie sate Oe a Temes common 4 oat) stored proces, Qtr examples of objets are indexes,“ anguage) Dea Sequences, views, synonyms ete, language which helps us to retrieve data fromthe onal tuctured Query Language database Example, SELECT command rc sores the din the ee mami | sioreandreive data ere has tobe some way to mn his oracle defined an. me melnoe, > ae iil rests ic bar tia their characteristics. Data Types ia Oracle haracer, dateete. Therefore, fferent types depending on Acolna asthe capability ofholdng only onetype of data wh ‘espefiad when the data structure fora tables defined, with DDL ine. 1. NUMBER: A column whose datatype is defined as a NUMBER as the this fixed. Ifa string of spaces to maintain the ‘The variable name or column name is defined as CHAR type which can ch ‘the name °xyz' is entered the served that in char datatype, memory padded with spaces to maintain the size. ty ofholding strings of variable length. an hold up to 25S characters, VARCHAR (SIZE) VARCHAR2 (SIZE) = Example: tes memory places and hhence no wastage of memory. igh VARCHAR and VARCHAR? is doing the same job. ‘VARCHAR is not used in higher versions of oracle therefore it is better to we VARCHAR2. ‘4. DATE: This datatype is used to store date and time. It stores yea, month and day values for date. For tores hours, minutes and seconds ‘ales. The standard format for string date is DD-MMIM-Y Y. Default format 's DD-MMM-YY. If we want to store date in some other format, then lable in SQL. DateTime stores date in 24 for valid dates are from J 31,4712 aD. ‘date that gives current date and time. Oracle database uses is own internal format to store dates. Default format can be changed usingNLS_DATE FORMAT.© LONG: This data Jength. The maxi restrictions. LONG datatype osc + eas to be restricted Therefore pertable, ii. LONG values can be use it a Subgoeris b. Functions Expression Indexes iii. Functions lke SUBSTR which work on normal charac cannot wor on LONG. data 6. RAW: RAW dataype is used to store binary data o ‘rented (for example graphics or audio files), RAW data can {Geer bur it cannot be manipulated. RAW data has different SQL and PL/SOL. inSOL is max size limits 2000 bytes an itsrax sie limits 32767 Symtax: RAW (size) RAW data canbe indexed. 7. LONGRAW: LONG RAW is similarto RAW butithas higher capacity of Store ie. up to2 GB. A table can have only one LONG RAW column ‘Because ofthe size is impractical to automatically retrieve all the data LONG RAW cans be indexed 8. LOB : LOB means Large Object data. LOBs are designed to support unsirctured deta. By unstructured data we mean text, graphic images, sill video clips, fll motion video and sound waveform, LOI unstructured data. The data may be within the database or ‘object maybe up to AGB. LOB datatype is better than LON BAW. > Difference between RAW and LONG RAW maT 1, Sts sie Smit is2000 bytes | 4 2. his possible to automatically rettiove data 7 BSeGura ‘B.8e. sem. > Difference between CHAR and VARCHAR v 1. fthas variable length 2. Memary i ted as only necessary amount of space is used, 3. Specifying the size is mandatory, 4. Max size is 4000 byes Difference between LONG/LONG RAW and LOB [tos LONG/LONGRAW 1. This data type can handle | 1. This datatype can handle 2GB data. 4GB data, T,_ A table can ave only one 2. Atable can have multiple LOB LONG column. columns of diferent types. 3. LONG supports only sequenifI 3. LOBSs support random access 10 acces to data dan, Operators in Oracle: ‘An operator manipulates data items and returns a result. The data items are called operands or arguments. There are two types of operators unary ‘and binary. A unary operator uses only one operand and binary operator uses two operands Arithmetic Operators Character Operators ‘Comparison Operators Logical Operators Set Operators Other Operators Arithmetic Operators: ‘There are two types of arithmetic operator: 8) Unary Operators a. + Makes operand positive b, ~ Negates operand = a ryd Preface Book & Co, ee Ee | ee Pre Be oe, *__B8coure ry Operators Sie Opon an $m . EM Divi — (works on Numbers and dates) 4, Logical Operators: Logical b. * Mabtplication Not | Rewns TRI c_ ~ Addition (works on Numbers and dates) Rear FALS 42. Subtraction (works on Numbers and dates) : = that compare ove expression te TRUE, FALSE or UNKN 10 rows. . Set Operators: Set operators combine the result of two queies into & ona single result. 5 Equality test UNION stnct rows selected by either query = UNIONALL ys selected by either query, including > TRTERSECT |” Ketunsalldintrons least baie ges D Z INTERSECTALL B= greater than or equal to test ‘MINUS ‘Returns all distinct rows selected by the first query = ess than or equal fo test but not the second. WN equivalentto any member oftest_| 6 Other Operators: "ANYSOME i NOTIN 5 e [NOT] between x and y ‘Not greater than or equal x and not j—sessimanerequaltey _]} ast one cohumm. Exits ‘TRUE iffa subquery has at least one Syotax row. CREATETABLE table_name a ( \10 ine Column_namel datatype (st =) Example: Column_name2 datatype (S22) DESC St [Table constraints} After the « v3 : tem that we want to DE «CREATE TABLE isa keyword telling the database syst SO create a new table. ete O js the name given to a table. table_name: i me ‘specify the name of the column. ROLL_} See i of data a column can hold. NAME ‘The datatype parameters specifies what type . VARCHAR type. ‘NUMBER typeete. : The datatype ay deo AP sf the column. It is a ad «The size parameter specifies the maximum length of the column. Gan? numeric value. +s The columns should be separated by comma. PERCEN *. ‘Thestatement should end with asemicolon. 4 ‘The Parenthesis include the entire list of columns in thetable. > Inserting * Thecolumns and the table may have constraints which may be optional, es Example: command. SQL> CREATE TABLE STUDENT(ROLL_NO CHAR(6),NAME enables us ‘VARCHAR2(30),ADDRESS VARCHAR2(40),CITY. Syntax: ‘VARCHAR(20), PERCENTAGE NUMBER(S,2)); INSERT I ‘After the execution of this command the following message will displayed: _ Values (ex Table created. © INSERT it > Rules for table names and column names: © table is the * The name should start with an alphabet. => expressior + Itmay have alphabets, numbers or underscore (_ ) are ‘* Its maximum length is 30 characters. ~ © Acolumn + Keyword: Keyword shoud note wsedas names fore g, CREATE, SELECT, INSERT 5 ahaa ‘Try this yourself = Statement Create table CUSTOMER with cust_id, c1 © Ifa list of« as col it ust_name, age, and add: column, is column, Use suitable datatypes and sizefor the eoluma | = Ifthe value > Viewing the structure ofa table necessary t After creating a table if ; Example 1 ee done by Rai following onsen a the structure of the table. Itcan SQL>INSE Syntax: STUDENT DESC table_name; After the ex 8 DESCis a keyword.It stands for DESCRIBI Ree Stee cI ' table_name is the name Sri and desctibes an oracletable “ ROLL_NO aan ole a8 aaaa0 BScGuru B.Sc. Som. VI ‘After the execution of this command the following structure will displayed: SQL> DESC STUDENT Name Null? Type ROLL_NO CHAR(6) NAME, VARCHAR2(30) ADDRESS VARCHAR2(40) ciry VARCHAR2(20) PERCENTAGE ‘NUMBER(G,2) Inserting data into a table: ‘Once a table is created data can be inserted into the table using the INSERT command, INSERT command is a DML command. INSERT command enables us to insert one or multiple records in a table. ‘Syntax: INSERT INTO table(column1, column2, ..n.-ne » column n) Values (expression, expression2, suv expression n); INSERT is a keyword table is the table-name in which the data has to be inserted. expression1 expression 2, .....-» Will be assigned to column! column2, smn Column respectively. ‘A column from a table can be omitted ifit allows NULL values Itis necessary to provide a value for every NOT NULL column Column name and expression should be separated by commas Statement should be terminated by a semicolon Ifa list of columns is not specified then data has to be provided for every column, Ifthe values provided are less than the number of table columns, then it is necessary to mention the columns, Example 1: SQL>INSERT INTO STUDENT (ROLL_NO,NAME,PERCENTAGE) STUDENT VALUES(‘210",’XYZ’,76.5); fier the execution of this command the following message will displayed: Lrow created. ROLL_NO 210s assigned to ROLL_NO s & = = aiE & 76.5 isassigned to PERCENT ao 2 ADDRESS field will beassigne ae ef vi insert only one recor < This command wil inser on ation mark ing must be in sing © Character string be stand alone ee i’, SEMINARY 2: «123°, Tanvi’,” SOLS NSERT INTO STUDENT VALUES( 123 2 79.6); is ‘ill displayed; HILLS’ NAGPUR’,79.6 lowing message will display ‘After the execution of this command the following row created. - Her, column names ae not mentioned as val jumns in the record. «Field must be in same order as the columns are Example a For an existing table Employee, withthe following structure. EMP_CODE CHAR(5) ‘NAME VARCHAR (20) DOB DATE SALARY NUMBER (7,2) Write an insert command to insert a record. INSERT into Employee values (123°, ‘Harshada’,TO_DATE('25-SEP- 1984”),60000.0); = TO_DATE isa function that converts CHAR datatype into type date. © Itis a good practice to specify a format_mask with TO_DATE function Example 4: Insertion of a record by reading the d: 0 h the oun ry ing the data throug! SQL> INSERT INTO STUDENT VALUES (&ROLL_NO’,’&NAME',’&ADDRESS’,’ Enter value for roll_no: 111 Enter value for name: UITWAL, Enter value for address: WAKAD Enter value for city: NAGPUR, Enter value for percentage: 95,5 Oldl: INSERT INTO STUDENT VALUES ( s ' ADDRESS & CITY’ APERCENTAGE), | OLL-NO'& NAME’ 8 new! : INSERT INTO STUDENT VALUES Che WIWAL’,’ WAKADY, ‘NAGPUR’, 95 5) er the execution of this command — row created, ‘hefollowing message willbe displayed lues are provided for all the ‘&CITY’,& PERCENTAGE); 43 BSc > Retrievin; It should be using the S This statem from a table » Viewing a Syntax: SELECT *f Example: SQL>SELE All the recor ROLL_NO 210 123 u1 112 > Viewing s Syntax: SELECT col Example: SQL> SELE: After the ex displayed: NAME Harshada Tanvi Ujjwal Gaurav ‘Try this You 1. Display cu has the fol CusT_ CUST_NA! CONTACT8 BScGuru {3__BseGum __ teem > Retrieving data from the table v ~ It should be possible to view the records from the table. This is possible using the SELECT command. SELECT command is a DRL statement. This statement helps us to view either all the records or selected records from a table. Viewing all the records from a table Syntax: SELECT * FROM TABLE_NAME; Example: SQL>SELECT * FROM STUDENT; All the records from the STUDENT table will be displayed ROLL_NO NAME ADDRESS CITY PERCENTAGE 210 Harshada 16S 123 Tanvi SEMINARY NAGPUR 79.6 HILLS ut Ujjwal = Wakad Nagpur 95.5 12 Gaurav Navpada ‘Thane 94.5 Viewing selected columns from table Syntax: SELECT column_namel, column_name2...... FROM table_name; Example: SQL> SELECT NAME, PERCENTAGE FROM STUDENT; After the execution of this command the following records will be displayed: NAME PERCENTAGE Harshada 76.5 Tanvi 79.6 Ujwal 95.5 Gaurav 94.5 ‘Try this Yourself _ 1. Display cust_id and cust_name using customer table, Customer table has the following structure. CUST_ CHAR(6) CUST_NAME VARCHAR2 CONTACT NO_NUMBER(10) _Preface Book & Co, g selected rows from the table cruect + PROM table_name where condition; Beam eLECT *FROM Su wine PERCENTAGE>90; i lisplayed. UuwAL WAKAD NAGPUR 95:5 9. i Navpada Thane 4.5 M2 ‘Try this yourself from Employee table whose salary Gaurav 1. View the record of those employees is less than 10,000. > Viewing selected columns and rows It is possible to make two-way selection. Syntax: SELECT columni, column2 FROM ‘table_name where condition; Example: SQL>SELECT ROLL_NO, NAME FROM STUDENT WHERE PERCENTAGE>90; ROLL_NO and NAME will be displayed for only those ‘students whose percentage is greater than 90 ROLL. No NAME mM USIWAL 42 Gaurav > Deriving Tables from existing table Suppose a table already exists and we want to create another table which has selected information from existing table. This is possible by adding @ select statement at the end of the create table statement. © Ifany error occurs while copying the data to the table, it is automatically dropped and not created. This statement does not create indexes for us. ‘The new table will be populated with the records from the existing table: Example 1: We want to copy all the columns from tablel to table2. The following command can be used. CREATE TABLE table2 AS SELECT *FROM table]; ag 45 az vooag Examp from ex CREAT columni The coh from tal ‘The col Examp column column the coli CREAT column, Examp table in stateme Examp) CREAT WHERI The tab stateme NOTE: - Atable . If we wi without in the w Alterin If we w: commar columns Ttalsoe: Alter tat First a te The alte: The orig ‘The tem Adding Syntax: ALTER? zstRE hose ‘hich inga cally able. The 45 BSc. Sem. VI 46__BSeGuru______...____—aase.semw Example2: If we want to create a new table by copying selected columns from existing table. CREATE TABLE table} AS SELECT column}, column2, — columnn FROM table2; ‘The columns column! , column: from table2 and will be copied to table3 ‘The column names remain unchanged in table3. column will be selected Example 3: If we want to create a new table by copying selected columns from existing table but with new names.If we want to copy column_namel and column_name? from table3 to tabled and rename the columns as column_name3 and column_named respectively. CREATE TABLE tabled (column_name3, column_name4) AS SELECT column_name1, column_name2 FROM table3; Example 4:1f we want to copy selected records from columns of existing table in a new table then WHERE clause can be used after the SELECT statement which is preceded by the CREATE TABLE. Example: CREATE TABLE TableS AS SELECT columnl, column? FROM Tablel WHERE condition; The table5 will be populated with information retuned by the SELECT ‘statement. NOTE: . A table can be created by selecting columns from the multiple tables. If we want to create a new table having the structure of the existing table without copying any records. Give the select command with a condition in the where clause that is not satisfied. Altering Table: If we want to modify the structure of an existing table ALTER TABLE command can be used. It allows us to add, delete, rename or modify columns in an existing table. It also enables us to add and drop constraints from existing table. Alter table works in the following way: First a temporary copy of the original table is created. The alterations are made to the temporary copy. The original copy is deleted. ‘The temporary copy is renamed. Adding column to the table Syntax: ALTER TABLE table_namell Preface Book & Co, fe Solumn_name2 datatype (size)); ADD (column_name! datatyPs EB ER (7,2)); Sait ENT ADD (STIPENT NUMBER (7,2)); > ALTER TABLE STUD! ENTER is se Teecution of this command the fo displayed Table altered. / [After alteration ofthe table, the structure will be SQL> DESC STUDENT; Name Null Type ROUNO CHAR() ee VARCHAR20) ADDRESS VARCHAR2(40) Gu ‘VARCHAR2(20) PERCENTAGE NUMBER(S) STIPENT JUMBER(7,2) > Dropping column from a table Ii'we want to drop a column from a table. Syntax: ALTER TABLE table_name DROP COLUMN column_name; Example: SQL>ALTER TABLE STUDENT DROPCOLUMN ADDRESS; After the execution of this displayed: Table Altered Note: A column ina table can be dro > Modifying existing column fica — ae eee cate to the name of the column, datatype of the Syntax: ALTER TABLE table_name ony (column_name New Datatype(NewSize)); SQL>ALTER TABLE STUDI MODIFY (NAME: VARCHARGS), fer the executi m atte execution ofthis command the following message will be command the following message will be Ped only ifit does not have any data. 17__BSeGu Table Alter Note: 1) The 2) The 3) The coh > Dropping If we no long free the mem Syntax: DROPTABL Example: SQL>DROP* After the ext displayed: Table Drop, > Droppingata > Returns the fi > All views and butare invalid => Synonyms for => Whena table recycle bin. = Atablefromr Try this vou Write aSQL q Field Name Emp_no Emp_name Address Phone_Numb Display ti Display ti‘able Altered 2y Note: |) The name of the column cannot be changed. i's 2) The name of the table cannot be changed. 3) The size of the column cannot be reduced if data is present in the column > Dropping Tables If we no longer need a table. It is a good practice to remove the table and free the memory for other purpose. DROP TABLE can be used. DROP TABLE table_name; Example: SQL>DROP TABLE STUDENT; After the execution of this command the following message will be displayed: Table Dropped Dropping a table removes the table definition. Retums the free space which can be used by other objects. All views and PL/SQL program unit dependent on a dropped table remain butare invalid. Synonyms for a table still exit but becomes invalid. When a table is dropped, the database renames the table and is placed in recycle bin. © A table from recycle bin can be recovered by FLASHBACK command. iil be ‘Try this yourself Write a SQL query to create a table “Employee” fen Field Name Datatype Sie Emp_no varchar? 5 Emp_name varchar? 25 of the Address varchar2 50 Phone Number number 10 Designation varchar? 1s Salary number 1S J. Display the structure of table, 2. Add qualification fleld at the end of employee table. 3. Modify the size of the name field 25 to 30. bee 4. Display the employee name whose salary is greater than 20,000. S._Display the employees details whose name starts with ‘A’.Preface Book & Co, > Integrity Constraints ‘curacy and consistency of data Integrity constraints are used 10 ens a ud be ensured that .. When data enters th inate dat ay he dtabase admit or ppication ito i ing constraints on columns of a is can be achieved by setting const ns of tte 7 doe to ‘ensure that valid data enters @ some fay adding table, Ths i ake oracle, domostof the work in maintaining the integrity co abuse so that work is reduced. A name can be given {0 constraint ae can be created at the time of creation of table or canbe later ed toa table by using alter command. Constraints can be added a aa jevel or at the end of the create table statement. Column lev cenaints are applied only to one column and table level constraints are applied to the entire table. > Types of constraints . Primary Key constraints Foreign Key constraints }. Unique Key constraints ‘NULL value constraints Check constraints © Candidate Key constraints: A candidate key is a combination of one or ‘more columns, the value of which uniquely identifies each row of the table, Candidate key does not allow NULL values. © Primary Key constraints: A primary key is one of the candidate keys that uniquely identifies a record. Itcannot have null values. A database can have one and only one primary key. Primary key must contain unique values; duplicate values are not allowed. This choice of primary key in a relational database often depends on the nice of the administrator, Primary key should not be LONG or LONG There are two types of primary keys 1. Simplekey 2. Composite key 4+ Simple key: -A primary key isa simple key if it has a single column Example: - Roll_no, driver_licence number, telephone number ete, Primary key is a composite key ifit is made of two ot 2. Composite key:~A ‘more columns. 9 BScGura © Primary key eo SOL>CREATE After the execu displayed: Table created. Here ROLL_NC © Primary key © If we want to d defined at column Example SQL>CREATE D_O FDATEN. PRIMARY KEY After the execu displayed: Table created. NOTE: Simple is the user’s cho © Primary key ca If the table is al Primary key. Itc SQL>ALTER Ts (Employee_code After the execu displayed Table altered. Foreign key co This constraint i: column ina table primary key of th is the child table, key is the master Foreign key de Example SQL>CREATE T, WL ree el YeLo. data td that ‘cation sofa idding tegrity straint ve later ded at revel ais are ‘one or of the e keys isecan unique ‘on the ONG nn. two or fr. resize rt ETT Vy ta Ve BScGura apa ay ental Ga ia ee = Primary key constraints can be defined at column leveh SQL>CREATE TABLE Student (ROLL_NO CHAR (6) PRIMARY KEY, NAME VARCHAR: ADDRESS VARCHAR? (20), PERCENTAGE NUMBER.2) 2 After the execution of this command the following message will be displayed iB sage will be ‘Table created. Here ROLL_NO is a primary key as it uniquely identifies a record. Primary key constraints can be defined at table level, If we want to define a composite key as a primary key, defined at column level and it has to be defined at table level Example ‘SQL>CREATE TABLE FLIGHT_DETAILS (FLIGHT_NO CHAR (6), D_O_FDATE,NAME of CUSTVARCHAR (10), CLASS VARCHAR (10), PRIMARY KEY (FLIGHT_NO, DOF); After the execution of this command the following message will be displayed: Table created. NOTE: Simple primary key can be defined at column level or table level. It is the user’s choice it cannot be Primary key can be created using ALTER command If the table is already created and then we wish to declare a column as primary key. It can be done using the ALTER command, ‘SQL>ALTER TABLE Employee ADD CONSTRAINT PRIMARY KEY (Employee_code); After the execution of this command the following message will be displayed: Table altered, Foreign key constraint: ‘This constraint is used to ensure referential integrity. A foreign key is a column in a table that references to a column in another table most often a primary key of that table. The first table in which we have the foreign key is the child table or transaction table and the table containing the primary key is the master table or parent table. Foreign key defined at column level. Example SQL>CREATE TABLE STUDENTPreface Book & Co 20 NAME VARCHAR? (40), PH_Ng (ROLL, NOCHAR (6) PRIMARY! Ce ee of this command the following message Will be Tanah rare a ie 1 EFERENCES STUDENT, PHY NUMBER (3), MATHNUMBER QB). COMP_SCINUMBER (3));_ ' After the exeeution of this command the following message will be displayed: reated. . ne rr example we have defined two tables one is the STUDENT table which contains student information and other is the MARKS table that contains the marks of students. In this case the STUDENT is the parent table and has the primary key ROLL_NO. The table marks is the child table in which we define ROLL_NO as a foreign key. Hence the primary key of student table is defined as a foreign key of the marks table. So the child table can easily refer to the parent table and we can find out which marks are associated with which student on the basis of the foreign key ROLL_NO. So there is a relationship established between the two tables because of the foreign key constraint. > Foreign key defined at table level ‘SQL>CREATE table Marks (ROLL_NO CHAR (6), PHY NUMBER (3), MTH NUMBER (3), COMP_SCINI MBER (3), FOREIGN KEY OLL. B (ROLL_N' s STUDENT ROLL. NO): NO) REFERENCE After the executi i a paral on of this command the following message will be Table created, ; Hie {0 be followed by Foreign key colueun ike the primary key a foreign key o 1 Unley a foreign key column can have N can oe HEY MAY not always refer to-a primary kee yee ee toa column having unique constreint? eet table. 3. Foreign key can be defined on} a imns hi 21 BS > Clauses Along w 1, ONDEL 2. ONDEL 1. ONDEL foreignk records fi if ON DE Syntax: SQL>CR (ROLL PHY NU After the displayed Table cre NOTE Ifthe rece then all th value ‘12 table tor existing r 2. ONDEL} This clau: effect beit the record child table Syntax: SQL>CRI (ROLL_N COMP _s: (ROLL_N NULL); After the displayed: Table crea NOTE: Ifa record bi having “125or 6 2 BScGuru cr . 5 Clauses defined with the Foreign Key Along with Foreign key constraint two clauses can be defined ON DELETE CASCADE ONDELETE SET NULL, ON DELETE CASCADE: This clause can be used with the definition of foreign key. The effect being if a record in the parent table is deleted all the records from the child table having the same key value will also be deleted ifON DELETE CASCADE is used otherwise an error is generated, Syntax: SQL>CREATE TABLE MARKS (ROLL_NO CHAR (6) REFERENCES Student ON DELETE CASCADE, PHY NUMBER (3), MTH NUMBER | (3), COMP_SCI NUMBER (3); After the execution of this command the following message will be displayed: Table created. NOTE: Ifthe record having ROLL_NO ‘ 125" is deleted from the STUDENT table, then all the records from the MARKS table having the same reference key value ‘125° are also deleted i.e, we do not want any record from the child table to refer to the deleted record from the parent table i.e. at a non- existing record. . ONDELETE SET NULL: This clause can also be used with the definition of FOREIGN KEY. The effect being if'a record in the parent table is deleted. The references of all the records from the child table are set to NULL i.e. No record from the child table will point at the deleted (non-existing record) Syntax: SQL>CREATE TABLE Marks (ROLL_NO CHAR (6), PHY NUMBER (2), MTH NUMBER (2), COMP_SCINUMBER (2), CONSTRAINT FK FOREIGN KEY (ROLL_NO) REFERENCES STUDENT(ROLL_NO) ON DELETE SET NULL); After the execution of this command the following message will be displayed: Table created. NOTE: Ifa record having ROLL_NO ‘125” is deleted from the parent tableall the records having *125" as their reference value from the child table will be set to NULL. 2 a & € 2 aPreface Book & Co, 22 3, UNIQUEKEY CONS If we want a column in UNIQUE KEY CONS’ Y CONSTRAINT can’ by h eae ‘This constraint can be laid at level > Definition UNIQUE KEY | CONSTRAINT at column yL>CREATE TABLE Employee cw NO CHAR (5) UNIQUE, NAME VARCHAR (20), DOB DATE, SALARY NUMBER (7, 2)); ; i ‘After the execution of this command the following message will be displayed: Table created. > Definition UNIQUE KEY CONSTRAINT at Table level ‘Annumber of columns ina single table can be defined as UNIQUE we can even havea composite UNIQUE key. UNIQUE key cannot be of LONG or LONG RAW datatype. Syntax: CREATE TABLE table_name (column_namel datatype (size), column_name2 datatype (size) UNIQUE (column namel, column_name2)); NOTE: 1. Simple UNIQUE KEY can be defined at column level or at table level. 2. Composite UNIQUE KEY has to be defined at table level only. 3. Composite UNIQUE KEY can be of 16 columns only, Q. What is NULL value? It isnot al it il ies i Ifthe date possible to have data available forall the entries in a cohumn i ues, the table not to have duplicate values, then RANT can be applied to that column. UNIQUE ‘cused with CREATE TABLE or ALTER TABLE {column level or at TABLE level, It can potato check for aNULL values |. SELECT * FROM Student WHERE: NAME IS NUL 2. SELECT * FROM Student WHERE NAME Is NOT L; = 23_BS« 4. NOTNUL By defaul column to to the colu NOT NUI Syntax: CREATE1 (column_n (size)); Example: SQL>CRE (EMP_CO! NUMBER( After the ex Table crea NOTE: N( 5. CHECKC( A check co; that must be and can be constraint is column depe column level Check cons SQL>CREA’ (EMP_Cop) VARCHAR, (7,2) CHECK After the ex: displayed: Table createc 1. Check constr entered starts 2. Check constra is in upper cas 3. Check constra 1S greater thanten, LE rel, be can jor te), ely nn. LL mn ed. ors 23 BSc. Sem. NOTNULL CONSTRAINT “ 4 BScGura y default, a column can hold NULL val w Sean EE ENUL alias pare einpENCUR MUS to the column. This can be applied at colume level NOT NULL constraint at column level Syntax: CREATE TABLE table-name (column_namel datatype (size) NOT NULL, column_name? datatype (size); Example: SQL>CREATE TABLE Employee (EMP_CODE CHAR (5) NOTNULL, NAME VARCHAR (20), SALARY NUMBER(7, 2)); Afier the execution of this command the following message will displayed: Table created. NOTE : NOT NULL constraint is not applied at table level. CHECK CONSTRAINT A check constraint is an integrity constraint. It specifies a requirement that must be met by each row ina database table. The constraint is predicate and can be applied to a single column or multiple columns. If a check constraint is specified for a column it allows only certain values for that column depending on the condition. A check constraint can be defined at column level or table level. Check constraint at column level SQL>CREATE TABLE Employee (EMP_CODE CHAR(S) CHECK (EMP_CODE like “E%"), NAME VARCHAR(20): |CHECK (NAME=UPPER(NAME)), SALARY NUMBER (7,2) CHECK (SALARY>10000)); After the execution of this command the following message will be displayed: Table created, + Check constraint for the first column EMP_CODE checks whether code entered starts with E. Check constraint for the second column checks whether the NAME entered is in upper case or not. Check constraint for the third column checks whether the salary entered 18 greater than 10000 or not.Lo, : Data willbe entered only fhe condition is satisfied or others TE " anerror message Will be displayed ;xample: oye . SOL INSERT INTO EMPLOYEE (EMP_CODE, NAME, SALARY) VALUES ('C123°, “TARA’, 15000); ener ‘This INSERT statement will cause an error and record will not be inserteg in the table as EMP_CODE does not start with E. > Check constraint at table level SQL>CREATE TABLE Employee on ‘(CODE CHAR (5), NAME VARCHAR (20), SALARY NUMBER (7, 2), GHECK (EMP_CODE like ‘E%’), CHECK (NAME UPPER(NAME), CHECK (SALARY>10000));, ‘After the execution of this command the following message will displayed Table created. > Specifying Name for the constraint ‘Naming constraints is a good practice. If a proper name is given to a ‘constraint it becomes easy to identify and manage the constraints. There are two advantages of naming a constraint. 1, Errors can be easily identified and fixed. 2. Modification and dropping constraint becomes easy. ‘An ideal constraint may tell us about the table on which we are working with and the table of constraint. i oe ; me tne corel that the constraint is a primary constraint and works Example: SQL>CREATE TABLE EMPLOYER (EMP_CODECHAR (6) CONSTRAINTPK_EMPPRIMARY KEY, NAME VARCHAR 20) CONSTRAINTN_NULLNOTNULL, SALARYNUMBER oa) CONSTRAINT. EMP CHECK (SALARY>10000)); displayed. OF this command the following message will be Table created. 1. DESCtable name; This command wil ll show t NULL constraints, he structure ofthe table along with the NOT 26, a BScGuru Tf we want to ser key constraint v stored in the US This table has t! _ OWNER: This |. CONSTRAINI constraint for e: CONSTRAIN1 P- Represents R— Represents U- Represents C—Check Con: . SEARCH_CO! check constrair . R_OWNER: T constraint. R_CONSTRA} foreign key con Example: If we want the give the follow! SELECT OWN FROMUSER, OWNER C DBA_WIPRO- S_WIPRO Adding integ Aftera table is command. The Example: ALTER TABLE ALTER TABL (Emp_code) Mi - ALTER TABLE (columnl, colu » ALTER TABL CHECK(Conditar 28 BScGuru_ 2, Ifwe want to see the other constraints like primary key constraint, for key constraint unique constraint and check constraint this informationa stored in the USER CONSTRAINT TABLE, | This table has the following columns _ OWNER: This column tells us about the owner of the column, CONSTRAINT NAME: This column tells us about the name of the constraint for example pk_emp. CONSTRAINT TYPE: This column tells us about the type of constraint. a. P- Represents primary key constraint 3). R - Represents foreign key constraint U- Represents unique constraint (C—Check Constraint SEARCH_CONDITION: It will show the condition associated with the | check constraint. I R_OWNER: The owner of the table is referenced by the FOREIGN key oa constraint. R_CONSTRAINT_NAME: The name of the constraint is referenced by | foreign key constraint. I Example: | If we want the constraints to be applied to the Employee table, we will ing sive the following command. SELECT OWNER, CONSTRAINT. NAME, CONSTRAINT_TYPE tks FROMUSER_CONSTRAINTS where TABLE_NAME=” Employee”; | OWNER CONSTRAINT_NAME CONSTRAINT_TYPE woo 5 ha DBA_WIPRO pk_Emp G ER S_WIPRO ck_Emp G I Adding integrity constraints be After table is created constraints can be added using the ALTER TABLE command. The constraint will be added to the columns of the table. Example: ALTER TABLE Student ADD PRIMARY_KEY (ROLL_NO); tints ALTER TABLE Employee ADD Constraint pk_Emp PRIMARY KEY two (Emp_code) MODIFY (NAME NOT NULL); ALTER TABLE table_name ADD CONSTRAINT U_constraint UNIQUE (columni, column2); ALTER TABLE table_name ADD CONSTRAINT my_constraint CHECK(Condition); —~ re oT Shrikeupa bea | Sree eeteomerana cm emanates ST | |int roping, Integrity a froma tableand ALTER TABLE cay, AC ;ONSTRAINT can be eee ae we want to drop the check constraint ck_emp fin taammoyee tuple, The command used is ALTER TAB = aerator the primary Ky fam employee ALTER TABLE employee DROPPRIMARY KEY; Write a SQL query to create a table “Sales_details” Field_Name Dtatype Se Sid varchar? 8 Pid varchar? 8 P_name varchar2 IS Price number 10 Oy number 8 1. Drop foreign key constraint on column p_no in table sales_details. 2. Add foreign key constraint on column sale_no in table sales details. }3. Modify the column qty to include not null constraint, 4. Insert 10 records insales_details, §: Display p_id and total of quantity ty for each product, 6. Display p_id and total ofprice for all the products, MORE ON SELECT Statement Operations using SELECT Statement: Selecting distinct Rows from a table Consider the table Srmo Student Name City 1 Radha Nagpur Bs Reshma Amravati 3. Kishor Mumbai 4. Kanchan Mumbai 5. Smita Pune SuPPose weare interested in thenames ofthe cites from which th ¢ e tl le students comayicr Wthout the duplication ofthe city names we give the following ma SQL> SELECT DISTINCT Crry FROM STUD CITY: v v _— - Preface Book & & Arithmetic’ Consider the income of the SQL> SELEC NAME SACHIN SURESH HARSHA Here the salar along with nai - Consider the obtained by tt SQL> SELEC SROLL | 101 78 3 i Using Colun names in displayed in the table. So while - SELECTNAN OUTPUT: NAME c en ROHITnts | ng v S BScGuru_ ms Samm, OUTPUT ciry AMRAVATI MUMBAI NAGPUR PUNE ‘The city MUMBAI will not be repeated twice in the output although it occurs twice in the table as DISTINCT word is used in the query. ‘Arithmetic operations on table data: Consider the employee table. Suppose we are interested in the Annual income of the employees we give the following command. SQL> SELECT NAME, SALARY*12 FROM EMPLOYEE; NAME SALARY*12 SACHIN 600000 SURESH 300000 HARSHA 420000 Here the salary from salary column will be multiplied by 12 & the result along with names will be displayed. . Consider the marks table. Suppose we are interested in the total marks obtained by the students. SQL> SELECT S_ROLL,PHY+MTH+COMP_SCIFROM STUDENT; S.ROLL PHY+MTH+COMP_SCI 101 212 B 201 3 246 Using Column Alias Name using AS clause ‘The names in a table are option short forms & may not be suitable to be displayed in the output. For example, the Column name DOB in the employee table. So while displaying it Alias name Date of Birth can be given. - SELECTNAME, DOB AS “DATE OF BIRTH” FROM employee; ourpur: NAME —_DATEOF BIRTH RADHA, 25-MAY-1990 ROHIT 2-OCT-1986 Shrikrupa‘AMRAVATI MUMBAI NAGPUR PUNE The city MUMBAI will not be repeated twice in the occurs twice in the table as DISTINCT word is used Arithmetic operations on table data: Consider the employee table. Suppose we are interested in the Annual income of the employees we give the following command. SQL> SELECT NAME, SALARY*12 FROMEMPLOYEE; output although it in the query. NAME SALARY*12 SACHIN 600000 SURESH 300000 HARSHA, 420000 Here the salary from salary column will be multiplied by 12 & the result along with names will be displayed. Consider the marks table. Suppose we are interested in the total marks obtained by the students. SQL> SELECT $_ROLL,PHY+MTH+COMP_SCIFROM STUDENT; S.ROLL PHY+MTH+COMP_SCI 101 212 78 201 3 246 Using Column Alias Name using AS clause ‘The names in a table are option short forms & may not be suitable to displayed in the output. For example, the Column name DOB in the employee table. So while displaying it Alias name Date of Birth can be given. . SELECT NAME, DOB AS “DATE OF BIRTH” FROM employee; oUurrur: NAME, DATE OF BIRTH RADHA 25-MAY-1990 ROHIT 2-OCT-1986Preface Book & ¢, CIAS “Total Marks” FRO 29__BSe6 Bsc SQL> SEL! YUTPUT: COMP_SC! eae ROLL_NO Roll_No Total Marks —— : 310 I mt 210 a Ww 180 ae oe we * ‘one subject, f relatis itors on table data using Ye have already seen the use of relational operator a See The relational operators are used in the select statement 3, NOT Oper: condition is ‘using the where clause. le > Logical Operations in SQL : ' ae The logical operators that can be used in SQL queries are ee acy SQL> SELE : NOT ROLL_NO 1, AND Operators: If we want two or more conditions in an SQL statement 02 tobe true then the logical operator AND should be used. The statements in ‘which the operator AND can be used are SELECT, INSERT, UPDATEo! > OTHER Si DELETE. Let us consider the table employee in which we want to get the list of employees getting salary in between 20000 & 40000. Eee ae SYNTAX: SQL>SELECT * FROM Employee WHERE(SALARY>20000 AND ste == Asa result, all the rows in which both the conditions are satisfied will be displayed. EXAMPLE 2. OR Operator: In an SQL query if weare checking two or more conditions. !- SELECT * FE & we want the where clause to be fulfilled even if one of the conditions is. _ 40000; true then OR operator can be used, OR operator can be used with the 2 SELECT * Fy select, insert, update or delete command, 3. SELECT * FR Example AND 40000, Before the execution of the query the table has the following data * SELECT +FR SQL> SELECT* FROM MARKS; . ROLL.NO PHY = MTH COMP Sct 2. IN OPERAT | Th T_T compare a col 101 45 67 89 the values in t 102 32 33 23 ‘multiple OR st I 103 56 3 56 : ® 16 90 91 SQL> SELEC Demeeeeeeeee Bites1) Be SELECT * FROM MARKS WHE oe. fom > ‘S WHERE (PHY>=75 - SoMP_SCP=75); ORMTH>~750R ROLL_NO PHY MIH COMP_scT | 101 6 a 89 B %6 90 1 If we want to know whether a student has scored distinction in at least cone subject, the above statement is used. it | 3, NOT Operator: If we ae interested in rows from a table where a particular condition is not satisfied then the NOT operator is used. Example If we want the roll numbers of all the students who have failed in PHY then the following query can be used SQL> SELECT ROLL_NOFROM MARKS WHERE NOT(PHY>=35); ROLL_NO xt in 102 > OTHER SQL OPERATORS e 1, BETWEEN: The BETWEEN operator is used to select value within a range. The values may be numbers, text or dates. D SYNTAX: SELECT COLUMN_NAME FROM Table where Column_Name be BETWEEN Valuel and Value2; EXAMPLE ns |_|. SELECT*FROM Employee WHERE SALARY BETWEEN 20000 AND i 40000; is \ < he | 2. SELECT *FROM Employee WHERE NAME BETWEEN °C ee 3, SELECT * FROM Employee WHERE SALARY: ‘NOT BETWEEN 2 ‘AND 40000; ae , | 4: SELECT*FROM Employee WHERENAMENOT BETWEEN °C AND NY 2. IN OPERATOR: If lists of values are given to us and we are ae ot Compare a column name with the lis. Ifthe column name malehe™ the values in the list, the record is displayed. This statement 'S ‘Multiple OR statement. EXAMPLE: SQL> SELECT * FROM EMPLOYEE; ShrikrupeSALARY al BScGurn NAMI e101 SACHIN 50000 ‘willbe displayed. F102 SURESH 25000 {SELECT NAME. DE fi anda’; F103 ABCDEFGHT 35000 NAMI SQL-SELECT EMP. CODE, NAME, SALARY FROM Employee itm, ee Oo one ch IN Rade Min act sar = sae DUAL table is a st E101 sry X in that call. E1ol SACHIN, 50000, eerste 3. NOTIN Predicate: NOT IN Predicate will give us exactly the oppesi: This table helps us result than IN Predicate, en SQL>SELECT 5*1 SQL>SELECT emp_code, NAME, SALARY FROM employee wher: “sp NAME NOTIN Radha’, ‘Milind’, ‘Dipak’); Ifthe Name is notin the list, the record will be displayed. 50 EMPC NAME SALARY The result will be £ en amas DUAL works as a E101 SACHIN 50000 > Example 2: E102 SURESH 25000 SQL>SELECTSY! E103 ABCDEFGHI 35000 SYSDATE 4. LIKE OPERATOR: Use of wild cards are allowed inSQL command. 33 ppm, wild card is substitute for any other character in a string, There are two _, ~ E16 types of wild cards, ‘> Example 3: 1. %acts as a substitute for 0 or more characters, SQL>SELECTUS 2. _acts as a substitute for a single character. ad 3. LIKE operator allows us to match a string value with another stringy value and displays it if they are similar or alike Eg, In short it allows, SCOT us to search a specified pattern in a column, © Example 4: SYNTAX: SQL>SELECT*F SELECT Column_name!,Column_name2——FROM TABLE WHERE Column_Name LIKE pattern; a EXAMPLE: x UPDATE: I. SELECTNAME; ADDRESS FROM STUDENT where NAME LIKE‘C%' All those entries which start with C and are of any length trom the NAME . uPPOse we have a column will be displayed, We want to make ¢| e II. SELECT NAME, ADDRESS FROM STUDENT where ADDRESS ae Lapa LIKE‘%LAYOUT’; Clause (where clausdosite where Alrthe address in the ADDR rete will be displayed: “T NAME,ADDRESS FROM STUDENT where NAME LIKE Names from NAME column like Nanda, Manda will be displayed, «tells ts that only one character ean be placed before anda, . > THE DUAL TABLE: DUAL table is a small work table of one row and one column having an entry X in that cell Itcan be used as a dummy table. It is a table owned by & is present by default. This table helps us to use the SELECT statement to work as a calculator = Example 1: ‘SQL>SELECT 5*10 FROM DUAL; 510 50 The result will be 50. DUAL works as a dummy table name for the above select Command. = Example 2: SQL>SELECT SYSDATE FROMDUAL; SYSDATE 25-FEB-16 © Example3: SQL>SELECT USER FROM DUAL; USER Scorr © Example 4: SQL>SELECT + FROM DUAL; D x UPDATE: Suppose we have a table with records already inserted in the table & now ‘We Want to make changes to the data in one record or row then UPDATE stmand is used. If we want to make changes to a single record then the yword UPDATE, SELECT should be used together along with the where Glause (where clause is essential otherwise all the records will be updated). ShrikrupePreface Book & c, ‘SYNTAX: UPDATE tble_name SE homnt=valuel, cokumn2—vale2... Where condition; Example 1: ‘Change the name Radha SQL>UPDATESTUDENT . ‘SET NAME='Sita’ WHERE NAME~ Radha’; Z : ‘Changes will be made to only those rows where NAME="Radha Note: If we omit the where clause in the above statement then all the entries in the column NAME will be changed to Sita. Example 2: If the organization has decided to give a employee by 1000 Rs SQL>UPDATE Employee SETSALAR} SALARY +1000; Changes can be made simultaneously to more than one column to a record inatable. Example 3: Suppose a student’s ROLL_NO and ADDRESS has changed then the following query can be used. SQL>UPDATE Employee SETROLL_NO="129”, ADDRESS WHERE NAME="Mahesh’; > DELETING DATAFROMA TABLE: At times it becomes necessary to delete a record from a table then DELETE command along with the WHERE clause is used. If we do not use the ‘where clause, then all the records from the table will be deleted. However, the structure of the table will be preserved. SYNTAX: SQL>DELETE FROM Table_name WHERE Condition; EXAMPLE: Asstudent from a class has cancelled his admission then we will have to delete the record, SQL>DELETE FROM STUDENT WHERE NAME="Mahesh’; Here only one record is deleted because WHERE CLAUSE is used. If we drop the WHERE CLAUSE thenall the records from the STUDENT table to Sita in the table Student. \crement to all its '='Gandhi Nagar” ls ce Fae deleted, only the equivalent tothe TRU SYNTAX: ‘TRUNCATE table table > WORKING WITH “Asequence is a feature reduces the work of t igenerates a Sequence ¢ fscending order or des the given interval are beginning. This is kn: 'A sequence can be © ‘Sequences can be use SYNTAX: (CREATE SEQUENC Start with initial_valu increment by increm¢ ‘maxvalue maximum_ cycle/no cycle; CREATE SEQUEN( ‘Sequence_Name is t Initial_value is the st Increment_value is t if the sequence is in . Maxvalue is the val . Cycle specifies that have reached the me Recycle specifies th EXAMPLE1: SQL>CREATE SEC Start with 1 Increment by 1 Maxvalue 100 Cycle; After the execution Sequence create Here sequence will then again start wil an3 ___BScGara. Fhe deleted. only the structure of the table will remain Wfauivalent tothe TRUNCATE Command SYNTAX: TRUNCATE tabletable_ name; >» WORKING WITH SEQUENCES, 4 sequence isa feature in SQL to proxtuce unique values on demand. ‘This qaduces the work of the user. IC can be defined as a bound object that penerates a soquence of numeric as pet specifications. ft may be in [scending order or descending onder in a given interval. Afler the values in she given interval are exhausted if necessary we can again start from the This is known as recycling. yuence can be created using the CREATE SEQUENCE keyword. ences can be used to automatically generate primary key values. SYNTAX: CREATE SEQUENCE Sequence_Name Star with initial_value increment by increment_value maxvelve maximum_value gyclemno cycle; CREATE SEQUENCE is a keyword. Sequence_Name is the name of the sequence. Initial_value is the starting value of the sequence. Increment_value is the value with which the sequence can be incremented if the sequence is in ascending order. | Maxvalue is the value until which sequence will be incremented by itself. 6. Cycle specifies that the values should start from the beginning after they have reached the maximum value. Be 7. Recycle specifies that the values should not start from the beginning, wer, EXAMPLEL: SQL-CREATE SEQUENCE $1 ‘Stan with 1 Increment by 1 Maxvalue 100 han | Cycle; ve “oat After the execution ofthis command the following message will display | Sequence created. fwe | Hete sequence will start with 1, will be incremented by 1 upto 100 and able | “HeNagain start with | EA mana aerate eT ShrikeupoPreface Book & ¢, oa a ne EXAMPLE: EATESEQUENCE S2 i. quent create C_maser with field's ¢_no, name, adress state and pin cones Field Name Datatype Size Co surchar? wo Name varchar? wo Sate varchar? 2» ay surchar? 20 Pin code umber 10 - Create sequence which will generate number from 1.999 in ascendin: ‘order with anintervalof land in cyclic order Iasert reconis. > WORKING WITH SYNONYMS A synonym is an alterative name given to an object. The objects may be 2 table, a view, a sequence ora stored procedure, ‘Synonyms are used when an access is granted to an object from another schema. Ifa synonym is given, the user need not prefix the table name with schema name. (A schema isa collection of database abject. The objects may be tables Jn other words, schema means the structure fora database), EXAMPLE: (CREATE PUBLIC SYNONYM Suppliers for app suppliers; 1. app is the schema name. ees Tt se. sam fable name present nthe Schema app. SYNONYM we can drop out the Schema name app it 1p Suppliers with Supplies, if we want 10 se all the record fom the his present in the app schema & if we have not ‘would be T, UPDATE or DELETE ean work on Suppliers 1ade to app Suppliers. ARITHMATIC FUNCTIONS, DATEFUNCTIONS CHARACTER FUNCTIONS arithmetic function's a function which ased on inputs called arguments and 2. AGGREGATE FUNCTIONS: > SINGLE ROW FUNCTIONS 1) MOD FUNCTION: tis necessary to pass two arguments to this function. ‘The first argument is divided by the second argument and the remainder is ‘returned as a result. f the second argument is O(zero)then the result will be the same as the first number. SYNTAX: MOD(m,n) EXAMPLE I: ‘SQL> SELECTMOD@0,7) FROM DUAL; ‘RESULT: ‘MOD(20,7) 6 FE> as Preface Book fc, EXAMPLE2: i SQL> SELECT MOD(0,7)*REMI" MOD(IS4)"REM2"FROM DUA, RESULT: REMI REM? 6 3 2) TRUNCFUNCTION: It is necessary to pass one of two arguments to this Function. The first argument is a number and second argument gives us the numberof digits afer the decimal point "TRUNC (number, decimal places) ‘The second argument is Optional EXAMPLE 1: ‘SQL> SELECT TRUNC(235.817,2)FROMDUAL; RESULT: ‘TRUNOQ35.817.2) 23581 EXAMPLE2: ‘SQL> SELECT TRUNC(235.817,2) “T1", TRUNC(75.73,1) DUAL; RESULT: 1 72 23581 75.7 EXAMPLE3: SQL> SELECT TRUNC(235,-2) FROM DUAL; RESULT: TRUNCQ35,2) 20 EXAMPLES: SOL>SELECT TRUNC(235 417) FROM DUAL; RESUS (235817) DS4I7 3 Bscaere = 5 isnot specified, the digits ater decimal places wil tetrueated 100 i$ FUNCTION: 3) AB function Will find th absolute value ofthe number passed as argument SYNTAX: ABS) [EXAMPLE 1: ‘SQL> SELECT ABS(-1736) FROM DUAL; RESULT: ‘ABSCI7:36) 1736 EXAMPLE2: SQL> SELECT ABS(-1736)"ABSI"ABS(1736)“ABSZ"FROMDUAL; RESULT: ABSI 17361736 4) CEILFUNCTION: ‘This fimetion will round upto the decimal value passed to it upwards 10 thenext upper integer value. The value passed may be positive or nepatve, ‘SYNTAX:CEIL(n) EXAMPLE 1: ‘SQL> SELECT CEIL(24.8) FROM DUAL; RESULT: CEILQ4.8) 3 EXAMPLE2: SQL> SELECT CEIL(-24.8) FROM DUAL; RESULT CEILY-24.8) w ‘ABS? shrikrupa \)——<—<———_—__ Sa a8 Preface Book & ¢, EXAMPLES: SQL> SELECT CEIL(24.8)"C1", CEIL(-24.8) FROM DUAL; RESULT: Cl CEILG-248) 22 5) FLOORFUNCTION: ‘This function will round up the decimal value passed to it down to the next least integer value. The number may be positive or negative. SYNTAX: FLOOR(®) EXAMPLE: ‘SQL> SELECT
[email protected]
) FROMDUAL: RESULT: FLOORG78) 2 EXAMPLE2: ‘SQL> SELECT FLOOR(-27.8) FROM DUAL; RESULT: FLOOR(-27.8) 28 EXAMPLE3: SQL> SELECT FLOOR (24.8)"F1",FLOOR(27.8)"F2” FROMDUAL; sol’ RESULT: EXPO) 73990561 +7) POWER FUNCTION: ‘When two numbers are passed as arguments. The first number raised to the second number will be calculated EXAMPLE: SQL> SELECT POWER(2,3) FROMDUAL; RESULT: POWER(2,3) & 8) SQRT FUNCTION: “his function will return square root of a number passed to it as an argument. SYNTAX:SORT(n) EXAMPLE: SQL> SELECTSQRT(9) FROMDUALs RESULT: soRT) 3 TT emeiteupa— so Preface Book ac, > AGGRE EXAMPLES OF AGGREGATE FUNCTIONS: 1) COUNTFUNCTION: ‘This function is used to count the number of rows of entries from column ina database table. | ‘SYNTAX: COUNT [(*) DISTINCTIALL] ColumnName; EXAMPLE I: ‘SQL>SELECT COUNT (*) FROMSTUDENT; ourPur: Tt counts all the rows from a database table regardless of NULL, COUNT) ‘Counts only the distinct rows. | EXAMPLE2: | SQL>SELECTCOUNT(DISTINCTCITY)FROMSTUDENT; | ourrur: | ‘Counts only the distinct rows. COUNTDDISTINCTCITY) iB ‘Counts all the cities. | ‘NOTE: The keyword ALL need not be mentioned. By default, ALL opton| is selected. 2) MAX FUNCTION: This function will find the maximum value from column for @ group of rows. | SYNTAX: ‘MAX [DISTINCT] Column_Name; IEDISTINCT is not mentioned by default all the record fr that colune are considered. EXAMPLE 1: SQL> SELECT MAX(PERCENTAGE) FROMSTUDENT; ‘se. sam v EXAMPLE EbL> SELECT MIN(PERCENTAGE) FROM STUDENT, OUrFUT: MIN(PERCENTAGE) pAX: ‘SUM (DISTINCT/ALL] Column Name EXAMPLE: ‘SQL> SELECTSUM (SALARY) FROMEMPLOYEE: wil find the sum ofall the salaries ofthe SALARY column fromthe EMPLOYEE table. AVGFUNCTION: ‘This function retums the average ofthe values ina given mumeic col. SYNTAX: AVG [DISTINCT/ALL] Column Name EXAMPLE 1: SQL> SELECT AVG (PERCENTAGE) FROM STUDENT: | ourrur | AVGPERCENTAGE) 88.12 Sheikeups rr TTSOL SELECT AVGISALARY) PROM EMPLOY our AVGSALARY Fon CLAUSES USED WITH AGGREGATE FUNCTIONS: ) MAVING CLAUSE: Having clause enables us to speci conditions thy Sites grou rest SYNTAX: dite oe st etaee of aparicar ified date on aoreB16 ORDER BY Column! Coburm, ality of weekday are controlled by the NLS_DATE, LANGUAGE option EXAMPLE: ‘SELECT ROLLNO, COUNT(ROLLNO) 3) LAST_DAY: FROM Student DAY funtion returns the ast date of the month specified with GROUPBYROLLNO HAVING COUNT ROLLNOP?2; > DATE FUNCTIONS : EXAMPLE: There ae cerain functions which can work on dates. ‘SQL>SELECTLAST_DAY (27-JAN-I6})"LASTDAY” FROMDUAL, 1) ADD_MONTHS: This function adds number of months to a date and! utpuT, ives & new date : LasTDAY SYNTAX: ‘ADD_MONTHS (date) SOIAN-IG EXAMPLE I: BETWEEN: SQL>SELECT ADD_MONTHS (SYSDATE,6) FROMDUAL; Renee een eee This command will add 6 months o the System dat. . una 2) E cai Kacecrt BETWEEN tel date2) £ EXAMPLE: = 1-AUG-I6 | SOL>SELECTMONTHS_BETWEEN(02-FEB-16,7-DEC-16)FROM e ‘DUAL; Wl EXAMPLE2: ‘SQL>SELECT ADD_ MONTHS (SYSDATE,-6) FROM DUAL; ‘This command will subtract 6 months from the SYSDATE.BSc. sem SYNTAX: | ROUND (date Format) | ‘There are two parameters | 1. Date: This i the date tobe removed 2. Format: Ths parameter is optional. used can have the following for. | Below are the valid format parameters ovreur: aa cae paraorete | rvevkag ae ere ore SV YVYIVEAR, | Rounds upon uly * Tis SYEAR,YYY,Y¥,¥ Wy EST: yvNt __{___| 5) GREATES @ Rounds upon he 1 ‘This function retus greatest date from lst of dates. Enea ee ‘SYNTAX: - | the quarter_ (GREATEST (date. date2 date’ —) Le) MONTH MON, MM, Rounds up onthe 1% da} a a RM of the month | SQL>SELECT GREATEST (TO_DATE ((2-FEB-16"), TO_DATE (3. “Week wet) ANI), TO_DATE (S-MAR-I5))) FROM DUAL = | iw ame week a ovrevr A the Fit dy of 180 | 2-FEBG year EXAMPLE | aw v Sone ty oe waa EA CTLEASTTO pATECW2HEIG)TO DATECSEC| | te Festdy often 16)) “LEAST” FROM DUAL: ) Dy DDD, DD. oureur | [Hour HEL HH12, HH24 LEAST | [7 Start day of the | DAY,DY,D | _week feed = 6) ROUND: je it ee oe ee) ‘The oracle ROUND function retums a date rounded toa specific unit of] EXAMPLE 1: measure. | SQL> SELECT ROUND (TO_DATE('22-AUG-03)),YEAR')) FROM DUAL; oureur ROUND(TO_ OL-JAN-04 EXAMPLE2: SQL>SELECT ROUND(TO_DATE(“16-SEP-2015"), MONTH "New ‘Month from dual; _ 01-0cr2015eo ae Rrefans Book toy | >» CHARFUNCTIONS: xe fe, [A character function sa fine ‘numbers as parameters and ret 1. LOWER This fuetion is used SYNTAX: LOWER (String) Example: SQL> SELECT LOWER (HELLO WO! DUAL: ourruT: LOWER CASE bello world 2. UPPER function is used to convert all characters of strings to upper case, v Example: SQL> SELECT UPPER( hello world’) AS upper_case FROM DUAL; OUTPUT: UPPER_CASE HELLO WORLD 3. TRIM: ‘This function removes Jeading & trailing spaces from a character ring) | Syntax: TRIM ([ (LEADING [TRAILING/BOT) FROM] target_string [COLLATE collation_name]); Examplel: SQL> SELECT TRIM(LEADING ‘‘ FROM * MAY’) DUAL; OUTPUT: LTRIM MAY Note : Only the leading spaces will be removed. ‘example 4: sQl> SELECT Th FROMDUAL; ourrur: 11RIM yal_char] | )ASLTRIMFROM | RIM(LEADING “1° FROM 1234567) AS L_TRIM 234361 a sequence of characters in a string with another -The function replaces a single character a a Sime 5 sal 'ASTRANSLATE” FROMEMPLOYEE: ‘TRANSLATE 0) be transated 10 GAS" me entry ina columns different it will sheikrupa‘These are conversions that takes place autor Example: 1. A VARCHAR? or CHAR valve canbe implicitly converted to NUMBER DATE. 2. A NUMBER OR DATE type value can be automatically converted ig Explct Conversion Pu Eapate of ype ening colina iS Chiat To NoMBERensTO.DATE 1. TOCHAR: Pose ecerly or in ble sng standart ste format DD NINMEYE Tne van to Suply the dati ae Weis Geathe TO. CHAR hon ws Sharer before deploying if we want toe following conan | SQLOSELECTROLL NO,NAME,DOBFROMSTUDENT, | NAME pos XYZ 25-Sep-1994 | PQR ‘17-May-1990 nC 20-Apr-2002 Example 1: ‘if we want to display the dates as 20*-Apr-2002. It can be done in the | ' following way. ‘SQL>SELECT ROLL, NONAME,TO_CHAR(DOB,DDTH-MON-YY) “DATE’ FROM Student; _ I Bs a 1STH-AUG-87 IND-APR86 ary 10 display the date in the form twenty-five or -t ROLL_NO, NAME TO_CHAR (DOB,DDSP’) FROM NAME=ABC’s ing with th atached to it. as Nineteenth DDSPTH _ NO, NAME, TO_CHAR (DOB, DDSPTH) FROM {AME="ABC’; NAME ‘TO_CHAR ABC ‘TWENTY-SECOND Conversion of Numeric Value into Character: ‘TO_CHAR function will convert numeric value into necessary to insert special symbols like S, into numbers for his conversion function can be used. : TO_CHAR (number, {format}; EXAMPLE SQL> SELECT NAME,TO_CHAR(B_ID;99999) FROMBROKER: BLNAME ‘TO_CHAR Copp 101.00 uM 102.00 TOM 103.00
You might also like
OracleSQL Infosys
PDF
No ratings yet
OracleSQL Infosys
43 pages
01 - SQL - Oracle SQL Training Manual
PDF
No ratings yet
01 - SQL - Oracle SQL Training Manual
91 pages
Relational Database Management System (RDBMS) : Payroll
PDF
No ratings yet
Relational Database Management System (RDBMS) : Payroll
114 pages
SQL Itp2
PDF
No ratings yet
SQL Itp2
110 pages
Practical File SQL Queries DBMS
PDF
0% (1)
Practical File SQL Queries DBMS
30 pages
Practical DBMS
PDF
100% (2)
Practical DBMS
38 pages
Dbms SQL File
PDF
No ratings yet
Dbms SQL File
35 pages
AssignmentFile 882 06112023165954
PDF
No ratings yet
AssignmentFile 882 06112023165954
44 pages
Oracle 10g Lab Simple
PDF
No ratings yet
Oracle 10g Lab Simple
93 pages
2 - Review DDL and DML
PDF
No ratings yet
2 - Review DDL and DML
53 pages
Basic Introduction of Oracle and SQL - PLSQL
PDF
No ratings yet
Basic Introduction of Oracle and SQL - PLSQL
395 pages
DBA Chapter 5
PDF
No ratings yet
DBA Chapter 5
21 pages
Oracle SQL Training Document
PDF
No ratings yet
Oracle SQL Training Document
91 pages
Creating and Modifying Database Tables
PDF
No ratings yet
Creating and Modifying Database Tables
71 pages
A Program Lab Report On: Bachelor of Computer Applications
PDF
No ratings yet
A Program Lab Report On: Bachelor of Computer Applications
21 pages
Introduction To SQL
PDF
No ratings yet
Introduction To SQL
13 pages
PLSQL Notes Modified
PDF
No ratings yet
PLSQL Notes Modified
124 pages
Good Afternoon To Everyone
PDF
No ratings yet
Good Afternoon To Everyone
4 pages
5.UNIT 5
PDF
No ratings yet
5.UNIT 5
24 pages
Structured Query Language SQL: Htet Mon Win Banking Division ACE Data Systems
PDF
No ratings yet
Structured Query Language SQL: Htet Mon Win Banking Division ACE Data Systems
37 pages
DBMSUNIT-3
PDF
No ratings yet
DBMSUNIT-3
26 pages
SQL Notes 1
PDF
No ratings yet
SQL Notes 1
101 pages
SQL Tutorial PDF
PDF
100% (1)
SQL Tutorial PDF
43 pages
SQL Narayana Reddy
PDF
100% (1)
SQL Narayana Reddy
124 pages
Database Development (Basic)
PDF
No ratings yet
Database Development (Basic)
5 pages
SQL 1
PDF
No ratings yet
SQL 1
108 pages
Structured Query Language: Chandra S. Amaravadi
PDF
No ratings yet
Structured Query Language: Chandra S. Amaravadi
49 pages
Structured Query Language (SQL)
PDF
No ratings yet
Structured Query Language (SQL)
29 pages
DBMS - CH-9 - SQL Notes
PDF
No ratings yet
DBMS - CH-9 - SQL Notes
42 pages
Oracle SQL Concepts
PDF
No ratings yet
Oracle SQL Concepts
176 pages
SQL Notes
PDF
No ratings yet
SQL Notes
124 pages
DBMS
PDF
No ratings yet
DBMS
4 pages
DBMS
PDF
No ratings yet
DBMS
8 pages
SQL - Part-1
PDF
No ratings yet
SQL - Part-1
59 pages
DDM 1&2 (2)
PDF
No ratings yet
DDM 1&2 (2)
45 pages
SQL (Unit Iii)
PDF
No ratings yet
SQL (Unit Iii)
16 pages
Structured Query Language
PDF
No ratings yet
Structured Query Language
33 pages
DBMS Defintion, Objective and Applications: Database
PDF
No ratings yet
DBMS Defintion, Objective and Applications: Database
17 pages
APznzaZiPsTwfBlw353QMg_uf_Zd1p9O50XMgUm4xYNYm6L0QBXmyV4rxIbUhE2neqUrAdBPE6UalErCG43TzwKm3Hy6uzXTHU8vo5b6qkvfyH8WWNfCFce-3h_o0RRDlGwwAcU8CnHX608y22_-rEGzkmuVdi8uMKAp_4KpDtzk6oAPTYYy0yJtaUFOKfHAPt4JTHh8xtkeAnCULIBLEJDDnD-qLb3RB-dw
PDF
No ratings yet
APznzaZiPsTwfBlw353QMg_uf_Zd1p9O50XMgUm4xYNYm6L0QBXmyV4rxIbUhE2neqUrAdBPE6UalErCG43TzwKm3Hy6uzXTHU8vo5b6qkvfyH8WWNfCFce-3h_o0RRDlGwwAcU8CnHX608y22_-rEGzkmuVdi8uMKAp_4KpDtzk6oAPTYYy0yJtaUFOKfHAPt4JTHh8xtkeAnCULIBLEJDDnD-qLb3RB-dw
3 pages
CS8481 DBMS RECORD FINAL Modfied
PDF
No ratings yet
CS8481 DBMS RECORD FINAL Modfied
123 pages
DBDev 02 (4) 2
PDF
No ratings yet
DBDev 02 (4) 2
90 pages
SQL Structured Query Language
PDF
No ratings yet
SQL Structured Query Language
7 pages
PG_MCA_Computer Applications_315 24 - RDBMS LAB(1)
PDF
No ratings yet
PG_MCA_Computer Applications_315 24 - RDBMS LAB(1)
84 pages
Database Basic Knowledge Training: Integrated Product Dept
PDF
No ratings yet
Database Basic Knowledge Training: Integrated Product Dept
78 pages
Class10_ICT_P2U3_DBMS
PDF
No ratings yet
Class10_ICT_P2U3_DBMS
7 pages
DBMS Lab Manual
PDF
No ratings yet
DBMS Lab Manual
40 pages
Dbms Lab Manual
PDF
No ratings yet
Dbms Lab Manual
43 pages
What Is SQL? - SQL Introduction
PDF
No ratings yet
What Is SQL? - SQL Introduction
184 pages
Using DDL Statements
PDF
No ratings yet
Using DDL Statements
8 pages
Database
PDF
No ratings yet
Database
26 pages
Unit 2 - SQL and PLSQL
PDF
No ratings yet
Unit 2 - SQL and PLSQL
156 pages
Database Dbms Rdbms Entity Attribute
PDF
No ratings yet
Database Dbms Rdbms Entity Attribute
15 pages
SQL Interview Questions
PDF
No ratings yet
SQL Interview Questions
45 pages
Intro SQL
PDF
No ratings yet
Intro SQL
33 pages
Dbms Lab Material1
PDF
No ratings yet
Dbms Lab Material1
47 pages
dbms file
PDF
No ratings yet
dbms file
41 pages