0% found this document useful (0 votes)
20 views40 pages

Unit 2 DBMS

The document provides an overview of Oracle 9i, focusing on database concepts, including definitions of databases and Database Management Systems (DBMS), as well as the benefits and features of Relational Database Management Systems (RDBMS). It discusses Dr. E. F. Codd's 12 rules for RDBMS and compares DBMS with RDBMS, highlighting their differences. Additionally, it outlines features of Oracle 9i Release 2 and various software development tools associated with Oracle.

Uploaded by

Sushma Borkar
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
0% found this document useful (0 votes)
20 views40 pages

Unit 2 DBMS

The document provides an overview of Oracle 9i, focusing on database concepts, including definitions of databases and Database Management Systems (DBMS), as well as the benefits and features of Relational Database Management Systems (RDBMS). It discusses Dr. E. F. Codd's 12 rules for RDBMS and compares DBMS with RDBMS, highlighting their differences. Additionally, it outlines features of Oracle 9i Release 2 and various software development tools associated with Oracle.

Uploaded by

Sushma Borkar
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
You are on page 1/ 40
SECTION I: Setting Up Oracle 9i 1. DATABASE CONCEPTS WHAT IS DATABASE A database can be defined as a collection of coherent, meaningful data. The phrase collection of coherent data needs to have a point of reference to be understood. A simple point of reference would be the example of a postal address, this would gencrally contain: , A building name 4 AA flat number in the building (if itis co-op housing society rather than a bungalow) A road name . ss : An area name A state name A pincode A country name (This is optional, but necessary if the letter is destined to a foreign country) ooo0000 To project on this further, rnultiple addresses kept together in one place, such as an address book, could be termed as a coherent collection of data. Thus the address book is a database and the postal addresses in the book, is the data that fills the database. WHAT IS DATABASE MANAGEMENT SYSTEMS (DBMS) To be able to successfully design and maintain databases we have to do the following: é 1. Identify which part of the world’s data is of interest to us 2. Identify what specific objects in that part of the world’s data are of interest 3. Identify a relationship between the objects Hence, the objects, their attributes and the relationship between them (that are of interest to us) are stored in the database that is designed, built and populated with data for a specific purpose. Software houses took up the éhallerige of designing a system that would help in managing data in such a database. These systems were called Database Management Systems (DBMS). DBMS. is a system: that allows-inserting, updating, deleting and processing of data. Some of the DBMS developed by software houses’ were Oracle, Ingress, Sybase, ‘Dbase ‘3+, Foxbase, ‘Foxpro, MS Access, Datasease, Dataflex, Advanced Revelation, and so on. : Benefits of DBMS 1. “The amount of data redundancy in stored data can be reduced 2. No more datp inconsistencies 3. Stored data can be shared by a single or multiple users 4. Standards can be set und followed . . .5. Data integricy can be maintained. Data integrity refers to the probiem of ensuring that database contains only accurate data . . 6. Security of data can be simply implemented 7. Data independence can be achieved, Le. data and programs that manipulate the data are two d..ferent entities Scanned with CamScz 2 SQL, PLISQL: THE PROGRAMMING LANGUAGE OF ORACLE WHAT IS A RELATIONAL DATABASE MANAGEMENT SYSTEM (RDBMS) ‘A Relational Database Management System (RDBMS) is a database management system ome) aa ‘ based on the relational model as introduced by Dr. Edgar F. Codd, Strictly speaking it should also sali Code's 12 rules, but in practice there is no DBMS that satisfies all these rules, In fach, most suecesem DBMS that are considered to be relational volte the relational model in several important ways, inelueing the Structured Query Language (SQL). However, most database practitioners and researchers use the ter in a loose way such that most databases that support SQL are included, : Relational Database Management Systems (RDBMS) stores data in the form of related tables. ROBMS ae powerful because they require frwv assumptions apout how data is related or how it will be extracted the database. As a result, the same database’ can be viewed in many different ways. An important feature of relational systems is that a single database can be spread across several tables. This differs from flat-file databases, in which each database is self-contained in a single table. The first released RDBMS that was a relatively faithful implementation of the relational model was the Multics Relational Data Store first sold in 1978. Others have been Berkeley Ingres, QUEL and [BM BS12. Today. popular commercial RDBMS for large databases include Oracle, Microsoft SQL Server, Sybase SQL Server, and IBM's DB2. The most-commonly used free RDBMS are MySQL, PostgreSQL. Dr. E. F. Codd's Rules for RDBMS Dr. E. F. Codd is an IBM researcher who first developed the relational data model in 1970. Ia 1985; Dr. Codd published a list of 12 rules that define an ideal relational database and has provided a guideline for the design of all relational database systems. : Dr. Codd has used the term guideline because till date no commercial relational database system fully conforms to all 12 rules. For a few years, scorecards were kept that rated each commercial product's conformity to Codd's rules. Today, the rules are not talked about ag much but remain a goal for relational database design. Q Rule 1: The Information Rule - All data should be presenter! in table form a Rule 2: Guaranteed Access Rule - All data should be accessible without ambiguity. This can | “ accomplished through a combination of the table name, primary key, and column name G Rule 3: Systeniatie Treatment of Null Values - A field should be allowed to remain empty, «involves the support ofa null valve, which is distinct from an empty string or a number with a value of | * zero. Of course, this can't apply to primary keys. In addition, most database implementations support | : the concept of a not-nul! field constraint that prevents null values in a specific table column i Rule 4: Dynamic On-Line Catalog based on the Relational Model - A relational database must : provide access to its structure through the same tools that are used to access the data, Thi usually accomplished by storing the structure definition within special system tables Rate $: Comprehensive Daia Sublanguage Rule - The database must support at least one clearly defined language that includes functionality for dats definition, dats manipulation, data integrity, and database transaction control. All commercial relational databases use forms of standard SQL’ (ic Structured Query Language) as their supported comprehensive language r Rule 6: View Updating Rule - Data can be presented in different logical combinations called views, Each view should support ihe same full ange of data manipulation that has direct access to a tably available. n practi I views is difficult and is not fully Scanned with CamSce DATABASE CONCEPTS 4 GQ Rule 7: High-level Insert, Update, and Delete - Data can be retrieved from a relational database in sets constructed of data fom multiple rows and/or multiple tables, This rule states that insert, update, and delete operation: should be supported for any retrievable set rather than just for a single row in a single table a Rule 8: Physical Data Independence - The user is isolated from the physical method of storing ang retrieving information from the database. Changes can be made to the underlying architecture (hardware, disk s.orage methods) without affecting how the user accesses it a Rule 9: Logical Data Independence - How data is viewed should not be changed when the logical structure (table’s structure) of the database changes. This rule is particularly difficult to satisfy. Most databases rely on strong ties between the data viewed and the actual structure of the underlying tables Q Rule 10: Integrity Independence - The database language (like SQL) should support constraints on user input that maintain database integrity. This rule is not fully implemented by most major vendors, Ata minimum, all databases do preserve two constraints through SQL. No component of a primary key can have a null value. If a foreign key is defined in one table, any value in it must exist as a primary key in another table. Q Rele 11: Distribution Independence - A user should be totally unaware of whether or not the database is distriauted (whether parts of the database exist in multiple locations). A variety of reasons make this rule di:vicult to implement. . Q Rule 12: Non subversion Rule - There should be no way to modify the database structure other than through the multiple row database language (like SQL). Most databases today support administrative tools that allow some direct manipulation of the data structure. DBMS V/S RDBMS DBMS RDBMS [in DBMS relationship between two lables or files are|In RDBMS relationship between two tables or files can maintained programmatically be specified at the time of lable creation DBMS does nat support ClienUServer Architecture _ [Most of the RDBMS supports ClienUServer Architecture __JIBBMS does not support Distributed databases Most of the RDBMS supports Distributed databases -|Ir DBMS there is no security of data In RDBMS there are multiple levels of security 1. Logging in at OVS level 2. Command ievel (i.e. at RDBMS level) : : 3. Object level : Table Is given an extension ia DBMS Many tables are grouped in one database in RDBMS. BMS may satisfy less than 7 to 8 rules of Dr. E F|RDBMS usually satisfy more than 7 to 8 ru‘es of Dr. EF Codd Ls ‘ Naming Conventions DBMS : Column, Attributes Ro i RDBMS See Scanned with CamScz i dy to be implemented. There are other no, I] now in their 3rd normal form, and ready aa maha. Hayee tell normal form, and 4th normal form, but these are very rarely used for busi spplcations. In most cases, tables that are in their 3rd normal form are already conform to these type of table formats anyway, Circumstances under which Normalization can be avolded ‘There are situations when normalization can be avoided: This can be seen in the following table structure: Table: Customer Field Key {Customer number__| Primary Key. Customer name Address = Pincode City Going through all the fields reveals the following: Q No repzating groups exists O Aprimary key is defined Q There is orly one key so partial dependencies do not exists This proves that it is at least in 2nd normal forma Q There are transitive dependencies ~Teseemas that like City might be determined by Pincode, which is usually the case in most Parts of the - World, but there is no need to remove City, and place it in a separate table, with Pincode as the key, Axhough this table is not technically in its 3rd normal format, removing this information is not worta it ing more tables increases the load slightly, slowing Processing down. This is often counteracted by the seduction in tcble sizes, and redundant data. But in this case, where the City would almost always be 2 “Beferenced as part of the address, it isn't worth it, Normalization is just a helpful process that usually results Balthe mos efficient ble structure, and not a rule for database desi : “a ANTRODUCTION TO GRACLE 4 fay back in June 1970, Dr E. F. Codd Published a paper entitied A Relational Model of Data for Large “"Siiared Data Banks. This relational model, sponsored by IBM, then came to be accepted as the definitive mode! for RDBMS. The language developed by IBM to manipulate the data stored within Codd's model wig originally called Stractured English Query Language (SEQUEL) with the word English later being ed in favor Structured Query Language (SQL). . In 1979 2 company called Relational Sofware, Inc, released the first commercially available nation cf SQL, Relational Sofware later came to be known, as Oracle Corporation. Oracle one on 18 a company that produces the most widely used, Server based, Multi user RDBMS named This proves that it is at least in 1st normal form Scanned with CamScz 7 SQL, PUSQL: THE PROGRAMMING LANGUAGE oF ol , RACLE Features of Oracle 9] Release? (9.2) go. Very Large Memory Support - Oracles; (92) for Windows supports Very Lage ne (VLM) configurations in Windows “sown 5 000 and ; — aa aoe ha ens OHS ese 2662) =D Ying gone M h of RAM traditional Wind it is available on available to Windows applications, Specially, only in aa Windows XP Oracle9i release 2 (9.2) uses addi g tel Pentium Mand Extensions (AWE) built into Windows 2000 ——s ee Windows XP to access more than 4 GB of RAM, ——— a 4GB RAM Tuning (4GT) - Wi 5 ‘ Scie ma ¢ as na rea ae Entei and Datacenter Esitions (version 4,0) running on OracleDi Enterprise Edition to acess up to 3 GB of meme ese eplications GB in previous operating system versions. 4GT provides a tremendeus berehe so ne memory is available for database use, increasing SGA sizes or connection counts: AGT ie akg Supported on Windows 2000 Advanced Server and Windows 2000 Datacenter Seno 8? ua VLM_ Instance Tuning - VLM configurations ne improve database performance by. caching more Nate database buffers in memory. This reduces disk /O Oncle 91 Release 2 (9.2) VLM compared to configurations without VLM. VLM. configurations do not support support in Oracle9i release 2 (9.2) has been ‘multiple dutsbase block sizes. re-written (o integrate very closely wih On?) ES database. User Migration Utility - A new command-line tool, User Migration Utility, simplifies conversion of local or external database users to enterprise users. . Q Oracle Shared Server Process ~ It is a server configuration which allows many user processes to share very few server processes. The user processes connect to a dispatcher hackground process, which routes client requests to the next available shared server process. Oracle Shared Server Process, which limits the number of threads needed in the Oracle database process, suppo-ts over 10,000 simultaneous connections to a single databass instance. a. - . Oracle Net multiplexing and connection pooling - Oracle Net multiplexing and connection pooling features a!iow a large configuration to connect more users to a sirigle database instance. Q Oracle Real Application Clusters - Oracle Real Note ; Application Clusters raises coanection cone i Gen dramatically by allowing multipre server computers ayy Oncle plicat to access the ‘same database files, increasing the not supposted on Windows XP. umber of user connections by tens of thousands, 38 een well as increasing throughput. . SOFTWARE DEVELOPMENT TOOLS OF ORACLE ‘which are comme 1. Structured Query language (SQL): Ithes 9 commands e 4. CREATE, DROP, ALTER for Tables b INSERT, UPDATE, DELETE for Reco c. GRANT, REVOKE for Permission _ aoe r should take up one byte 4 d. SELECT for ae 1 SQL standards, which stare that one chal Sy ANSI ISO. wmichis qualiy control, SQL was initiated by IBM but now 10 all RDBMS OCAHNEU WIL Lalo ech same on ti estan se mem em) lain ine DATABASE CONCEPTS 9 2. SQL*PLUS: It is an extension to SQL. It has been introduced to eliminate SQL limitations. tt has ir inate it hundreds of SQL commands is envioenone mands. SQL is a subset of SQL*PLUS. It is used for setting up the 3. Procedural Language SQL (PL*SQL): ft i OOPS. It's a Forth eration angers guy ais 4. Forms: It is used for creating data entry screens, It is a Grapt ; Forms took - Ibis part of Oracle’s Internet Development suite Reports: A teport writer in Oracle. ft has man! creating reports. It is part of Oracle's Inemet Developer games tat can be wed a templates for 6. Menus: Itis part of Oracle's Intemet Development suite i eee i is part a peed Internet Development Suite + IDS: it includes the above four tools ie. Forms, Reports, Menus, ics." i known as Developer 2000. It is also an Internet Develoomert Suite $8 Goh: wes previously 9. used to take Onicle database backups 10. IMO: This is used to Restore backups 11. Oracle terminal (Oraterm): Used for Keyboard mapping 12. SQL * Loader: Convens files from other RDBMS To Oracle 13. SQL *DBA/SVRMGRIOEM: Database administration 14. Oracle Case: Cad, DFD, ERP, Diagrams 15. Designer 2000: It includes Oracle CASE tools plus an [DS 16. Oracle Power Objects: Support for VB 17. Oracle Objects for QLE: C++ and VB connectivity 18. Oracle Manufacturing: Software for manufacturing processes 19. Oracle Financials: Accounting software (ERP) 20. Oracle HRMS: HRD Software . 21. Oracle Applications: It includes Oracle manufacturing, Oracle financials & Oracle HRMS 22. Oracle CRM: Software used in Call centers, E-sales, E marketing 23. Oracle Web Browser: For browsing an iol dab . Discover 2000: It includes Oracle Web Browser plus an | . a Personat Oracle: Single user version of the Oracle database engine (DOS + Windows) ramming language native to Oracle. tt suppons hical User Interface, front end, client side, “INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) in a is it interface to relational database systems. Language (SQL) is a language that provides an in ‘SOL vas ‘soniye by IBM in the 1970s for us¢ in System R, and is a de facto standard, as well as an ISO -git-ANSI standard. SQL is often’ pronounced SEQUEL. oe i i ERTs, UPDATEs, r DML (Data Manipulation Language), for INSERTS, tn common wage SOL ae pea agape) sed fr ceaing and modiing wiles nd ober abs: “structures. / i i rds Institute (ANSI) is The developinent of SQL is governed by standards. The Late ane sak pana zat sin Sante ato org ved in 1986 based on IBM's an organization that approves Ctl : aan orally approved oy ii | database communication, Orig TE NST SsQu sala standard language in relational t no gan (180) se cna i i 7, the International Standares zal ae called 0192 The neves eal wad cd was revised again in 199; ject extensions and are Boe ee ig A referred to as SQL3, SQL3 support object ex! standard is now called i ; antad in OvarleR and 9. Se nee 0 SOI. hes t pp cof mer SQL cnecwiion Heomaine it own command Langu ge Features of SQL SOL canbe ured by a range of users, i Jy vs 2 Hon procedural language ween » command language for conmenanaeat niin Omncle SQL contain many extensions, When an SOL tarernent is see dalled dhe SQL buffer and remains there watit a mew SQL. statement is entered. “PLUS fv wn Oracle tool thet recognizes aed submits SQL OL, PUBL: THE PROGRAMMING LANGUAGE OF ORACLE fon with the Oracle 91 Server from any tool oF centered, its stored in a part statements to the Oracle 9i Server for inclading those with little of no programming experience 1 2 3 jrrecuces the amount of time required for creating and maintain ng systems 4 ics an English-tike Ianguage Features of SQL *PLUS jraccepts SQL input from files It controls environmental sertings 11 formats query results into basic reports In accesses local and remote databases SQL V/s SQL "PLUS sou QI. wi # language for communicating with the| Oracle Server to access dats ou awa SOL *PLUS accepts ad hoc extry of statements In provides a line editor for modifying SOL statements [SQL “PLUS ISQL *PLUS recognizes SQL statements and sends them to the server SQL is based on American National Scandards| Institute (ANSI) standard SQL FSQL manipulates data and table definitions in the database ISQL “PLUS is the Oracle proprietory interface for| lexecuting SQL statements SQL *PLUS does not allow manipulation of values in the database SOL + tered into the SQL beffer on one or more lines [epi doce not have # continvation character SQL *PLUS is entered one line al a time, not stored in} the SQL buffer SQL *PLUS uses a dash (-)as a continuation character if the command is longer than one line 5g utes function 1 perform ome forma s for SQL pdditional adjectives. Example: PROM Each verb is followed by rumber of clauses. : Treanndt be abbreviated It can be abbreviated SOL vies a termination character to execule|SQL *PLUS does not require termination characters; umerediately executes commands immediately ISQL *PLUS uses commands to format data ‘SQL suns with a verb (ie. 4 SOL action word) Example: SELECT statements. This verb may have Example: FROM, WHERE, HAVING ce need em comenine sae ae 3. A spece separates cleuses. Exemple: DROP TABLE EMP; 4, Acomma (,) veparates paremesers without a clause $ is used 10 end SQL staternents 6 Sulements may be split across lines but keywords may not 7. Lex'-al units such as identifiers, operator names, literals are separated by one or more spaces or other delimiters thpt will not be cor fused with the lexical unit SCAHNEU WILE Lalo sdemifiers unless enclosed with double quotes. Reserved fe secntun et oD TseRT [VALUES _ [PCTFREE va [ast Rupit [SHARE [MopIFY [BETWEEN [NOAUDIT [NOT [LIKE [AUD —FeragT_(owalT {CLUSTER [SESSION oN oar FABLE [NUMBER [COMMENT _|SYSDATE er ODE GRANT_|UNION JONLINE [COMPRESS _|SYNONYM uiD_|NULL_[GROUP WHERE _ [OPTION [CONNECT TRIGGER RWS [INDEX_[ACCESS_[RENAME CURRENT _|VARCHAR DECIMAL _|DISTINCT CHAR SAE [LEVEL [COLUMN [REVOKE BSC RIE rin CREATE |ROWNUM [DEFAULT {RESOURCE DROP |USER ORDER DELETE [SELECT [INITIAL [ROWLABEL ELSE [VIEW [PRIOR [EXISTS _ [UNIQUE INTEGER _|SMALLINT [OFFLINE _|VALIDATE WITH [PUBLIC HAVING [UPDATE “haracters and must slart with an alphabetic character be enclosed within single quotes : ted by simple values such as 0.32, -34, 01991, and so on, scientific ANY [FILE ‘9, Menlifiers can contain up to 30 10, Character and dace literals must 11, Numeric literals ean be represen notation as 2E5 meaning 2x10 to the power of S = 200,000. 12, Comments may be enclosed between /* and */ symbols and may be multi line. Single line comments may be prefixed with a syrabol SQL Delimiters Delivaiters are symbols or compound symbols, which hi i in ithit ee ip symbols, which have a special meaning within SQL and PL/SQI F rAddition a [Quote identifier : A Host variable F js [Exponential | i [Ste [Relational 7 ls><__ |Relatiozal <=>= [Relational [Oo Expression or list = [Assignment : —[= [Association 7 mn Concatenation —| : . eegeey saa fe 3 Remote access indi (Comm 4 A [Character string delimiter |7* 3] 7 AY) [Comment (Multitiney —] “Components of Sal. 1. DDL (Datn Detitt (Datn Definition Language) ~ It is a set of SQL cor beacesang tee d ese coinmands are mands used to create, modify and deléte daaase designer or aevlenn clon. They Tre poral lac by genera! user, wo shoo Susceptible io ROLLBACK en eevloper. These Sally used bythe DBA to aimed ete trample updates as execu eran It should aiso be WS are immediate ie. they are not every DDL command 4 ie then issuing any DDL, Toted tha: if several DML statements for Tu fve the CREATE abet anes COMMIT o meme, ld COMMIT alte update BML (Osta Manipulation tee eee and a Tablespace men the database. Anybody using DDL ae RUN) tis the ween Meain which to create objects. t allows changing data within the » OCdINEU WILT U: MSc 12 ‘SQL, PL/SQL: THE PROGRAMMING LANGUAGE oF ORACLE 3. DCL (Data Control Language) - [tis the tothe dtabase. Occasionally BCL sae er eon OFSQL statement hat conta acces to data end nts. Examples of DDL, DML and DCL commands DDL: Data Definition Language statements Examples: iF CREATE To create objects in the database ALTER Alters the structure of the database - DROP Delete objects from the database TRUNCATE Remove all records from a table, including all spaces allocated for the records are | removed | i | oo00 Q COMMENT Add comments to the data dictionary Q_ GRANT Gives user's access privileges to database Q REVOKE Withdraw access privileges given with the GRANT command DML: Data Manipulation Language statements i Examples: INSERT Insert data into a table i UPDATE Updates existing data within a table : i DELETE Deletes all records froma table, the space for the records remain | CALL Call a PLISQL ot Java subprogram / EXPLAIN PLAN Explain access path to data LOCK TABLE Control concurrency oooooo0 DCL: Data Control Language statements Examples: COMMIT Save work done - | SAVEPOINT Identify a point in a transaction to which en roll back ROLLBACK Restore database to orginal since the last COMM se SET TRANSACTION Change transaction options ria GRANT / REVOKE Grant or take back permissions to or from the oracl eoouo DQL: Data Query Language statement Examples: - 2 SELECT Retrieve data from the a database ocdi leu WILT 114 SQL, PLISQL: THE PROGRAMMING LANGUAGE OF ORACLE 7. INTERACTIVE SQL PART -! TABLE FUNDAMENTALS _ A table is database object that holds user dats, The siriplest analogy is to think of a table as « spreadsheet, The cells of the spreadsheet equate to the columns of a table having a specific data type associated with them. Ifthe spreadsheet cell has a number dala type associated with it, then storing letters (Le. characters) in the same cell is not allowed, The same logic is applied to a table's column. Each column of the table will have a specific data type bound to it, Oracle the column, will be stored within the column, estat oily data, which Is identical tothe data type of Oracle Data Types B: es Data types come in several forms and sizes, allowing the programmer to create tables suited to the scope of the project. The decisions made in choosing proper data types greatly influence the performance of database, so it is wise to have a detailed understanding of these concepts. (Oracle is capable of many of the data types that even the novice programmer has probably already been exposed to. Refer to table 7.1 for some of the more = commonly used include: = eDeseription— ~s= 3 ie wed to store charac: stings vale of Teed Tengih. The Sad ia brackets JoteriiniePihe vimber oF ehtireeters the cet! cam hold. The maximum mumber of characters (ic. the size) this data type can hold is 255,characters. The data held is right- padded with spaces ia whatever length specified. For examplerIn of of Nawwe CHAR(60), ithe del in he variable Name i eal 20 characters in leaf, then the be padded wiih'40 characters wort of spaces. These spaces will be removed when the value is reiricéd though. These entries will be | sorted and compared by MySQL in .case-insensitve’ fashions unless the BINARY | Keyword is dssociéted With i. The BINARY attribute mens tLat cokimn. values == | sensitive fashion ‘Sing the’ underlying character code values rather then a lexical | ordering. BINARY d6esa't affect how the column is stored or retrieved. | i VARCHAR : This dua type is ised to store vafiable Jength alphaieric data. It is « more flexible : (size)! | form ofthe CHAR dats type. The maximum this date type can hold upto 4000 characters, VARCHAR ! One difference between this dats type and the CHAR data type is ORACLE compares ; 2size) | VARCHAR values ising uon-padded compariscn semantics ie, the inserted values will | i j not te padded wis It also represents data of type String, yet stores this dats in : * | variable length format. VARCHAR can bild I to 255 characters. VARCHAR is.usually t .j wiser choice-thin CHAR, due to ir variable length format cliarécteristic. But, keep in | “mind, that CHAR ig much fi : er thar: VARCHAR, sometimes up to 50%. Table 7 ocd Neu WILT Ud Nove DATE {date and time. The standard format is DD-MON-yyy other’ than the standard format, use the appropriay. as in 2 + ewes date in the 24-hour format. By default, the time in a date fig | functions. DateTime fa portion is specified, The default date for a date field is the first | na an mth Valid dates range from January 1, 4712 B.C. to December 31, Description on 7 is used to repre’ This da ONO. To enter dates ‘NUMBER (PS) LONG RAW/ LONG RAW The RAW /LONG RAW data types are used to store binary data, such as digitized 4712 A.D. ; ic bers (fixed or floating point). Numbers to store numbers of The NUMBER data type is ae up to 38 digits of precision. Valid values are 0, and virtually any magnitude maybe ster tude 1.0E-130 to 9.9...£125. Numbers Es i bers with magnitude 1. . may be rai rsp oi 00 2B Ha e int (J; ‘nscientific notation, such as, 1.85E3 for 1850. The precision (P), seni cond, Mgmum length of the data, whereas the scale (S), determines te number of places to the right of the decimal. If scale is omitted then the default is zero. If precision is omitted, values are stored with their original precision upto the maximum of thes ype is used to store variable length character strings containing upto 2 GB, LONG data can be used to store arrays of binary data in ASCII format. Only one LONG value can be defined per table. LONG values cannot be used in subqueries, functions, expressions, where clauses or indexes and the normal character functions such as SUBSTR carnot be applied to LONG values. A table containing a LONG value cannot | b: clustered. picture or image. Data loaded into columns of these data types are stored without any further conversion, RAW data type can have'a maximum length of 255 bytes. LONG RAW data type can contain up to 2 GB. Values stored in columns having LONG RAW data type cannot be indexed. . . , Table 7.1 (Continued) Comparison Between Orac!e 81/91 For Various Oracle Data Types Date [Gracie a [Oracle 91 Tema li - s i Explanation 0 aan “Te maximum Where pis the precision and s is the scale. ta 838° [precision is 38 For example, clec(3,1) is a number that has’ j cigs. digits, 7 digits befor: the decimal and | digit after decid) ; the decimal mal(p, 5) ree ison ieae | ee meXimum | Where,p is the precision and isthe see fa Free” 1538 |For example, decimral(3,1) is a number that ; : igits. bas 2 digits before the decimal and 1 digit louble precision | : after the decimal. Float oo int 2 T integer Scanned with CamScz [Oracle 2, in PLSQL. Up to 2 gigabytes. —- =~ Oracle 9, : . rarchar2 (size | Up to 32767 bytes [Up to 32767 bytes in | Where size iu the number of characters to jin PLSQL. _ | PLSQL. store. Variable-length strings. Up to 4000 bytes in | Up to 4000 bytes in —— Oracle 8i. : Tong Up to 2 gigabytes. |Up to2 gigabytes. | Variable-length strings. (backward) _ tible) ‘ a Up to 32767 bytes [Up 10 32767 bytes in_| Variable-length binary Strings Thcludes year, month, day, hour, minute, land seconds. imest - 5 Includes year; month, day, hour, minute, ~ jand seconds; with a time zone displacement value .~ + - . For exemple: timeetamin($) with rime zone Scanned with CamScz vy _ The format of the rowid is: .|BBBBBBB.RRRR. FFFFF Where BBBBBBB’ is the block in the - database file; RRRR is the row in ‘ithe block; FFFFF is the database file, {Valid in PLSQL, but this datatype does not exist in Oracle 9i. Up to 32767 bytes in PLSQL. Up to 2000 bytes in Oracle.9i. - Up to 32767 bytes |Up.to 32767 bytes . in PLSQL, inPLSQL. . - Up to 4000 bytes in|! Jp'to 4000 bytes in Oracle 8i.* . Oracle 9i.: Pe Up to 4 gigabytes. |Up to-4 gigabytes. Up to4 gigabytes. |Up to 4 gigabytes. The format of the Where BBBBBBB is the block in the database file;: iT RRRR is th: row in Valid in PLSQL, but this datatype does not exist in Up to 32767 bytes in PLSQL. Up to 2000 bytes in Scanned with CamScz 118 SQL, PLISQL: THE PROGRAMMING LANGUAGE OF ORACLE The CREATE TABLE Command ‘The CREATE TABLE command defines each column of the table uniquely. Each column has a minimum of three atributes, a name, datatype and size (Le, column width). Each table column definition is a single ( ), ()); Nete espe Each column maust have a datatype. The column should either be defined as null or not null and if this value is left blank, the database assumes “null” as the default. ABrlef Checklist When Creating Tables : considered before creating a table: The following provides a small checklist for the issues that need to be @ What are the attributes of the rows to be stored? What ae the datatypes of the attributes? Should varchar? be used instead of char? Which columns should be used to build the primary key? Which columns do (not) allow null values? Which columns do / do not, allaw duplicates? Are-tnere default valies for certain columns that also allow null values? oo000 Example I: ; Create the BRANCH_MSTR table as shown in the Chapter 6 along with:the atnicture for, other table belonging to the Bank System, CREATE TABLE "DBA_BANKSYS"."BRANCH_MSTR" : "BRANCH NO" VARCHAR2(10), *_"NAME® VARCHAR2(25)); Outputs, - . : : ' Table created. Nate = = Alltable columns beiorg to a single record. Thercfore ail the table column lefinitions are enclosed within parenthesis. ” ocanned witn Lamsce INTERACTIVE SQL Paar, Inserting Data Into Tables Once a table is created, the must natural thing to do is load this table with data to be manipulate Mer, When inserting a single row of data into the table, the insert operation: U Creates v new row (empty) in the database table Loads the valves. passed (hy the SQL insert) into the columns specified Syntax: INSERT INTO («columnnamei>, , ); Example 2: Insen the values into the BRANCH_MSTR lable (For values refer to 6th chapter under Test Records) INSERT INTO BRANCH_MSTR (BRANCH_NO, NAME) VALUES(‘BI' ‘Vile Parle (HO)’); INSERT INTO PRANCH_MSTR (BRANCH_NO, NAME) VALUES('B2’, Andheri’); INSERT INTO BRANCH_MSTR (BRANCH_NO, NAME) VALUES('B3'. Churchgate’); INSERT INTO BRANCH. MSTR (BRANCH_NO, NAME) VALUES(‘B4’, ‘Sion; INSERT INTO BRANCH_MSR (BRANCH_NO, NAME) VALUES(‘BS, 'Borivali); INSERT INTO BRANCH_MSTR (BRANCH_NO, NAME) VALUES('B6,, ‘Matuinga’); Output for each of the above INSERT INTO statemen 1 row created. In the INSERT INTO SQL sentence, table columns and values have a one to one relationship, (ke. the fir value described is inverted into the first column, and the second value described is inserted into the se columa and so on). : - Hence, in an INSERT INTO-SQL sentence if there are. exactly the same umbers of values as there columns and the valu:s are sequenced in exactly in accordance with the data type of the table colun there is no need to indicate the column names, . However, if there are less values being described than there are columns in the table then itis mandate 0 indicate both the table column name and its comesponding value in the INSERT INTO SQL sentence. . . + An the absence of mapping a table column name to a value in the INSERT INTO SQL sentence, the Ore! engine will not know which columns to insert the data into. This will generally cause a loss of 4 i ty. Then the data held within the table will be largely uséless. Hote =m: “ ; SOE EEEET ETT Refer (9 the file Chap07_Adtu.pdf, for the INSERT INTO staterient beionging t0 the tables a: mentioned iti Chiapter 6. These statements ure built on the test data mentioned in CH#Pl 6: Tist Records For Retall Banking. : OcalNeu WIL Ud yao SQL, PLISQL: THE PROGRAMMING LANGUAGE OF ORACLE VIEWING DATA IN THE TABLES ‘Once data has been inserted into a table, the next most logical operation would be to view what has been Geared, The SELECT SQL vst is sed to achieve this The SELECT comiaand is used to etreve rows selected from one or more tables. : All Rows And All Columns Inorder to view global table dats thg syntax is: ‘SELECT FROM TobleName: 1 to ColuennName N represents table column names. seep _Here, ColumaName Syntax: : SELECT * FROM ¢TableNome>; Example 3: 7 Show all employee numbers, first name, middle name and last name who workin the bank, SELECT EMP_NO, FNAME, MNAME, LNAME FROM EMP_MSTR: ‘Bayross Desai Joshi : oe Joseph ~ 7 ea : Dalvi Nelson IS, sed Seater ge ocdiiileu Witt When data from all rows and Columns from the table are to be viewed the syntax of the SELECT statement will be: SELECT * FROM ; Oracle allows the use of the Meta character asterisk (*), this is expanded by Oracle to mean all rows ; and all columns in the table, ‘The Oracle Server parses and compiles the SQL query, executes it, sad retrieves data from all rows/columns from the table. — — — Filtering Table Data While viewing data from a table it is rare that all the data from the table will be a oy Hence, SQL provides a method of filtering table data that is not required, The ways of filtering table data are: Selected columns and all rows ae = 2 Selected rows and all columns 2 Selected columns and selected rows ted Columns And All Rows ‘The retrieval of specific columns from a table can be done as shown below: Syntax: SELECT , FROM: : Scanned with CamScz specific If information of a particular cliem is to be feirieved from a table, its retrieval must be based on condition. The SELECT statement used until now displayed all rows. This is because there was no condition set that informed Oracle about haw to choose a specific sét of rows (or a specific row) from any table. Oracl provides the option of using a WHERE Clause in an SQL query to apply a filter on the rows retrieved. When a where clause is added to the SQL query, the Oracle engine compares each record in the table with the condition specified in the where clause. The Oracle engine displays only those records that satisfy the specified condition. Syntax: SELECT * FROM WHERE : Here, is always quantified as Example 6: : Display the branch details of the branch named Vile Parle (HO) SELECT * FROM BRANCH_MSTR WHERE NAME ='Vile Parle (HO); Vile Parle (HO) Scanned with CamScz INTERACTIVE SQL Part Output: ACCT_NO, ‘3a $B3 $85 ‘SBE SBB ‘$B9 7 cows sel2cted. ELIMINATING DUPLICATE ROWS WHEN USING A SELECT STATEMENT ‘Atable could hold duplicate rows. In such a ease, to view only unique rows the distinct clause canbe used The DISTINCT clause cliows removing duplicates from the result set. The DISTINCT clause can only be. used with select statements, “The DISTINCT clause scans through the values of the columa/s specified and displays only unique valu from amongst them. Syntax: SELECT DISTINCT , FROM «TcbleName>; ‘The SELECT DISTINCT * SQL syntax scans through entire rows, and eliminates rows that have exactly the same contents in each column, Syntax: SELECT DISTINCT * FROM : Example 8: Show different types of occupations ofthe bank custorsers by eliminating the repeated occupations SELECT DISTINCT OCCUP FROM CUST_MSTR; Output: OCCUR Business Community Wel: Executive Infornation Technology Retail Business Self Employed Service 7 rows s2lected; -First insert one more record inthe tabls BRANCH_M: pas Cr I MSTR so as to see the output for the INSERT INTO BRANCHL_MSTR (BRANCH_NO, NAME) VALUES(B6, "Matunga); gai, PUSAL: THE PROGRAMMING LANGUAGE oF onAoig gus ge branch details. show gcT DISTINCT * FROM BRANCH _MSTR; seu c cto ouput shows the ety fr Bony one even ough enered ening oe The . Vile Parle” (iioy ~ Andheri Churchgate Sion Borivali 86 Matunga ¢ rows selected. SORTING DATA IN A TABLE Oracle allows data from a table to be viewed in a sorted order. ‘The rows {ctrieved from the table will be sorted in either ascending or descending order depending on the condition specified in the SELECT sentence. The syntax for viewing data in a sorted order is as follows: Syntax: SELECT " FROM ORDER BY , <{Sort Order)»; The ORDER BY clause sorts the result set based on the Columns specified. The ORDER BY clause can only be used in SELECT statements. 5 Example 10: Show deail ofthe branich according to the branch's name. SELECT * FROM BRANCH_MSTR ORDER BY NAME; Output; BRANCH NO NAME a . Andheri Me Borivald [ Churchgate ne Matunga HM Matunga tl Sion Vile Parle (10) 1 ros selected, * — te aS ates umn name fe) a temina data in descending sorted order the word DESC must b: mersioned after the clemn Oa nd before i wt order, the Oracle 7 ai the semi colcn in the ordet by clause. In case there is no mention of the so Sine sors in ascending order by defaalt, | dvarineu wit LamSce INTERACTIVE SQL PARTI 425 Example 11: Show the details of the branch according to the branch’s name in descending order. SELECT * FROM BRANCH_MSTR ORDER BY NAME DESC; Outpr B4 Sion Dé Matunga BE Matunga B3 Churchgate BS Borivali . B2 Andheri, 1 rows selected. CREATING A TABLE FROM A TABLE Syntax: CREATE TABLE (, « ColumnName>) AS SELECT , FROM Example 12: ° . Create a table named ACCT_DTLS having three fields Le. ACCT_NO, BRANCH_NO and CURBAL from the'source table named ACCT_MSTR and reaame the field CURBAL to BALANCE. CREATE TABLE ACCT_DTLS (ACCT_NO, BRANCH_NO, BALANCE) AS SELECT ACCT_NO, BRANCH_NO, CURBAL FROM ACCT_MSTR; Output: Table Speskeds . SSL HN => Ie the Source Table Acct Mtr was populated wit record then the target table Abst Dis will aso populated with the same. Scanned with CamScz { ; RACLE 126 SQL, PLISQL: THE PROGRAMMING LANGUAGE OF OF RBAL from 5 1 . ICH_NO and CUI oan named ACCT_DTIS having three fields ie. ACCT_NO, BRAN! “BALANCE. The table JAL to the source table numed ACCTMSTR and rename the field CURB: ACCT_DTLS should not be populated with any records. ICE) CREATE TABLE ACCT_DTLS (ACCT_NO, BRANCH_NO, BALAN RE 1=2; AS SELECT ACCT_NO, BRANCH NO, ‘CURBAL FROM ACCT_MSTR WHE! i Output: Table created, INSERTING DATA INTO A TABLE FROM ANOTHER TABLE aca a ith data {Im addition to inserting vats one row at a tinte into a table, i is quite possible to populate a table wit that already exists in antler tsble. The syntax for doing so is as follows: Synt INSERT INTO SELECT , FROM : Example bd: {nsert data inthe yable ACCT_DTLS using tke table ACCT_MSTR as a source of data, INSERT INTO ACCT, TLS SELECT ACCT, NO, BRANCH_NO, Cu:Bal FROM ACCT_MSTR; Output: 10 rows created, Insertion Of A Data Set Into A Table From Another Table Syntax: INSERT INTO SELECT , WHERE: «Conditions: = aie Example 15: as Insert nlp svings tank secouits Weta inthe target able ACCT-DTLS, ..' INSERT INTO ACCT.DILS SELECT ACCT_NO, BRANCH NO, CurBal FROM = WHERE ACCT.NO LIKE 'SAtyy NO, CuBal FROM ACCT n4sTR Outputs 6 rows created. DELETE OPERATIONS The DELETE command dcletes rows from ihe r lable that satisfies ition” prov clause, and fetums the numer af records deleted, St conn provided ay ig Where SCAHNEU WIL UaINOCée ithers The verb DELETE. In SQL 1s used to remove el a Allthe rowa from a table OR Q Aset of rows from a table Romoval Of All Rows SM OLETE FROM ; Example 16; Empty the ACCT_DTLS table DELETE FROM ACCT_OTLS; | Output: 16 rows deleted, Removal Of Specific Row(s) Syntax: DELETE FROM «TableName> WHERE ; Example 17; Remove only the Savings bank accounts details from the ACCT_DTLS table, DELETE FROM ACCT_DTLS WHERE ACCT_N Output: 0 LIKE ‘spy; 6 rows deleted, Sometimes it is desired to delete Possible to list be used, ° : le based o ore nes more than one table in the FROM clause whats on AlUes in another table. Since it i se While Performing a delete, the EXISTS clause Example 18: Remove the address details of the DELETE FROM ADDR_DTLE WHERE CUST Msn ou AND CUST MsTREW: customer named Wan, scannea with Camsce sal, puSQL: THE PROGRAMMING LANGUAGE oF ORACLE eatticeal records inthe ADDR DTLS table where th i wil ANE is Ivan, and the CUST_NO field belonging 10 ne Mo elnsing othe able ADDR. DTS, DATING THE CONTENTS OF A TABLE uPpDATE command is used to change of modify data values in a table. \ere is a record in the CUST_MSi the table CUST_MSTR is the fants ecb update in SQL is used to either update: al the ows froma table eect set of rows from a table jpdating All Rows UPDATE statement updates columns in the existing table's rows with new values. The'SET clause feates which column data should be modified and the new values that they should hold. The WHERE, se if given, specifies which rows should te updated. Otherwise, all table rows are updated. tax: UPDATE SET = , imple 19: the address details by changing Its city name to Bombay DATE ADDR_DTLS SET City = ‘Bombay's Expression2>; : "UPDATE SET «ColumnNamel > = eacumis, «ColurmnName2> WHERE «Conditions; ” ‘ample 20; ste the branch details by changing the Vile Parle (HO) to head office. PATE BRANCH_MSTR SET NAME = ‘Head Office! HERE NAME = ‘Vile Parle (HO)'s 2 ocarineu wit UainSce EC —— a eee," meme To use ALTER TABLE, the ALTER, INSERT, and CREATE privileges for the table are required. Adding New Columns Syntax: ALTER TABLE ADD{ («Size>), ()...); Example 21: Ener nev fed called City inthe table BRANCH_MSTR. ALTER TABLE BRANCH_MSTR ADD (CITY VARCHAR2(25)}; Output: Table altered. Dropping AColumn From A Table Syntax: li . ¢ : ALTER TABLE DROP COLUMN ; a Example 22: Drop the column city from the BRANCH. MSTR table. ALTER TABLE BRANCH_MSTR DROP. COLWMN CITY; Rie Output: Table altered. Scanned with CamScz 430 SQL, PL/SQL: THE PROGRAMMING LANGUAGE OF ORACLE Modifying Existing Columns Syntax: , ALTER TABLE «NewDatatypes()): Example 23: . Alter’ the BRANCH_MSTR table to allow the NAME field to hold maximum of 30 characters ALTER TABLE BRANCH_MSTR MODIFY (NAME varchar2(30)); Output: Table altered, Restrictions on the ALTER TABLE The following tasks cannot be performed when using the ALTER TABLE classes Change the name of the table Q Change the name of the column Decrease the size of a column if table data exists RENAMING TABLES Oracle allows renaming of tables. The rename operation is done atomically, which means that no other thread can access any of the lables while the rename process is running. rR “To rename a tble the ALTER atd DROP privileges on the orginal table, and.the CREATE and Se ipa peiiires onthe tam cb es ne, Torename a table, the syntax is Syntax: ne a | : RENAME TO «NewTobleNam2> Example 24: ‘Change the name of branches table to o branch table RENAME BRANCH_MSTR TO BRANCEIES; Output: Table, renamed. TRUNCATING TABLES {TRUNCATE TABLE empties a table complet: Logialy, this is, equivalent tc that deletes all rows, but there are practical differences under some circumstances, ae —o Scanned with CamScz INTERACTIVE SaL PaRy) i ia the following ways: {CATE TABLE differs ftom DELETE ia the followir ; Heat operations drop and re-create the table, which is much faster than deleting rows ong wae Q Truncate operations are not transaction-safe (i.c. an error will occur if an active transaction of ana table lock exists) @ The number of deleted rows are not returned Syntax: TRUNCATE TABLE : Example 25: Truncate the table BRANCH_MSTR TRUNCATE TABLE BRANCH_MSTR; ‘Output: Table truncated. DESTROYING TABLES Sometimes tables within a particular database become obsolete and need to be discarded. In such situation 4 “using the DROP TABLE statement with the table name can destroy a specific table. an Syntax; “DROP TABLE ; @ 1a table is stropped all records held within it ae lost and cannot be recovered, SS “a Example 26: . 3 Remove the table BRANCH_MSTR along with the data held, DROP TABLE BRANCH_MSTR; : Table dropped. CREATING SYNONYMS 4 penis slhemativenaine for objects such as tales, views, sequences, stored procedures, and other Syntax: : CREATE [OR REFLACE] [PUBLIC] SYNONYM [SCHEMA .] SYNONYM NAME FOR [SCHEMA J OSJECT_NAME [© DBLINK]; OCAHNEU WIL Lalo 492 SQL, PL/SQL: THE PROGRAMMING LANGUAGE OF ORA CLE ite lace phrase all a The OR replace p! allows to recteate the a DROP synonym command. Synonym (if it already exit) wit a The PUBLIC phrase means that the synonym is a publi Remember though that the user must first have the = ml 5 ate privile ‘out having t6 issue a |S accessible to all users, synonym. eS i : a The SCHEMA phrase is the appropriate schema. If ths , : ‘© the object to use the reference is made to the user's own schema, Phrase is omitted, Gracle assumes that a The OBJECT_NAME phrase is the name of the object for whi : ta can be one of the following: ich you are creating the synonym, + Table lane + Package «View + Materialized View «Sequence + Java Class Schema Object + Stored Procedure + User-Defined Object » Function + Synonym Example 27: Create a synonym to a table named EMP held by the user SCOTT. CREATE PUBLIC SYNONYM EMPLOYEES FOR SCOTT.EMP; Output: Synonym created. Explanation: Now, users of other schemas can reference the table EMP, which is.now called.as EMPLOYZES without having to prefix the table heme with the schema naméd SCOTT. For example: SELECT * FROM EMPLOYEES; Dropping Synonyms . gees Py Syntax: DROP [PUBLIC] SYNONYM [SCHEMA.]SYNONYM_NAME [FORCE]: aa, A The PUBLIC phrase allows to drop « public syrom specify a schema: Q The FORCE phrase will force Oracle to drop ine syrony Tota good idea to use the force plifast as it can cause inva yr. pubic is specified, then there i no need to even ifit has dependencies. Itis probably Tidation of Oracle objects - Example 28: noe Drop the public synonym named EMPLOYEES : i DROP PUBLIC SYNONYM EMPLOYEES; : ; 4 OCAHNEU WIL Lalo INTERACTIVE SQL PARTI 133 Output: Synonym dropped. EXAMINING OBJECTS CREATED BY A USER Finding Out The Tablels Created By A User The command shown below is wed to determine the able to which «user ha acces, ‘The tables created under the currently selected tablespace are displayed. Frample 29: SELECT * FROM TAB; ‘ Output: ACCT_FO_CUST DIES" TABLE ACCT_MSTR TABLE ADDR_DTLS TABLE BRANCH_MSTR TABLE CNTC_DTLS TABLE CUST_MSTR TABLE EMP_MSTR TABLE FDSLAB_MSTR * TABLE FD_DTLS TABLE FD_MSTR TABLE NOMINEE_MSTR TABLE SPRT_DOC TABLE TRANS_DTLS ‘TABLE TRANS_MSTR TABLE 14 rows selected. : Displaying The Table Structure To display information about the columns defined i ina ible use the following syntax . Syntax: - DESCRIBE ; ° . ‘ ‘This command displays the column names, the data types and the special attributes connected to the table. Example 30: Show the table structure of table BRANCH_MSTR DESCRIBE BRANCH_MSTR; Oxtput: Name TYPE ececeeee iARCiARG (0) VARCHAR? (25) 170 SQL, PLISQL: THE PROGRAMMING LANGUAGE OF ORACLE Output: 282 ¢ SYSDATE SYSDATE is a pseudo column that contains the current date and time. It requires no arguments when selected from the table DUAL and returns the current date. Cxample SULECT SYSDATE FROM DUAL; Oo. cr -g0L-6a~ ORACLE FUNCTIONS Oracle Functions serve the purpose of manipulating data items and retuming a result. Functions are also capable of accepting user-supplied variables or constants and operating on them. Such variables or constants are called arguments. Any number of arguments (or no arguments at all) can be passed to a function in the following format: Function_Name(argumenti, argument2,..) Oracle Functions can be clubbed together depending upon whether they operate on a sin of cows retrieved from a uble. Accordingly, functions can be classified as follows: camel Group Functions (Aggregate Functions) Functions that act on a sei of values are called Group Functions. For example, SUM, is a function, whi calculates the tol set of rumbers. A group function returns single result ow fora group of queried wo” Scalar Functions (Single Row Functions) Functions that act on aaly ans vaiue «time are called Scalar Functions. For example, LENGTH, is a function, which calzuais the leith of one particular string valuc: A single row function tetums one reult for every row of a queried table or view. ‘Slagle row functions can be further grouped together by the data type of their arguments and For example, LENGTH relates to the String Data type. Functions can be classified corte different data types as: : | ‘String Functions : For String Date type ‘Numeric Functions: For Number Dats type Conversion Functions: For Converalon of one Data type to another. Date Functions: For Date Data type | Aggregate Functions AVG: Retums an average value of , Ignoring rll valves in a column, Syotax: AVG ([«DISTINCT>| ) |) ) Example: SELECT MIN(CURBAL) "Minimum Balance” FROM. ACCT_MSTR; Output: uM COUNT(expr): Returns the number of rows where expr is not null Syntax: COUNT([«DISTINCT>| ] ) Example: : SELECT COUNT(ACCT_NO) "No. Of Actounts" FROM ACCT_MSTR; Ovtput : COUNT(): Ketums the number of rows in the ‘able, includitig diplicates-and those with ull. Syntax; . + COUNT(*) : Example: SELECT-counn(*) MAX: Retums the max imum velue Syrtax: MAX({) “Maximum Balance" FROM ACCT_MSTR; OCAHNeU WIL SQL, PLISQL: qm THE PROGRAMMING UANGUAGE oF OF Ora Le SUM: Retums the sum of the values of 'y!, syntax: SUM([| ] eno) Example: SELECT SUM(CURBAL) "Total Balance" FROM ACCT_MSTR; , Output: . Total, Balance __ a 11006 Numeric Functions ABS: Returns the absolute value of 'n’, Syntax: ABS(n) Example: SELECT ABS(-15) "Absolute" FROM DUAL; Output: 2b is POWER: Retums.m raised to the a power. m must be an integer, else an error is returned. Syntax: POWER(m,n) Example: SELECT POWERG,2) "Raised" FROM,DUAL; tm Homie; wis founded © places to the'right ofa delat 1a est be an ee. ROUND: round . UND: Retums n, jedtom ff digits to the fe of ‘the decimal poi places. m can be negative to round o Syutax: , ROUND (nf ml) : : Example: z HAL: SELECT ROUNC(IS.19,1) “Round” FROM DUAL: ‘ Output: & SCAHNEU WILE Lalo INTERACTIVE 8, PART Ii 13 SQRT: Returns square root of n, Ifn<0, NULL, SQRT returns a real result, Syntax: ae Exampl Sauer: saRTes) “Square Root" FROM DUAL; Output: * s EXP: Retums e raised tothe nth power, where €2.71828183. Syntax: EXP(n) Example: SELECT EXP(5) “Exponent” FROM DUAL; Output: uu. Exponent T98.4T3i59 EXTRACT: Retums a value extracted from a date ot an interval value, A DATE can be used only to extract YEAR, MONTH, and DAY, while a timéstamp with a time zone datatype can be used only to extrast TIMEZONE, HOUR and TIMEZONE MINUTE, Syntax: EXTRACT( fyear | month | day | hour | minute | second | timezone_hour | timezone_minute | timezone_region | timezone_abbr} . FROM { date_value | interval_value } ) Example: _SELECT EXTRACT(VEAR FROM DATE 7004-07-02) "Yeu? ~- EXTRACT(MONTH FROM SYSDATE) "Month" FROM DUAL; Outpt: _Year_Month * GREATEST: Retums the ome value in a list of expressions, Syntax: GREATEST(expel, expe2, ... expr_n) where, expr, expr2, .. expr_n ere expressions that are evaluated by the greatest function. Example: SELECT GREATEST(4, 5, 17) "Num", GREATEST(‘4', Output: _ Num Text ‘I7) "Text" FROM DUAL; OCAHNEU WIL Lalo | Smee _ In the GREATEST( and LEASTO function if the datatypes of the expressions are different, 2B expressions will be, converted to whatever is datatype of the first expression in the list. If 1 comparison is based on a character comparison, one character is considered greater than another if has a higher character set vaiue. reer ner rere MOD: Retums the remainder of a first number divided by second number passed a parameter. If th second number.is zero, the result is the same as the first number. Syntax: MOD(m, n) Example: SELECT MOD(IS5, 7) "Mod!", MOD(15.7, 7) "Mod2" FROM DUAL; Outputs Med} Mod2_ TRUNC: Returns 2 number truncated to a certain number of decimal places, The decimal place value mus be an integer. If this parameter is omitted; the TRUNC function will truncate the number to 0 decima places. : a : , [decimal_ploces}) 125.815. 1) "Trune|". TRUNC(125.815. .2) "Trine?" PRAM Nat. Scanned with CamScz cor rere murat a om Output: Fri Flr2 24 13 CEIL: Retums the smallest integer value that is greater than or equal to a number. Syntax: CEIL(n) Example: SELECT CEIL(24.8) "Ceill",CEIL(13.15) "Ceil2" FROM DUAL: Output: Ceill ceil2 2s 14 Note == ; Several other Numeric functions are available in Oracle. These include the following: SS a ACOSI), ASIN, ATANO, ATAN20, Q COS(), COSH(, SIN(), SINH(), TAN(), TANH(), Q COVAR_POP(, COVAR_SAMP(, VAR_POP(), VAR_SAMPO, . 0. CORR’), SIGN : rr String Functions LOWER: Returns char, with all letters in lowercase. Syntax: LOWER(char) Example: ; SELECT LOWER(IVAN BAYROSS’) "Lower" FROM DUAL; Output: Lo ‘ivan’ bayross INITCAP: Retums a string withthe first letter of each word in uppercase, Syntax: INITCAP(char) Example: SELECT INITCAP(IVAN BAYROSS’) "Title Case" FROM DUAL; Outp UPPER: Retums char, ‘vith all letters forced to upperce Syntax; UPPER (char) Scanned with CamScz s7e SQL, PLISQL: THE PROGRAMMING LANauAge OF ona CLE Example: , | SELECT UPPER(MS, Caro “Copied” FROM DUAL, Output: capitalised. Ms. CAROL SUBSTR: Retums a portion of chatacters, beginning at chs . omied, the resul retuned is upto the lit character he sting Tet ae to chance ttn lion of char is 1, syntax: . SUBSTR(«string>, «start position», [+length>)) where, string is the source string, start_position i the postion for extraction, The frst poston Pa? length isthe number of characters to extract, Postion inthe sing is abways 1, Example: SELECT SUBSTR(SECURE.3.4) "Substring" FROM DUAL; Output: Substring cl ASCII: Retums the NUMBER code that rey he NU Presents the specified characte. If more than one characteris srtered, the function will return the value for the frst character and ignore all ofthe characters afer th, first. Syntax: ASCTI(«single_character>) where, single_character is the specified character to retrieve the NUMBER code for. Example: SELECT ASCII(a‘) “ASCIII", ASCII(‘A') "ASCII2" FROM DUAL; COMPOSE: Retums a Unicode string. It can be a char, varchar2, nchar, nvarchar2, cab, or nelob. Syntax: . COMPOSE() Below is a lis ing of unistring silues tht ean be combined with other characters in the compose function, [Unbtring Vatu ting character] Valuing Value [Resulting eb 0200) [grave accent)» _ Hust 10301") Jacute accent (’ — ISTR(WO307)—_[eircumflex (S| UNISTROO303') tilde ( UNISTR(VO308) —_|umfaut (") Example: i , UAL; no SELECT COMPOSE(s' | UNISTR(10301")) "Composed" FROM : Scalineu wit ValliSCce INTERACTIVE SQL PART Ill 47 DECOMPOSE: Accepts a string and retums a Unicode string. Syntax: DECOMPOSE() Example: SELECT DECOMPOSE(COMPOSE(*' [| UNISTR(10301'))) "Decomposed" FROM DUAL; Output: ae INSTR: Returns the location of a substring ina string. Syntax: INSTR(«stringl >, «string2>, [«start_position>], [enth_appearance>]) where, string! is the string to searct string? is the substring to search for in string]. start_position is the position in stringl where the search will start. If omitted, it defaults to 1. The first position in the string is 1. If the start_position is negative, the function counts back start position number of characters from the end of stringl and then searches towards the beginning of stringl. ‘th _appearance is the ath appearance of string2. If omiited, it defaults to 1. Example: SELECT INSTR(SCT on the net’, v) “Instrl", INSTR(SCT on the net’,"t, 1, 2) “Instr FROM DUAL; Output: _Instrl_ Inste2, TRANSLATE: Replaces a sequence of characters in a string with another set of characters. However, it replaces a single characier ata time. For example, it will replace the Ist character inthe tring_to_replace with the Ist character in the replacement string. Then it will replace the 2nd character in the string_to_replace with the 2nd character in the replacement_string, and so on. Syntax: TRANSLATE(, , ), where, string! is the string to replace a sequence of characters with another set of characters, string, to_replace isthe string that wilt be searched for in stringl. All characters in the string to_replace will de replaced with the comesponding character in the replacement_string. - Example: SELECT TRANSLATE(‘isctS23', "123", ‘7a "Change* FROM DUAL; Output: OCAMNEU WILE Lao ayAGE OF ORALLE 178° SQL, PLISQL: THE PROGRAMMING LANGUAGE LENGTH: Returns the length ofa word. Syntax: LEN6TH(word) Example:. . AL; SELECT LENGTH(SHARANAM) "Length" FROM DUAL; Ontp ? to ol haract character i cers removed upto the first f ith initial cl ; ; left of char witt 3 ot in set. rs from the Syntax: LTRIM(charf,set)) Example: : ‘SELECT LTRIM(NISHA',N) "LTRIM" FROM DUAL; Output: LIRIM . B ‘set! is optional, RTRIM: Returns char, with final characers removed after the last character not in the set. ‘set’ is optional it defaults to spaces, : Syntax: RTRIM (chor, [set]) Example: ‘SELECT RTRIM(SUNILA\'A) "RTRIM" FROM DUAL; Outputs ‘TRIM: Removes all specified characters either from the beginning or the ending of a string, Syntax; : : TRIM( [leading | trailing | both [ FROM 1] ) there, leading - remove trim_string ffom the font of string}, } tralling - remove trim string from the end ofstring!. both - remove trim_string trom the frontand end of string! ; 2f none of the above optoa is chosen, the TRIM function wil remove trim str ; end of string, ; © trtt_string from both the front ang trim character is the character that will be Femoved from string]. {¢ thi, oe function will remove ail leading and tailing spaces from sting], BI. this parameter is omitted, the trim -String! is the string to trim. Example 1: i SELECT TRIM( Hansel ') "Trim beth sides” FROM DUAL; Scanned with CamScz INTERACTIVE SQL PART 1 eeern ‘TRIM(LEADING 'x' FROM 'xxxHanselxxx) "Remove prefixes" FROM DUAL; Output: Remove prefixes. fia Example 3: SELECT ‘TRIM(BOTH ‘x FROM ‘'xxxHanselxxx) "Remove prefixes N suffixes" FROM DUALS ‘Output: enove iiansel efixes N suffixes Example 4: SELECT TRIM(BOTE ‘I' FROM '123Hansell2111°) "Remove string” FROM DUAL; Output: ‘Renove string | “Panselia LPAD: Retums charl, left-padded to length n with the sequence of characters specified in har, If char? is not specified Oracle uses blanks by default Syntax: LPAD (chart (char) Example: SELECT {LPAM (Page 1\10*9 “LPAD" FROM DUAL: Output: BEAD, RPAD: Returns chart, right-padded to length m withthe characters specified in char’. If ea is not specified, Oracle uses blanks by default. Syste: RPAD(char'l nf, cher2]) Example: SELECT RPAD(FNAME,10,x) "RPAD Example" FROM CUST_MSTR 4 WHERE FNAME = ‘Wan; 7 Output . Teanexxxxx ‘SIZE: Returns the number of bytes inthe intemal ‘epresentation of an expression, Syntax: « VSIZE(« expression») ocdiilleu WIL 7 sal, pusat: THE PROGRAMMING LANGUAGE OF ORACLE 48 eee ystZE(SCT on the net) “Size” FROM DUAL; se output: size 34 sion Functions conve! S T0,NUM BER: Converts char, a CHARACTER value expressing a number, to a NUMBER datatype. ! i : syntax: TO_NUMBER(char) les Example CCT MSTR SET Curbal = Curbal + TO_NUMBER(SUBSTR(S100‘2,3)); UPDATE Qutput: - 19 rows updated. Sey Here. the value 100 will be added to every accounts curent balance in'the Acct_Mstr table. Bee SSS TO_CHAR (aumber conversion): Converts a value of a NUMBER datatype toa character datatype, using the optional format string. TO_CHAR() sccepts 2 number (n) and a numeric format (fmt) in which the eumber has to appear. If fmt is omitted n is converted to a char value exactly long enough to hold all significant digits. Syntax: TO_CHAR (n{.fmt]) Example: SELECT TO_CHAR(17145, '5099,999) "Char" FROM DUAL; Outp ‘SoLT, 14s* TO_CHAR (date conversion): Converts a value of a DATE. datatype to CHAR value TOL cHarg accept a date as well asthe Fora (ing) in which tv dete hes to appear. fet mst be 2 dee format. If {rats omiued, the dete is converted 10 a character value using the default date format... #.“DD-MON- Syntax: TO_CHAR(datef,fmt]) Example: SELECT TO. CHAR(DT, ‘Month DD, YYYY) "New Date Format” FROM Trans. Msi WHERE Trans_No='T1': dvanifeu win LdINSce

You might also like