1SQL(Structured Query Language)CREATED BY:-Gaurish Gopal GoelPeopleSoft TraineeAEQUOR INFORMATION TECHNOLOGIES17thOctober ...
2CONTENTSTOPIC PAGE NO.SQL – Introduction………………………………………………………………………….3Database Architecture……………………………………………………………………….4-...
3SQL – IntroductionSQL is a tool for organizing, managing, and retrieving data stored by a computer database. Thename "SQL...
4Database ArchitectureArchitecture describes the structure of the contents of the database specified by SQL1 Standard.Ther...
5Multi-Location Architecture:Multipledatabases
6 Supports multiple databases. Uses computer system‟s directory structure to organize them. Different databases at diff...
7 The CUST column is a foreign key for the CUSTOMERS table, relating eachorder to the customer who placed it. The REP co...
8DATA TYPES: (ORACLE Specific)Data types are broadly classified into:1. Character data types2. Numeric data types3. Date d...
92. Floating-Point Numbers:There are two numeric data types for floating-point numbers: BINARY_FLOAT (32-bit, single-prec...
10BUILT-IN FUNCTIONSFUNCTION RETURNSBIT_LENGTH (string)Number of bits in a bit stringCAST (value AS data type)The value co...
11Types of Commands in SQL1. DDL (Data Definition Language) Create – Adds a new table to the database Drop – Removes a t...
12CONSTRAINT person_pk PRIMARY KEY (P_Id))Result:P_Id LastName FirstName Address CityWe can also make more than one column...
13Result:P_Id LastName FirstName Address City DateOfBirth1 Goel Gaurish Gurgaon South_City12 Dash Bimal Ghaziabad Shipra_S...
14Result:P_Id LastName FirstName Address City DateOfBirth1 Goel Gaurish Gurgaon South_City1 11-JUL-922 Dash Bimal Ghaziaba...
15back out any changes made to the database during the transaction. In effect, the DBMSrestores the database to its state ...
16JOINSSQL joins are used to query data from two or more tables, based on a relationship betweencertain columns in these t...
17Example-1:SELECT FirstName, Address, P.P_Id FROM Persons P, Accounts A WHERE P.P_ID = A.P_IdExample-2:SELECT FirstName, ...
18Result:P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id1 Goel Gaurish Gurgaon South_City111...
19Result:P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id1 Goel Gaurish Gurgaon South_City111...
20SELECT * FROM Persons FULL OUTER JOIN Accounts ON Persons.P_Id =Accounts.P_IdResult:P_Id LastName FirstName Address City...
21Syntax:create alias per for Personscreate alias acc for AccountsWe can also drop the created aliases:drop alias perdrop ...
22Result:Above example will create a view with the name “GGG” which selects specifiedcolumns.INDEXESAn index is a structur...
23Syntax to create an index:Unique is used to specify that the combination of columns being indexed must contain a uniquev...
24Note:There are two temporary tables Inserted & Deleted which are created automatically by theDBMS. These tables make our...
25CLUSTERINGA cluster is a schema object that contains data from one or more tables, all of which have one ormore columns ...
26Column: Specify one or more names of columns in the cluster key. You can specify up to 16cluster key columns. These colu...
27SYSTEM TABLESSystem tables provide information regarding the structure of the database itself. Each vendor hasits own st...
28EXPLAIN PLANSThe EXPLAINPLAN statement displays execution plans chosen by the optimizer for SELECT,UPDATE, INSERT, and D...
29Figure -1Figure -2
30Figure – 1Select * from PS_DEMAND_PHYS_INV where business_unit = EURLCIn figure – 1 only one condition is given which is...
31APPENDICESAALIAS 21BBUILT-IN FUNCTIONS 10CCLUSTERING 25DDATA TYPES(ORACLE Specific)Character Data Types 8(ORACLE SPECIFI...
Upcoming SlideShare
Loading in...5
×

SQL, Oracle, Joins

606

Published on

Published in: Education, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
606
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "SQL, Oracle, Joins"

  1. 1. 1SQL(Structured Query Language)CREATED BY:-Gaurish Gopal GoelPeopleSoft TraineeAEQUOR INFORMATION TECHNOLOGIES17thOctober 2012
  2. 2. 2CONTENTSTOPIC PAGE NO.SQL – Introduction………………………………………………………………………….3Database Architecture……………………………………………………………………….4-6Single-Database ArchitectureMultiple Database ArchitectureMulti-Location ArchitectureTypes of Keys in SQL……………………………………………………………………….6-7Primary KeyUnique KeyForeign KeyComposite Primary KeyDATA TYPES: (ORACLE Specific)………………………………………………………..8-9CharacterNumericDATELOBBUILT-IN FUNCTIONS…………………………………………………………………….10Types of Commands in SQL…………………………………………………………………11-15DDLDMLDCLTCLJOINS………………………………………………………………………………………...16TYPES OF JOINS……………………………………………………………………………16-20Inner Join Equi Join Natural Join Cross or Cartesian JoinOuter Join Left Outer Join Right Outer Join Full Outer JoinSelf JoinALIAS………………………………………………………………………………………..21VIEWS……………………………………………………………………………………….21-22Horizontal ViewVertical ViewINDEXES…………………………………………………………………………………….22-23TRIGGERS…………………………………………………………………………………...23-24DUAL TABLE………………………………………………………………………………..24SCHEMAS…………………………………………………………………………………...24-25CLUSTERING……………………………………………………………………………….25-26SYSTEM TABLES…………………………………………………………………………...27SYSTEM CATALOGS……………………………………………………………………….27EXPLAIN PLANS……………………………………………………………………………28-30
  3. 3. 3SQL – IntroductionSQL is a tool for organizing, managing, and retrieving data stored by a computer database. Thename "SQL" is an abbreviation for Structured Query Language.The above figure shows how SQL works.1. SQL Request is sent to the DBMS(Oracle/MySQL etc.)2. DBMS interacts with the database to find the requested data.3. Data is returned back by DBMS.SQL is used to control all of the functionsthat a DBMS provides for its users, including:• Data definition: SQL lets a user define the structure and organization of the storeddata andrelationships among the stored data items.• Data retrieval: SQL allows a user or an application program to retrieve stored datafrom thedatabase and use it.• Data manipulation: SQL allows a user or an application program to update the database byadding new data, removing old data, and modifying previously storeddata.• Access control: SQL can be used to restrict a users ability to retrieve, add, and modifydata,protecting stored data against unauthorized access.• Data sharing: SQL is used to coordinate data sharing by concurrent users, ensuringthat theydo not interfere with one another.• Data integrity: SQL defines integrity constraints in the database, protecting it fromcorruptiondue to inconsistent updates or system failures.
  4. 4. 4Database ArchitectureArchitecture describes the structure of the contents of the database specified by SQL1 Standard.There are two types of architecture:1. Single-Database Architecture2. Multiple-Database Architecture3. Multi-Location ArchitectureSingle-Database Architecture:Above figure shows singledatabase architecture where DBMS supports one systemwidedatabase. Examples of such databases are: DB2, Oracle etc.An advantage of this architecture is that the tables in the various applications can easilyreference one another.A disadvantage of this architecture is that the database will grow huge over time as more andmore applications are added to it. The problems of managing a database of that size - performingbackups, recovering data, analyzing performance, and so onusually require a full-time databaseadministrator.Multi-Database Architecture:The below figure clearly shows three different databases with a unique name assigned to each ofthe database. DBMSs which implement this architecture are: MS SQL Server, Sybase etc.The main advantage of the multi-database architecture over the single-database architecture isthat it divides the data management tasks into smaller, more manageable pieces.The main disadvantage of the multi-database architecture is that the individual databases maybecome unconnected to one another. Typically a table in one database cannot contain a foreignkey reference to a table in a different database. Often the DBMS does not support queries acrossdatabase boundaries, making it impossible to relate data from two applications.
  5. 5. 5Multi-Location Architecture:Multipledatabases
  6. 6. 6 Supports multiple databases. Uses computer system‟s directory structure to organize them. Different databases at different locations can have the same name.The major advantage of the multi-location architecture is flexibility.The disadvantages of this type of databases are same as that of multi-database architecture. Inaddition there is one more drawback i.e. there is no master database that keeps track of all thedatabases where they are located in the system‟s directory.Types of Keys in SQLKeys are those fields which are used to uniquely identify the records in a database. Thefollowing are the types of keys in SQL:1. Primary Key: It is the field that can uniquely identify a record and every value in this fielduniquely identifies a row in the record. Cannot accept NULL values. Cannot accept duplicate values.2. Unique Key: It‟s a set of one more fields that can uniquely identify a record. Can accept NULL value. Cannot accept duplicate values.3. Foreign Key: A column in one table whose value matches the primary key in some other tableis called a foreign key. Can accept NULL as well as duplicate values.
  7. 7. 7 The CUST column is a foreign key for the CUSTOMERS table, relating eachorder to the customer who placed it. The REP column is a foreign key for the SALESREPS table, relating each orderto the salesperson who took it. The MFR and PRODUCT columns together are a composite foreign key for thePRODUCTS table, relating each order to the product being ordered.4. Composite Primary Key: It is a combination of one or more fields/columns that uniquely identifies a record.Below is a table with a composite primary key in which MFR_ID andPRODUCT_ID are combined to act as primary key.
  8. 8. 8DATA TYPES: (ORACLE Specific)Data types are broadly classified into:1. Character data types2. Numeric data types3. Date data types4. LOB data typesCharacter Data Types:1. CHAR Data Type :Stores fixed length character strings.Must specify the string length (1-2000 bytes or characters)2. VARCHAR2 and VARCHAR Data type :VARCHAR2 stores variable length character strings.Specify a maximum string length between 1 to 4000 bytes.VARCHAR is synonymous with VARCHAR2 (later is recommended to use).3. NCHAR and NVARCHAR2 Data type :Store Unicode character data.NCHAR stores fixed length character strings (1 to 2000 bytes).NVARCHAR2 stores variable length character strings (1 to 4000 bytes).Note:A database column that stores Unicode can store text written in any language.Numeric Data Types:1. NUMBER Data type:Stores fixed and floating-point numbers.Positive numbers in the range 1 x 10-130to 9.99...9 x 10125with up to 38 significantdigits.Negative numbers from -1 x 10-130to 9.99...99 x 10125with up to 38 significant digits.Optionally, you can also specify a precision (total number of digits) and scale(number of digits to the right of the decimal point): column_name NUMBER (precision, scale) If a precision is not specified, the column stores values as given. If noscale is specified, the scale is zero.You can specify a scale and no precision: column_name NUMBER (*, scale)
  9. 9. 92. Floating-Point Numbers:There are two numeric data types for floating-point numbers: BINARY_FLOAT (32-bit, single-precision floating-point numberdatatype) BINARY_DOUBLE(64-bit, double-precision floating-point numberdatatype)Use binary precision that enables faster arithmetic calculations and usually reducesstorage requirements.Frequently used for scientific calculations.DATE Data type:The DATE data type stores point-in-time values (dates and times) in a table.The standard Oracle date format is DD-MON-YY (Ex. 11-JUL-92)To enter dates that are not in standard Oracle date format, use the TO_DATE functionwith a format mask:TO_DATE („JULY11, 1992‟, „MonthDD, YYYY‟)LOB Data Types:The LOB datatypes BLOB, CLOB, NCLOB, and BFILE enable you to store and manipulatelarge blocks of unstructured data (such as text, graphic images, video clips, and soundwaveforms) in binary or character format.Following are several types of LOB data types:BLOB Data type (128 TB of binary data)CLOB and NCLOB Data type (128 TB of character data)Bfile Data type (stores a file locator that points to an external file containing the data)Note:ORACLE doesn‟t support Boolean data type
  10. 10. 10BUILT-IN FUNCTIONSFUNCTION RETURNSBIT_LENGTH (string)Number of bits in a bit stringCAST (value AS data type)The value converted to the specified data_type (e.g.,dateconverted to character string)CHAR_LENGTH(string)Length of a character stringCONVERT (String USINGconv)String converted as specified by a namedconversionmethodCURRENT_DATECurrent dateCURRENT_TIME (precision)Current time with the specified precisionEXTRACT (part FROM source)Specified part (Day, Hour, etc.) from a DATETIMEvalueLOWER (string)String converted to all lower case letters.OCTET_LENGTH (string)Number of 8-bit bytes in a character stringPOSITION (target IN source)Position where the target string appears in the sourcestringSUBSTRING (source FROM n FOR len)A portion of the source string, beginning at the n-thcharacter, for a length of lenTRANSLATE (string USING trans) String translated as specified by a named translationFunctionTRIM (BOTH char FROM string) String with both leading and trailing occurrences ofchar trimmed offTRIM (LEADING char FROM string)String with any leading occurrences ofchar trimmed offTRIM (TRAILING char FROM string) String with any trailing occurrences ofchar trimmed offUPPER (string)String converted to all uppercase lettersNote:There are some column functions in SQL such as: SUM ( ), AVG ( ), MIN ( ), MAX ( ),COUNT ( ), COUNT (*)
  11. 11. 11Types of Commands in SQL1. DDL (Data Definition Language) Create – Adds a new table to the database Drop – Removes a table from the database Alter – Changes the structure of an existing table2. DML (Data Manipulation Language) Select – Retrieves data from the database Insert – Adds new rows of data to the database Delete – Removes rows of data from the database Update – Modifies the database data3. DCL (Data Control Language) Grant – Grants user access privileges Revoke – Removes user access privileges4. TCL (Transaction Control Language) Commit – Ends the current transaction Rollback – Aborts the current transactionSQLCommands with Example:1. CREATE TABLESyntax:CREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,......CONSTRAINT constraint_name PRIMARY KEY (column_name1,column_name2, …..,column_n))Example:CREATE TABLE Persons(P_Idint,LastNamevarchar(255),FirstNamevarchar(255),Address varchar(255),City varchar(255),
  12. 12. 12CONSTRAINT person_pk PRIMARY KEY (P_Id))Result:P_Id LastName FirstName Address CityWe can also make more than one columns as our primary keys under one constraintname.2. INSERT INTOSyntax:INSERT INTO table_name VALUES (value1, value2, value3,...)INSERT INTO table_name (column1, column2, column3,...)VALUES(value1, value2, value3,...)Example:INSERT INTO Persons VALUES (1,Goel, Gaurish, Gurgaon,South_City1)INSERT INTO Persons VALUES (2,Dash, Bimal, Ghaziabad,Shipra_Sun_City)INSERT INTO Persons VALUES (3,Chawla, Preeti, Gurgaon,South_City2)Result:P_Id LastName FirstName Address City1 Goel Gaurish Gurgaon South_City12 Dash Bimal Ghaziabad Shipra_Sun_city3 Chawla Preeti Gurgaon South_City23. ALTER TABLESyntax:ALTER TABLE table_name MODIFY column_namedatatypeExample:ALTER TABLE Persons ADD DateOfBirth date
  13. 13. 13Result:P_Id LastName FirstName Address City DateOfBirth1 Goel Gaurish Gurgaon South_City12 Dash Bimal Ghaziabad Shipra_Sun_city3 Chawla Preeti Gurgaon South_City2We can also drop a column using this command : ALTER TABLE Persons DROPCOLUMN DateOfBirth4. UPDATESyntax:UPDATE table_name SET column1=value, column2=value2 ...WHERE some_column=some_valueExample:UPDATE Persons SET DateOfBirth=‟11-JUL-92‟ WHEREFirstName=‟Gaurish‟ AND LastName=‟Goel‟Result:P_Id LastName FirstName Address City DateOfBirth1 Goel Gaurish Gurgaon South_City1 11-JUL-922 Dash Bimal Ghaziabad Shipra_Sun_city3 Chawla Preeti Gurgaon South_City2While using UPDATE command make sure that you don‟t forget to put WHERE clauseotherwise all the rows will be updated.5. DELETE FROMSyntax:DELETE FROM table_name WHERE some_column=some_valueExample:DELETE FROM Persons WHERE LastName=Chawla ANDFirstName=Preeti TRUNCATE is used to delete all rows in a table. It is a DDL commandand thisaction cannot be rolled back.
  14. 14. 14Result:P_Id LastName FirstName Address City DateOfBirth1 Goel Gaurish Gurgaon South_City1 11-JUL-922 Dash Bimal Ghaziabad Shipra_Sun_cityTo delete all rows use this command : DELETE * FROMtable_name6. SELECTSyntax:SELECT * FROM table_nameSELECT column_name1, column_name2,….. FROM table_nameWHERE some_column = some_valueExample:SELECT FirstName, LastName, DateOfBirth FROM Persons WHEREAddress = „Gurgaon‟Result:FirstName LastName DateOfBirthGaurish Goel 11-JUL-927. DROP TABLESyntax:DROP TABLE table_nameExample:DROP TABLE Persons8. COMMITand ROLLBACKSQL supports database transactions through two SQL transaction processing statements:The COMMIT statement signals the successful end of a transaction. It tells the DBMSthat the transaction is now complete; all of the statements that comprise the transactionhave been executed, and the database is self-consistent.The ROLLBACK statement signals the unsuccessful end of a transaction. It tells theDBMS that the user does not want to complete the transaction; instead, the DBMS should
  15. 15. 15back out any changes made to the database during the transaction. In effect, the DBMSrestores the database to its state before the transaction began.9. GRANT and REVOKEThe basic GRANTstatement is used to grant security privileges on database objects tospecific users. Grant statement is normally used by the owner of the table to give accessto other users. Grant statement includes the specific list of grant privileges, the name ofthe table to which the privileges apply and the user-id to which the privileges are granted.Example:GRANT select, insert, delete, update ON Persons TO GaurishGrant privileges Table_nameUser_name PUBLIC keyword is used to give access privileges to all users. WITH GRANT OPTION clause is used to give the right to a user to grantprivileges to other users.The privileges that you have granted with the GRANT statement can be taken away withthe REVOKE statement. The REVOKE statement has a structure that closely parallelsthe GRANT statement, specifying a specific set of privileges to be taken away, for aspecific database object, from one or more user-ids.Example:REVOKE select, insert ON Persons FROM Gaurish
  16. 16. 16JOINSSQL joins are used to query data from two or more tables, based on a relationship betweencertain columns in these tables. The JOIN keyword is used in SQL statements. Two tables arerelated to each other with keys.For example: There are two tables Persons and Accounts. Both are related by a common fieldP_Id.Persons TableP_Id LastName FirstName Address City1 Goel Gaurish Gurgaon South_City12 Dash Bimal Ghaziabad Shipra_Sun_CityAccounts TableAccount_No Opening_Date P_Id5423 12-NOV-11 14561 24-JUL-12 2TYPES OF JOINS1. Inner Join (also known as Simple Join)1.1 Equi Join1.1.1 Natural Join1.1.2 Cross Join or Cartesian Join2. Outer Join2.1 Left Outer Join2.2 Right Outer Join2.3 Full Outer Join3. Self Join1. Inner Join:Inner join creates a new result table by combining column values of two tables (A and B) basedupon the join-predicate.The query compares each row of A with each row of B to find all pairs ofrows which satisfy the join-predicate. When the join-predicate is satisfied, column values foreach matched pair of rows of A and B are combined into a result row.
  17. 17. 17Example-1:SELECT FirstName, Address, P.P_Id FROM Persons P, Accounts A WHERE P.P_ID = A.P_IdExample-2:SELECT FirstName, Address, P.P_Id FROM Persons P INNER JOIN Accounts A ON WHEREP.P_ID = A.P_IdResult of both examples:FirstName Address P.IdGaurish Gurgaon 1Bimal Ghaziabad 21.1 Equi JoinAn equi-join is a specific type of comparator-based join that uses only equality comparisons inthe join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join.If columns in an equi-join have the same name then we can use USING keyword.SELECT * FROM Persons INNER JOIN Accounts USING (P_Id)1.1.1 Natural JoinA natural join is a type of equi-join where the join predicate arises implicitly by comparing allcolumns in both tables that have the same column-names in the joined tables. The resultingjoined table contains only one column for each pair of equally named columns.SELECT * FROM Persons NATURAL JOIN Accounts1.1.2 Cross or Cartesian JoinCROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, itwill produce rows which combine each row from the first table with each row from the secondtable. There are two ways of writing a cross join:SELECT * FROM Persons CROSS JOIN Accounts // Explicit Cross JoinSELECT * FROM Persons, Accounts // Implicit Cross Join
  18. 18. 18Result:P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id1 Goel Gaurish Gurgaon South_City111-JUL-92 5423 12-NOV-11 12 Dash Bimal Ghaziabad Shipra_Sun_City5423 12-NOV-11 11 Goel Gaurish Gurgaon South_City111-JUL-92 4561 24-JUL-12 22 Dash Bimal Ghaziabad Shipra_Sun_City4561 24-JUL-12 22. Outer JoinAn outer join does not require each record in the two joined tables to have a matching record.The joined table retains each record even if no other matching record exists.2.1 Left Outer JoinThe result of a left outer join (or simply left join) for table A and B always contains all records ofthe "left" table (A), even if the join-condition does not find any matching record in the "right"table (B).Persons TableP_Id LastName FirstName Address City DateOfBirth1 Goel Gaurish Gurgaon South_City1 11-JUL-922 Dash Bimal Ghaziabad Shipra_Sun_City 23-DEC-783 Preeti Chawla Gurgaon South_City2 19-OCT-854 Ravi Kanth Gurgaon DLF_City 04-MAR-86Accounts TableAccount_No Opening_Date P_Id5423 12-NOV-11 14561 24-JUL-12 26879 14-AUG-10 47809 10-JAN-11 5SELECT * FROM Persons LEFT OUTER JOIN Accounts ON Persons.P_Id =Accounts.P_Id
  19. 19. 19Result:P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id1 Goel Gaurish Gurgaon South_City111-JUL-92 5423 12-NOV-11 12 Dash Bimal Ghaziabad Shipra_Sun_City23-DEC-78 4561 24-JUL-12 23 Chawla Preeti Gurgaon South_City219-OCT-85 NULL NULL NULL4 Kanth Ravi Gurgaon DLF_City04-MAR-86 6879 14-AUG-10 42.2 Right Outer JoinA right outer join (or right join) closely resembles a left outer join, except with the treatment ofthe tables reversed. Every row from the "right" table (B) will appear in the joined table at leastonce. If no matching row from the "left" table (A) exists, NULL will appear in columns from Afor those records that have no match in B.SELECT * FROM Persons RIGHT OUTER JOIN Accounts ON Persons.P_ID =Accounts.P_IdResult:P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id1 Goel Gaurish Gurgaon South_City111-JUL-92 5423 12-NOV-11 12 Dash Bimal Ghaziabad Shipra_Sun_City23-DEC-78 4561 24-JUL-12 24 Ravi Kanth Gurgaon DLF_City04-MAR-86 6879 14-AUG-10 4NULLNULL NULL NULL NULL NULL 7809 10-JAN-11 52.3 Full Outer JoinA full outer join combines the effect of applying both left and right outer joins. Where records inthe full outer joined tables do not match, the result set will have NULL values for every columnof the table that lacks a matching row. For those records that do match, a single row will beproduced in the result set (containing fields populated from both tables).
  20. 20. 20SELECT * FROM Persons FULL OUTER JOIN Accounts ON Persons.P_Id =Accounts.P_IdResult:P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id1 Goel Gaurish Gurgaon South_City111-JUL-92 5423 12-NOV-11 12 Dash Bimal Ghaziabad Shipra_Sun_City23-DEC-78 4561 24-JUL-12 23 Chawla Preeti Gurgaon South_City219-OCT-85 NULL NULL NULL4 Ravi Kanth Gurgaon DLF_City04-MAR-86 6879 14-AUG-10 4NULLNULL NULL NULL NULL NULL 7809 10-JAN-11 53. Self JoinA self join is a join of a table to itself. This table appears twice in the FROM clause and isfollowed by table aliases that qualify column names in the join condition. To perform a self join,Oracle Database combines and returns rows of the table that satisfy the join condition.SELECT p1.FirstName, p2.Address FROM Persons p1, Persons p2 WHERE p1.P_Id =p2.P_IdResult:FirstName AddressGaurish GurgaonBimal GhaziabadChawla GurgaonKanth GurgaonALIAS(Formerly known asSYNONYMS)When selecting data from many tables, it becomes difficult to write complex queries. To solvethis problem we can create aliases (shorthand notations) and use them at the place of tablenames. Aliases were formerly known as Synonyms.
  21. 21. 21Syntax:create alias per for Personscreate alias acc for AccountsWe can also drop the created aliases:drop alias perdrop alias accVIEWSA view is a SQL query that is permanently stored in the database and assigned a name. Theresults of the stored query are visible through the view, and SQL lets you access these queryresults as if they were a real table in the database.But unlike a real table, a view does not exist inthe database as a stored set of data values.A common use of views is to restrict a users access to only selected rows or columns of a table.Types of views:1. Horizontal view2. Vertical viewHorizontal View:It restricts a user‟s access to selected rowsSyntax to create a view:Create view view_name as select column_names from table_name where some_column =some_valueExample:CREATE VIEW GGN AS SELECT * FROM Persons WHERE Address = „Gurgaon‟Result:Above example will create a view with the name “GGN” which selects only those rows whichare having „Gurgaon‟ as their Address field.Vertical View:It restricts a user‟s access to selected columnsSyntax to create a view:Create view view_name as select column_name1, column_name2, ….fromtable_nameExample:CREATE VIEW GGG AS SELECT FirstName, LastName, City FROM Persons
  22. 22. 22Result:Above example will create a view with the name “GGG” which selects specifiedcolumns.INDEXESAn index is a structure that provides rapid access to the rows of a table based on the values ofone or more columns. The DBMS uses the index as you might use the index of a book. Theindex stores data values and pointers to the rows where those data values occur. In the index thedata values are arranged in ascending or descending order, so that the DBMS can quickly searchthe index to find a particular value. It can then follow the pointer to locate the row containing thevalue. The following figure may give an idea about the indexes:There are two indexes for the PRODUCT table. One of the indexes provides access based on theDESCRIPTION column. The other provides access based on the primary key of the table, whichis a combination of the MFR_ID and PRODUCT_ID columns.When to use an index: Create index for those columns which are frequently accessed by theusers. Most DBMS products alwaysestablish an index for the primary key of a table, becausethey anticipate that access to the table will most frequently be via the primary key.
  23. 23. 23Syntax to create an index:Unique is used to specify that the combination of columns being indexed must contain a uniquevalue for every row of the table.Example:CREATE UNIQUE INDEX prsn_indx ON Persons (P_Id, LastName)TRIGGERSTriggers are those procedures stored in PL/SQL that run (fire) implicitly when any useractionoccurs. These actions include:DML - Insert, Update, DeleteDDL - Create, AlterDatabase events – logon/logoff, errors, startup/shutdownSyntax:Create trigger trigger_name on table_name for event_name (insert/update/delete) as action (SQLcommand that specifies your action)Example:CREATE TRIGGER trig1ON PersonsFOR INSERTAS UPDATE Accounts SET Accounts.P_Id = Inserted.P_Id from Accounts, InsertedDescription:The first part of the trigger tells that the trigger is to be invoked when an INSERT is attemptedon table Persons. The trigger‟s action is defined after the keyword AS. In this case the action isto update the table Accounts. The row being inserted is referred to using the pseudo-tablenameinserted within the UPDATE statements.
  24. 24. 24Note:There are two temporary tables Inserted & Deleted which are created automatically by theDBMS. These tables make our task easier while writing queries.DUAL TABLEThe DUAL table is a special one-column table present by default in all Oracle databaseinstallations. It is suitable for use in selecting a pseudo column such as SYSDATE or USER. Thetable has a single VARCHAR2(1) column called DUMMY that has a value of X.Example:Select SYSDATE from DUALSelect USER from DUALSelect 1+2+3 from DUALSCHEMASA schema is a named entity within the database and includes the definitions for:TablesViewsDomains (function like extended data types used to define columns in a table)PrivilegesCharacter Sets (database structures used to support international languages)Collations (define the sorting sequence of character sets)Translations (control how text data is converted from one character set to another)Syntax:CREATE SCHEMA schema_name AUTHORIZATION user_name CREATE(table/view/domain/character sets/collation/translation) or GRANT privilegesExample:CREATE SCHEMA GGG AUTHORIZATION GaurishCREATE TABLE People (Name varchar (30), Age number (2))CREATE TABLE Places (City varchar (30), State varchar (30))GRANT ALL PRIVILEGES ON People TO PUBLICGRANT SELECT ON Places TO Bimal
  25. 25. 25CLUSTERINGA cluster is a schema object that contains data from one or more tables, all of which have one ormore columns in common. Oracle Database stores together all the rows from all the tables thatshare the same cluster key.Use the CREATECLUSTER statement to create a cluster.Prerequisites:To create a cluster in your own schema, you must have CREATECLUSTER systemprivilege.To create a cluster in another users schema, you must have CREATEANYCLUSTERsystem privilege.Syntax:Schema: Specify the schema to contain the cluster. If you omit schema, Oracle creates thecluster in your current schema.Cluster: Specify the name of the cluster to be created. After you create a cluster, you add tablesto it. A cluster can contain a maximum of 32 tables. You can access clustered tables with SQLstatements just as you can access non-clustered tables.
  26. 26. 26Column: Specify one or more names of columns in the cluster key. You can specify up to 16cluster key columns. These columns must correspond in both datatype and size to columns ineach of the clustered tables, although they need not correspond in name.Datatype: Specify the datatype of each cluster key column.Size:Specify the amount of space in bytes reserved to store all rows with the same cluster keyvalue or the same hash value. Use K or M to specify this space in kilobytes or megabytes. Thisspace determines the maximum number of cluster or hash values stored in a data block. If SIZEis not a divisor of the data block size, Oracle uses the next largest divisor. If SIZE is larger thanthe data block size, Oracle uses the operating system block size, reserving at least one data blockfor each cluster or hash value.TableSpace:Specify the tablespace in which the cluster is created.Single Table:It specifies that the cluster contains only one table.Index Clause:Specify INDEX to create an indexedcluster. In an indexed cluster, Oracle storestogether rows having the same cluster key value. Each distinct cluster key value is stored onlyonce in each data block, regardless of the number of tables and rows in which it occurs.After you create an indexed cluster, you must create an index on the cluster key before you canissue any data manipulation language (DML) statements against a table in the cluster. This indexis called the cluster index.HashKeys Clause:Specify the HASHKEYS clause to create a hash cluster and specify thenumber of hash values for a hash cluster. In a hash cluster, Oracle stores together rows that havethe same hash key value. The hash value for a row is the value returned by the clusters hashfunction.Parallel clause: The parallel_clause lets you parallelize the creation of the cluster.
  27. 27. 27SYSTEM TABLESSystem tables provide information regarding the structure of the database itself. Each vendor hasits own structure for these tables. System tables are owned by SYS user. Some examples ofsystem tables are:AW$ (Maintains a record of all analytic workspaces in the database, recording its name,owner, and other information)AW_Obj$ (Describes the objects stored in analytic workspaces), etc.SYSTEM CATALOGSThe catalog is a collection of named database schemas. The catalog also contains a set of systemtables (confusingly, often called the "system catalog") that describe the structure of the database.The system catalog is a collection of special tables in a database that are owned, created, andmaintained by the DBMS itself. These system tables contain data that describes the structure ofthe database. The tables in the system catalog are automatically created when the database iscreated.The DBMS constantly refers to the data in the system catalog while processing SQL statements.For example, to process a two-table SELECT statement, the DBMS must:Verify that the two named tables actually exist.Ensure that the user has permission to access them.Check whether the columns referenced in the query exist.Resolve any unqualified column names to one of the tables.Determine the data type of each column.
  28. 28. 28EXPLAIN PLANSThe EXPLAINPLAN statement displays execution plans chosen by the optimizer for SELECT,UPDATE, INSERT, and DELETE statements. A statement execution plan is the sequence ofoperations that the database performs to run the statement.The row source tree is the core of the execution plan. The tree shows the following information:An ordering of the tables referenced by the statementAn access method for each table mentioned in the statementA join method for tables affected by join operations in the statementData operations like filter, sort, or aggregationIn addition to the row source tree, the plan table contains information about the following:Optimization, such as the cost and cardinality of each operationPartitioning, such as the set of accessed partitionsParallel execution, such as the distribution method of join inputsThe EXPLAINPLAN results let you determine whether the optimizer selects a particularexecution plan, such as, nested loops join. The results also help you to understand the optimizerdecisions, such as why the optimizer chose a nested loops join instead of a hash join, and letsyou understand the performance of a query.Execution plans can differ due to the following:Different SchemasDifferent CostsDifferent Schemas:The execution and explain plan occur on different databases.The user explaining the statement is different from the user running the statement. Twousers might be pointing to different objects in the same database, resulting in differentexecution plans.Schema changes (usually changes in indexes) between the two operations.Different Costs:Even if the schemas are the same, the optimizer can choose different execution plans when thecosts are different. Some factors that affect the costs include the following:Data volume and statisticsBind variable types and valuesInitialization parameters set globally or at session levelExplain Plan Restrictions: Oracle Database does not support EXPLAINPLAN for statementsperforming implicit type conversion of date bind variables. With bind variables in general, theEXPLAINPLAN output might not represent the real execution plan.
  29. 29. 29Figure -1Figure -2
  30. 30. 30Figure – 1Select * from PS_DEMAND_PHYS_INV where business_unit = EURLCIn figure – 1 only one condition is given which is resulting in FULL SCAN and ahigh cost and hence poor performance. We should take care that full scan doesn‟toccur in the execution plan of a query.Figure – 2Select * from PS_DEMAND_PHYS_INV where business_unit = EURLC and order_no =0002104289;While in figure – 2 two conditions are there which results in a tremendous decreasein cost and good performance.
  31. 31. 31APPENDICESAALIAS 21BBUILT-IN FUNCTIONS 10CCLUSTERING 25DDATA TYPES(ORACLE Specific)Character Data Types 8(ORACLE SPECIFIC)DATE Data type 9LOB Data Types 9Numeric Data Types 8DATA TYPES: (ORACLE Specific) 8Database Architecture 4Multi-Database Architecture 4Multi-Location Architecture 5Single-Database Architecture 4DUAL TABLE 24EEqui JoinCross or Cartesian Join 17Natural Join 17EXPLAIN PLANS 28IINDEXES 22Inner JoinEqui Join 17JJOINS 16OOuter JoinFull Outer Join 20Left Outer Join 18Right Outer Join 19SSCHEMAS 24SQL – Introduction 3SQL Commands with Example 11SYSTEM CATALOGS 27SYSTEM TABLES 27TTRIGGERS 23Types of Commands in SQL 11DCL 11DDL 11DML 11TCL 11TYPES OF JOINS 16Inner Join 16Outer Join 18Self Join 20Types of Keys in SQL 6Composite Primary Key 7Foreign Key 6Primary Key 6Unique Key 6VVIEWS 21Horizontal View 21Vertical View 22

×