Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

SQL Commands

Uploaded by

Lalit Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views

SQL Commands

Uploaded by

Lalit Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 24
114 SQL, PLISAL: THE PROGRAMMING LANGUAGE OF ORACLE au ee ape [SECTION III: Structured Query Lanau SOL 7. INTERACTIVE SQL PART TABLE FUNDAMENTALS ink ofa table as a spreads A table is database object that holds user data, ‘The simplest analogy 1810 INTE Chia sng sociated The cells of the spreadsheet equate to the columns of a table nate ied storing letters (ie. character’ them. If the spreadshe a saci tt column. Each column of the table wi} tm tatn, which is dentin! 10 the dita type gp type bound to it the column, will be stored within the colunn, Oracle Data Types Basic Data Types ited to the to create tables suited to the scope of ss allowing the programmer to create tables suited 10 the isions made in choosing proper data types greatly influence the performance of g to have a detailed understanding of these concepts. Oracle is capable of man expe . a ly of the data types that even the novice programmer has probably already been (10, Refer (0 table 7.1 for some of the more commonly used includ __Data Type aa: = ~~ Description i CHAR(si: ] This data type is use Graracter strings values of fixed length. The size in ? | brackets determ a lve nuaber a efactes the cell can hold. The maximum numberof | j characters (i.e. the size) this data type can at is 255 characters. The data held is right. | | padded with spaces to whatever length specified. . | For exampl ih case of Name CHAR(0), if the data held in the varfable Name is only | 0 characters in length, then the eniry will be padded with 40 characters worth of spaces, | | These spaces will be removed when the value is retrieved though. These entries will be | j sorted and compared by MySQL in case-insensitive fashions unless the BINARY keyword is associated with it, , The BINARY attribute means that column values are sorted and compared in case- [sensitive fashion using the underlying character code values rather then a lexical | ordering. BINARY doesn't affect how the column is stored or retrieved. VARCHAR _ This data type is used to store variable length alphanumeric data. It is a more flexible (size) / form of the CHAR data type. The maximum this data type can hold upto 4000 characters. VARCHAR | One difference between this data type and the CHAR data type is ORACLE compares 2(size) VARCHAR values using non-padded comparison semantics i.e. the inserted values will not be padded with spaces. It also represents data of type String, yet stores this data in variable length format. VARCHAR can hold 1 to 255 characters. VARCHAR is usually a wiser choice than CHAR, due to it's variable length format characteristic. But, keep in ____mind, that CHAR is much faster than VARCHAR, sometimes up to 50%, Table 7.1 y pata Type pate NUMBER ip.S) LONG RAW LONG RAW INTERACTIVE SQL PARTI 15 Description This data type is used to rey as in 21-JUN.04. Present date and time. The standard format is DD-MON-YY } functions. DateTime sian gltes Other than the standard format, use the appropriate 12:00:00 arn, fy eres date in the 24-hour format. By default the time in a dine feld is 12 am. if no time portion is specifi jor a date field is the first day of the current month, Vath Tene ‘ified. The default date for a date fi ATIZAD, ates range from January 1, 4712 B.C. to December 31, The NUMBER di: virtually lata type y magnity positive and negative expressed in two way point (); second, in. scientif determines the number of pl is used to store le maybe stored up t numbers (fixed or floating point). Numbers of 10 38 digits of precision. Valid values are 0, and numbers with magnitude 1.08-130 to 9.9...£125. Numbers may be ® fist. with the numbers 0 to 9, the signs + and -, and a decimal © notation, such as, 1.8SE3 for 1850, The precision (P). seth length of the data, whereas the scale (S). determines the be Fy He FiBL Of the decimal, If scale is omitted then the default is 7er0. If Mediate Ned. values are stored with their original precision upto the maximum of 38 digits Lote he i used (o store variable length character sirings eontaining 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 eed te subqueries, functions, | CANRSHOnS. where clauses or indexes and the normal character functions such 39 | SUBSTR cannot be applied to LONG values. A table containing a LONG value cannot be clustered. The RAW /LONG RAW data t picture or image. Data loaded int ypes are used to store ary data, such as digitized « to 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 Oracle 8: ‘or Various Oracle Data Types Data Type Oracle 81 [Oracle 91 Explanation [dec(p. 8) The maximum ‘The maximum) Where p is the precision and s is the scale. precision is 38 precision is 38 For example, dec(3,1) is a number that has digits, digits. 2 digits before the decimal and | digit after decimal(p, s) the decimal. The maximum |The maximum | Where p is the precision and s Is the scale. Precision is38 [precision is 38 |For example, decimal(3,1) is a number tha digits. digits. hhas 2 digits before the decimal and | digit after the decimal. double precision {float int [integer real (smallint Table 7.2 = 116 SQL. PLIS@L: THE PROGRAMMING LANGUAG char (size) number(p, 2) JOrncte 81 The maxinw precision is 38, digits, um imum is 38 The mi precisi digits Up to 32767 bytes in PLSOL Up to 2000 bytes in ele Si, fintot SOL. Up to 4000 byt Oracle 1 _ ip to 32767 bytes The maximum precision is 38 digits The maximum ion is 38 digits Up to 32767 bytes PLSOL. Up to 2000 bytes in jp to 32767 byt PLSQL. Up to 4000 bytes in Oracle 9 n_ j ) je precision and v iethea= hep the eae where 1! Where 7 rons For example, numeric(?-2) 18.9 Imhep its before the decimal ang 9 pat has 5d Arne after te deel < ie prec Hv here p is th Where nte. number 7.2) 18 number € the decimal a re md | For example that has 5 dig! ‘after the deci: _ is the number of character =| ngth strings. Space pada, | Where size store. Fixed-let J | =-size is the number of character j= Whe r tore, Variable-length strings, Variable-length strings. (backward Tong Oracle Si, Up to 2 gigabytes. compatible) —__ _ Variable-length binary strings raw I ip to 2 gigabytes, Up to 32767 bytes in PLSQL. Up to 2000 bytes in Oracle 8, Up t0 32767 bytes in PLSQL. ‘Up to 2000 bytes in Oracle 9i. Varlable-length binary strings. ( (csize>), («si ys: . Note = Each column must have a datatype. ‘The column should either be defined as null or not nul ng => i: value is left blank, the database assumes “null” as the default. ———— A Brief Checklist When Creat ing Table: The following provides a small checklist for the issues that need to be considered before creating a table: What are the attributes of the rows to be stored? What are the data types 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, allow duplicates? Are there default values for certain columns that also allow null values? So000g Example 1: : Create the BRANCH_MSTR table as shown in the Chapter 6 along with the structure for other ui belonging to the Bank System. RANCH_MSTR"( CREATE TABLE "DBA_BANKSYS' "BRANCH_NO" VARCHAR2(10), "NAME" VARCHAR2(25)); Output: Table created. gle record. Therefore all the table column definitions are encl All table columns belony to a SS thin parenthesis, EE —___—— ————————————— ee Inserting Data into Table S INTER, Once a table is crentey, th : When inserting a singe , D Creates a new rome Loads the vatuee nae n sample 2: vPressiong Insert the values ine th Ne BRANC NCH Misty ORANG y ORAS ONAN = R dean (BRANC BRANC Output for cach oF the above pers. 1 row created, MOCINSERT | Tip Character ex; O. ‘essions ph Med within the Inthe INSERT INT value described ig jn, column and so on), © SOL sentene Sentence, table columns serted into the f iyi st column, and SNE A One to one relat 1 described is inse the second valy, Columns in the table then it is In the absence of mapping a tabi engine will not know which columns integrity. Then the data held within the table will Note the remaining Refer to the file Chap07_Adtn.paf, for the INSERT INTO statement belonging to tables as mentioned in Chapter 6. These statements are built (on the test data mentioned in Chapter 6: Test Records For Retail Banking. ee a a? 1 20 SOL, PLISaL: THE PROGRAMMING LANGUAGE OF ORACLE _VIEWING DATA IN THE TABLES neration would be LECT command is w Once da ; inser 2 ta has been inserted into a table, the next most logical oP Meerted The SELECT SQL verb is used to achieve this: The Si selected from one or more tables. All Rows And All Columns In order to view global table data the syntax i i SELECT TO FROM TableName: jumn names. ING ee SEG Here. ColumnNamet to ColumnName N represents table col Syntax: SELECT * FROM : e who work in the bank. Example 3: Show all employee numbers, first name, middle name and last nam SELECT EMP_NO, FNAME, MNAME, LNAME FROM EMP_MSTR: Outp: El Bayross E2 Amit Desai E3 Maya Mahima Joshi E4 Peter Iyer Joseph ES Mandhar Dilip Dalvi E6 Sonal Abdul Khan E7 Anil Ashutosh Kambli E8 Seema P. apte E9 Vikram Vilas Randive E10 Anjali Sameer = Pathak 10 rows selected. Example 4: Show all the details related to the Fixed Deposit Slab SELECT * FROM FDSLAB_MSTR3 Output: FDSLAB_NO ve we Output: ( 6 Comtiniteg) Tate Mall tering “able data a isnoreen he The ways, OF filtering tae ta are, > O Selected Columns and af Tous F Selected rows ang All colunng O Selected column cl Desai Joshi Joseph Dalvi Khan Kambli Apte Randive Pathak 10 rows selected, 122 SOL, PLISOL: THE PROGRAMMING LANGUAGE OF ORACLE Selected Rows And All Columns If information of a particular et condition This # «(or asp to apply a filte The SELECT statement teed tintil now dixplayed all rows informed Oracle nbout how to choose a epecific cet of Provides the option of using a WHERE Clange in ap SOL query ach cle engine compar s only those records that When a where clause is added to the SQL query. the Or the condition specified in the where clause specified condition engine display Syntax: SELECT * FROM WHERE : ied as Here, is always qua Example 6: Display the branch details of the branch named Vile Parle (HO) Vile Parle (HOY's SELECT * FROM BRANCH_MSTR WHERE NAM| Output: CH Bi Note such as When specifying a condition in the where clause all standard operato arithmetic, predicates and so on, can be used. => an“ SS 390—0 Selected Columns And Selected Rows To view a specific set of rows and columns from a table the syntax will be as follows: Syntax: SELECT , FROM WHERE ; Example 7: List the savings bank account numbers and the branch to which they belong. SELECT ACCT_NO, BRANCH_NO FROM ACCT_MSTR WHERE TYP! "TAG SO Papp, ta ELIMINATING OUP Lica A table could hog op E Rows Me Thi oT Ins, fcr tlause ata, 8 * Statemen The DISTINGY g Stem, ts, MN lca clans, from amongst then, © Scans “hough Syntax: SELECT OISTINey « The SELECT pig 7) iC the same contents jn ch colony, Syntax: SELEcT DISTINCT + Example 8: Community Weltare Executive Information Technology Retail Business Self Employed Service 7 rows selected, First insert one more record ? in the table BRANCH MTR so 3 ose the cua rte Bet query example, INSERT INTO BRANCH, MSTR| (BRANCH_NO, NAME) VALUES(BS, Maung); N 424 SQL, PLISOL: THE PROGRAMMING LANGUAGE OF ORACLE Example 9: Show only unique branch details SELECT DISTINCT * FROM BRANCH MSTR: nly once even though entered twice in the tay The following output shows the entry for BO NO Vile Parle’ (HO) Andheri Churchgate Sion Borivali Be Matunga 6 rows selected. SORTING DATA IN A TABLE in a sorte data from a table to be viewed | escending order depending on t ted order is as follows: 1d order, The rows retrieved from the ty he condition specified in he ¢ EL ae: Oracle allows sorted in cither ascending or descen¢ sentence. The syntax for viewing data in a so Syntax: SELECT * FROM <[Sort Order]>; ORDER BY , he columns specified. The ORDER BY ¢ja,,, The ORDER BY clause sorts the result set based on tl only be used in SELECT statements. Example 10: Show details of the branch according to the branch’s name. BY NAME; SELECT * FROM BRANCH_MSTR ORDER Andheri Borivali Churchgate Matunga Matunga Sion Vile Parle (HO) 7 rows selected. For viewing data in descending sorted order the word DESC must be mentioned after the column: and before the semi colon in the order by clause. In case there is no mention of the sort order, the 0 engine sorts in ascending order by default. peample 11: pave the details of the sh the beamed ae 7 word SELECT * FROM RR Ag, : st ANeH Msy Rr Outpt CREATING A TABLE FRom AT, syntax: ABLE " CREATE TABLE «Tabi AS SELECT «Column ? (-Coluanta, me > aa a, “€ Col Example 12: “umnNames Frog eine) Create a table named ACCT Tr TeBleNames DTLS hav the source table named Acros having 4 poath named ACCT nignit ee enc e, Ace NO, BRAN E TABLE A ae, ORBAL iw BaLaNcen! CU CRE SELECT acer NDE RAACCT No, BRan siebauaver ORAL -NO, RANCH No. cuts AL ENO BALANCE) Vl ; FRom ACCT _Mstr; rable created. Note : “Bete Ut the Source Table ace SF ye popuiated with the same YS Poulatd ip “cords then the target tab st table Acet_Dtls will also The Source table is the table identified inthe SELE Source ta CT section ofthis § one identified in the CREATE section of tie Soe is SQL staat, The Target table is dota Home Seulbetchie QL sentence, This SQK ar Populates the Target table To create a Target table without the re: fk . he selec cords from the source table (i.e. tructure only) WHERE clause. (i.e. create the st nly), 1 me ~ The WHERE clause must specify s condition that cannot satisfied. This means the SELECT statement in the CREATE TABLE detinition wil ti Nl not retrieve any rows from t source table, it will just retrieve the table structure thus the target table wi ill be created empty. 126 ie SQL, PLISOL: THE PROGRAMMING LANGUAGE OF ORAC! Example 1a: Crente a inti. the sour aa pitned ACCT_DTLS havi : mee table named ACC ee ACCT DTL ST, med ACCT MSTR m Hd not be populated with any records ANCH_NO and ¢ felds ic. ACCT_NO. BRANC nd CUR Fields ce eid CURBAL to BALANCE CREATE TanLE ; BALANCE) BLE ACCT_DTLS (ACCT_NO, BRANCH NO. r VERE ASSELECT ACCT NO, ARANCIL NO, CURBAL FROM ACCT. MSTR WHERE 1-7, Output: Table ¢ reate, INSERTING DATA INTO A TABLE FROM ANOTHER TABLE In addition that alte " 10 inserting data one row a ossible to populate a t ime into a quite p al sts table, Th yntas for doing so is as follows? Syntax: INSERT INTO SELECT FROM ; Example 14: {nsert data in the fable ACCT_DTLS using the table ACCT_MSTR as a source of data, INSERT INTO ACCT_DTLS SELECT ACCT_NO, BRANCI_NO, CutBal FROM AC Output: 10 rows created, Insertion Of A Data Set Into A Table From Another Table Synts INSERT INTO SELECT , FROM WHERE ; Example 15: Insert only the savings bank accounts details in the target table ACCT_DTLS. INSERT INTO ACCT_DTLS SELECT ACCT_NO, BRANCH_NO, CurBal FROM ACCT_MSTR WHERE ACCT_NO LIKE 'SB%'; Output: 6 rows created. DELETE OPERATIONS The DELETE command deletes rows from the table that satisfies the condition provided b; clause, and returns the number of records deleted, caution The verb DEL Ey ing o AM Me roves fay SOL is oR able OD Asetoftor, fron, ay able Removal of All Rows Syntax: DELETE FROm Example 16: Ta Names. Empty the AC PTS table DELETE FROM acc; Dns, Output: 16 TOWS deleteg, Removal Of Spec} fic Row(s) Syntax: DELETE FROM “TableNames WHERE cae “Conditions, CCT NO LIKE gpo,. Output: SB; 6 rows deleteg, Removal Of Specific Row(s) Bas, ited to delete eee than one table in ‘ed On The Data Held B, Ords in one tab} the FROM claus Sometimes it is desir possible to list more be used, 'y The Other Table Values in another forming a delete, le based on ble. Since it is aot Se While pe the EXISTS clause caz Example 18: Remove the address details of the customer named Ivan, DELETE FROM ADDR_DTLS WHERE EXISTS(SELECT FNAME FROM CUST_MSTR WHERE CUST_MSTR.CUST NO= ADDR_DTLS.CODE_NO AND CUST_MSTR.FNAME= ‘Wan’); oN oF ORACLE 128 SQL, PLISAL: THE PROGRAMMING LANGUAGE Output: Tow deleted, Explanation: This win ecord in the CUS here there is a record in Tw whose f delete all records in the ADDR_DTES table where MUTT uct MsTR is mi NAME is Ivan, and the CUST NO field belonging CODE NO belonging to the table ADDR. DTLS. Tp, UPDATING THE CONTENTS OF A TABLE : ina table The UPDATE command is used! to change oF modify data values The verb update in SQL is used to cither update: 7 AT the rows froma table OA select set of rows from a table Updating All Rows : ie +s rows with new values, The The UPDATE statement updates columns in the existing table’ i ae rol Te indicates which column data should be modified and the new val ie all table rows are updated clause, if given, specifies which rows should be updated. Otherwise, Syntax: UPDATE 2> = SET = , DROP coLy; NN («NewSize NAME field to hold maximum of P30 char, 1_MSTR table to allow the Example 23; H_MSTR MODIFY (NAME varchar2(30)); Alter the BR. ALTER TABLE BRANC! ANC! Output: rable altered. n the ALTER TABLE be performed when using the AT Jause: Restrictions ©! wing tasks cannot name of the table column lumn if table data exists ‘The follo a Change the Change the name of the Decrease the size of a col RENAMING TABLES aming of tables. TI ‘any of the tables while the r Oracle allows ren he rename operation is done atomically, which ename process is running. Means that a w* thread can access | DROP privileges on the original table, and th and the G name a table the ALTER an Tr Note = is INSERT privileges on the new table are required. To rename a table, the syntax is Syntax: me> TO RENAME ; Example 26: Remove the table BRANCH _MstR along with the data held. DROP TABLE BRANCH_mstR; Output: Table droppea. CREATING SYNONYMS A synonym is an alternat tive name for objects such as tables, views, sequences, stored Procedures, and latabase objects. eee [OR REPLACE] [PUBLIC] SYNONYM, TSCHEMA .} SYNONYM_NAME FoR [SCHEMA .] OBJECT_NAME [@ DBLINK]; > | 132 SQL, PLISQL: THE PROGRAMMING LANGUAGE OF ORACLE In the syntay a 7 D Hak replace phrase allows to recreate the synonym (if it already exists) without hayin, , synonym command, itty a c Pl x el + i The PUBLIC phrase means that the synonym is a public synonym and is accessible yy ite privileges (0 the object. thy Ren ember though that the user must first have the anpronrt onym a SCHEMA phrase is the appropriate schema, If this phrase is omitted, Oracle assin,, a Tyree mind to the user's ow seem. i ; 2 JECT _NAME phrase is the name of the abject for which you are creating the gy, can be one of the following: S + Table . ized View * Sequence * Java Class Schema Object * Stored Procedure * User-Defined Object * Funetion * 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 EMPLOYEES witn, having to prefix the table name with the schema named SCOTT. For example: SELECT * FROM EMPLOYEES; Dropping Synonyms Syntax: DROP [PUBLIC] SYNONYM [SCHEMA.]SYNONYM_NAME [FORCE]; In the syntax, The PUBLIC phrase allows to drop a public synonym. If public is specified, then there is no ne specify a schema. Q The FORCE phrase will force Oracle to drop the synonym even if it has dependencies. It is pbs not a good idea to use the force phrase as it can cause invalidation of Oracle objects Example 28: Drop the public synonym named EMPLOYEES DROP PUBLIC SYNONYM EMPLOYEES; x, EXAMINING BIKE < rnc Finding o, ae = 9 Out The Tablon, 7 REATED ' es he COMMANT shown 4, Toateg u nder the curren lew ig s os MY setectea tea te te” SUae, eR Example 20: Mespnce eT MsPtayeet |e te “hich ADDR _DTL: BRANCH_MSTR TLS TABLE TABLE TABLE TABLE TABLE, 14 rows selectea, Displaying The Table Structure To display information Syntax: the following syntax DESCRIBE ; This command displays the column names, the data » types and the special attribute tes Connected to the table. Example 30: Show the table structure of table BRANCH_MSTR DESCRIBE BRANCH_MSTR; Null? Type VARCHAR2 (10) 7 VARCHAR2 (25) 5 OF ORACLE q34 SOL, PLISOL: THE PROGRAMING LANGUAG SELF REVIEW QUESTIONS ayes PULLIN THE BLANKS 1 A ic m dntahince object that holds meer 2. Table creation ie done ucing the

You might also like