SlideShare une entreprise Scribd logo
1  sur  31
1
SQL
(Structured Query Language)
CREATED BY:-
Gaurish Gopal Goel
PeopleSoft Trainee
AEQUOR INFORMATION TECHNOLOGIES
17th
October 2012
2
CONTENTS
TOPIC PAGE NO.
SQL – Introduction………………………………………………………………………….3
Database Architecture……………………………………………………………………….4-6
Single-Database Architecture
Multiple Database Architecture
Multi-Location Architecture
Types of Keys in SQL……………………………………………………………………….6-7
Primary Key
Unique Key
Foreign Key
Composite Primary Key
DATA TYPES: (ORACLE Specific)………………………………………………………..8-9
Character
Numeric
DATE
LOB
BUILT-IN FUNCTIONS…………………………………………………………………….10
Types of Commands in SQL…………………………………………………………………11-15
DDL
DML
DCL
TCL
JOINS………………………………………………………………………………………...16
TYPES OF JOINS……………………………………………………………………………16-20
Inner Join
 Equi Join
 Natural Join
 Cross or Cartesian Join
Outer Join
 Left Outer Join
 Right Outer Join
 Full Outer Join
Self Join
ALIAS………………………………………………………………………………………..21
VIEWS……………………………………………………………………………………….21-22
Horizontal View
Vertical View
INDEXES…………………………………………………………………………………….22-23
TRIGGERS…………………………………………………………………………………...23-24
DUAL TABLE………………………………………………………………………………..24
SCHEMAS…………………………………………………………………………………...24-25
CLUSTERING……………………………………………………………………………….25-26
SYSTEM TABLES…………………………………………………………………………...27
SYSTEM CATALOGS……………………………………………………………………….27
EXPLAIN PLANS……………………………………………………………………………28-30
3
SQL – Introduction
SQL is a tool for organizing, managing, and retrieving data stored by a computer database. The
name "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 and
relationships among the stored data items.
• Data retrieval: SQL allows a user or an application program to retrieve stored datafrom the
database and use it.
• Data manipulation: SQL allows a user or an application program to update the database by
adding new data, removing old data, and modifying previously storeddata.
• Access control: SQL can be used to restrict a user's 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 they
do not interfere with one another.
• Data integrity: SQL defines integrity constraints in the database, protecting it fromcorruption
due to inconsistent updates or system failures.
4
Database Architecture
Architecture describes the structure of the contents of the database specified by SQL1 Standard.
There are two types of architecture:
1. Single-Database Architecture
2. Multiple-Database Architecture
3. Multi-Location Architecture
Single-Database Architecture:
Above figure shows singledatabase architecture where DBMS supports one systemwide
database. Examples of such databases are: DB2, Oracle etc.
An advantage of this architecture is that the tables in the various applications can easily
reference one another.
A disadvantage of this architecture is that the database will grow huge over time as more and
more applications are added to it. The problems of managing a database of that size - performing
backups, recovering data, analyzing performance, and so onusually require a full-time database
administrator.
Multi-Database Architecture:
The below figure clearly shows three different databases with a unique name assigned to each of
the 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 is
that it divides the data management tasks into smaller, more manageable pieces.
The main disadvantage of the multi-database architecture is that the individual databases may
become unconnected to one another. Typically a table in one database cannot contain a foreign
key reference to a table in a different database. Often the DBMS does not support queries across
database boundaries, making it impossible to relate data from two applications.
5
Multi-Location Architecture:
Multiple
databases
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. In
addition there is one more drawback i.e. there is no master database that keeps track of all the
databases where they are located in the system‟s directory.
Types of Keys in SQL
Keys are those fields which are used to uniquely identify the records in a database. The
following 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 field
uniquely 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 table
is called a foreign key.
 Can accept NULL as well as duplicate values.
7
 The CUST column is a foreign key for the CUSTOMERS table, relating each
order to the customer who placed it.
 The REP column is a foreign key for the SALESREPS table, relating each order
to the salesperson who took it.
 The MFR and PRODUCT columns together are a composite foreign key for the
PRODUCTS 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 and
PRODUCT_ID are combined to act as primary key.
8
DATA TYPES: (ORACLE Specific)
Data types are broadly classified into:
1. Character data types
2. Numeric data types
3. Date data types
4. LOB data types
Character 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-130
to 9.99...9 x 10125
with up to 38 significant
digits.
Negative numbers from -1 x 10-130
to 9.99...99 x 10125
with 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 no
scale is specified, the scale is zero.
You can specify a scale and no precision:
 column_name NUMBER (*, scale)
9
2. Floating-Point Numbers:
There are two numeric data types for floating-point numbers:
 BINARY_FLOAT (32-bit, single-precision floating-point number
datatype)
 BINARY_DOUBLE(64-bit, double-precision floating-point number
datatype)
Use binary precision that enables faster arithmetic calculations and usually reduces
storage 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 function
with 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 manipulate
large blocks of unstructured data (such as text, graphic images, video clips, and sound
waveforms) 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
BUILT-IN FUNCTIONS
FUNCTION RETURNS
BIT_LENGTH (string)Number of bits in a bit string
CAST (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 string
CONVERT (String USINGconv)String converted as specified by a named
conversionmethod
CURRENT_DATECurrent date
CURRENT_TIME (precision)Current time with the specified precision
EXTRACT (part FROM source)Specified part (Day, Hour, etc.) from a DATETIME
value
LOWER (string)String converted to all lower case letters.
OCTET_LENGTH (string)Number of 8-bit bytes in a character string
POSITION (target IN source)Position where the target string appears in the source
string
SUBSTRING (source FROM n FOR len)A portion of the source string, beginning at the n-th
character, for a length of len
TRANSLATE (string USING trans) String translated as specified by a named translation
Function
TRIM (BOTH char FROM string) String with both leading and trailing occurrences of
char trimmed off
TRIM (LEADING char FROM string)String with any leading occurrences of
char trimmed off
TRIM (TRAILING char FROM string) String with any trailing occurrences of
char trimmed off
UPPER (string)String converted to all uppercase letters
Note:There are some column functions in SQL such as: SUM ( ), AVG ( ), MIN ( ), MAX ( ),
COUNT ( ), COUNT (*)
11
Types of Commands in SQL
1. 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 table
2. 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 data
3. DCL (Data Control Language)
 Grant – Grants user access privileges
 Revoke – Removes user access privileges
4. TCL (Transaction Control Language)
 Commit – Ends the current transaction
 Rollback – Aborts the current transaction
SQLCommands with Example:
1. CREATE TABLE
Syntax:
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
CONSTRAINT person_pk PRIMARY KEY (P_Id)
)
Result:
P_Id LastName FirstName Address City
We can also make more than one columns as our primary keys under one constraint
name.
2. INSERT INTO
Syntax:
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 City
1 Goel Gaurish Gurgaon South_City1
2 Dash Bimal Ghaziabad Shipra_Sun_city
3 Chawla Preeti Gurgaon South_City2
3. ALTER TABLE
Syntax:
ALTER TABLE table_name MODIFY column_namedatatype
Example:
ALTER TABLE Persons ADD DateOfBirth date
13
Result:
P_Id LastName FirstName Address City DateOfBirth
1 Goel Gaurish Gurgaon South_City1
2 Dash Bimal Ghaziabad Shipra_Sun_city
3 Chawla Preeti Gurgaon South_City2
We can also drop a column using this command : ALTER TABLE Persons DROP
COLUMN DateOfBirth
4. UPDATE
Syntax:
UPDATE table_name SET column1=value, column2=value2 ...
WHERE some_column=some_value
Example:
UPDATE Persons SET DateOfBirth=‟11-JUL-92‟ WHERE
FirstName=‟Gaurish‟ AND LastName=‟Goel‟
Result:
P_Id LastName FirstName Address City DateOfBirth
1 Goel Gaurish Gurgaon South_City1 11-JUL-92
2 Dash Bimal Ghaziabad Shipra_Sun_city
3 Chawla Preeti Gurgaon South_City2
While using UPDATE command make sure that you don‟t forget to put WHERE clause
otherwise all the rows will be updated.
5. DELETE FROM
Syntax:
DELETE FROM table_name WHERE some_column=some_value
Example:
DELETE FROM Persons WHERE LastName='Chawla' AND
FirstName='Preeti'
 TRUNCATE is used to delete all rows in a table. It is a DDL commandand this
action cannot be rolled back.
14
Result:
P_Id LastName FirstName Address City DateOfBirth
1 Goel Gaurish Gurgaon South_City1 11-JUL-92
2 Dash Bimal Ghaziabad Shipra_Sun_city
To delete all rows use this command : DELETE * FROMtable_name
6. SELECT
Syntax:
SELECT * FROM table_name
SELECT column_name1, column_name2,….. FROM table_name
WHERE some_column = some_value
Example:
SELECT FirstName, LastName, DateOfBirth FROM Persons WHERE
Address = „Gurgaon‟
Result:
FirstName LastName DateOfBirth
Gaurish Goel 11-JUL-92
7. DROP TABLE
Syntax:
DROP TABLE table_name
Example:
DROP TABLE Persons
8. COMMITand ROLLBACK
SQL supports database transactions through two SQL transaction processing statements:
The COMMIT statement signals the successful end of a transaction. It tells the DBMS
that the transaction is now complete; all of the statements that comprise the transaction
have been executed, and the database is self-consistent.
The ROLLBACK statement signals the unsuccessful end of a transaction. It tells the
DBMS that the user does not want to complete the transaction; instead, the DBMS should
15
back out any changes made to the database during the transaction. In effect, the DBMS
restores the database to its state before the transaction began.
9. GRANT and REVOKE
The basic GRANTstatement is used to grant security privileges on database objects to
specific users. Grant statement is normally used by the owner of the table to give access
to other users. Grant statement includes the specific list of grant privileges, the name of
the 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 Gaurish
Grant 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 grant
privileges to other users.
The privileges that you have granted with the GRANT statement can be taken away with
the REVOKE statement. The REVOKE statement has a structure that closely parallels
the GRANT statement, specifying a specific set of privileges to be taken away, for a
specific database object, from one or more user-ids.
Example:
REVOKE select, insert ON Persons FROM Gaurish
16
JOINS
SQL joins are used to query data from two or more tables, based on a relationship between
certain columns in these tables. The JOIN keyword is used in SQL statements. Two tables are
related to each other with keys.
For example: There are two tables Persons and Accounts. Both are related by a common field
P_Id.
Persons Table
P_Id LastName FirstName Address City
1 Goel Gaurish Gurgaon South_City1
2 Dash Bimal Ghaziabad Shipra_Sun_City
Accounts Table
Account_No Opening_Date P_Id
5423 12-NOV-11 1
4561 24-JUL-12 2
TYPES OF JOINS
1. Inner Join (also known as Simple Join)
1.1 Equi Join
1.1.1 Natural Join
1.1.2 Cross Join or Cartesian Join
2. Outer Join
2.1 Left Outer Join
2.2 Right Outer Join
2.3 Full Outer Join
3. Self Join
1. Inner Join:
Inner join creates a new result table by combining column values of two tables (A and B) based
upon the join-predicate.The query compares each row of A with each row of B to find all pairs of
rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for
each matched pair of rows of A and B are combined into a result row.
17
Example-1:
SELECT FirstName, Address, P.P_Id FROM Persons P, Accounts A WHERE P.P_ID = A.P_Id
Example-2:
SELECT FirstName, Address, P.P_Id FROM Persons P INNER JOIN Accounts A ON WHERE
P.P_ID = A.P_Id
Result of both examples:
FirstName Address P.Id
Gaurish Gurgaon 1
Bimal Ghaziabad 2
1.1 Equi Join
An equi-join is a specific type of comparator-based join that uses only equality comparisons in
the 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 Join
A natural join is a type of equi-join where the join predicate arises implicitly by comparing all
columns in both tables that have the same column-names in the joined tables. The resulting
joined table contains only one column for each pair of equally named columns.
SELECT * FROM Persons NATURAL JOIN Accounts
1.1.2 Cross or Cartesian Join
CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it
will produce rows which combine each row from the first table with each row from the second
table. There are two ways of writing a cross join:
SELECT * FROM Persons CROSS JOIN Accounts // Explicit Cross Join
SELECT * FROM Persons, Accounts // Implicit Cross Join
18
Result:
P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id
1 Goel Gaurish Gurgaon South_C
ity1
11-JUL-92 5423 12-NOV-11 1
2 Dash Bimal Ghaziabad Shipra_
Sun_Cit
y
5423 12-NOV-11 1
1 Goel Gaurish Gurgaon South_C
ity1
11-JUL-92 4561 24-JUL-12 2
2 Dash Bimal Ghaziabad Shipra_
Sun_Cit
y
4561 24-JUL-12 2
2. Outer Join
An 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 Join
The result of a left outer join (or simply left join) for table A and B always contains all records of
the "left" table (A), even if the join-condition does not find any matching record in the "right"
table (B).
Persons Table
P_Id LastName FirstName Address City DateOfBirth
1 Goel Gaurish Gurgaon South_City1 11-JUL-92
2 Dash Bimal Ghaziabad Shipra_Sun_City 23-DEC-78
3 Preeti Chawla Gurgaon South_City2 19-OCT-85
4 Ravi Kanth Gurgaon DLF_City 04-MAR-86
Accounts Table
Account_No Opening_Date P_Id
5423 12-NOV-11 1
4561 24-JUL-12 2
6879 14-AUG-10 4
7809 10-JAN-11 5
SELECT * FROM Persons LEFT OUTER JOIN Accounts ON Persons.P_Id =
Accounts.P_Id
19
Result:
P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id
1 Goel Gaurish Gurgaon South_C
ity1
11-JUL-92 5423 12-NOV-11 1
2 Dash Bimal Ghaziabad Shipra_
Sun_Cit
y
23-DEC-78 4561 24-JUL-12 2
3 Chawla Preeti Gurgaon South_C
ity2
19-OCT-85 NULL NULL NUL
L
4 Kanth Ravi Gurgaon DLF_Ci
ty
04-MAR-86 6879 14-AUG-10 4
2.2 Right Outer Join
A right outer join (or right join) closely resembles a left outer join, except with the treatment of
the tables reversed. Every row from the "right" table (B) will appear in the joined table at least
once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A
for those records that have no match in B.
SELECT * FROM Persons RIGHT OUTER JOIN Accounts ON Persons.P_ID =
Accounts.P_Id
Result:
P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id
1 Goel Gaurish Gurgaon South_C
ity1
11-JUL-92 5423 12-NOV-11 1
2 Dash Bimal Ghaziabad Shipra_
Sun_Cit
y
23-DEC-78 4561 24-JUL-12 2
4 Ravi Kanth Gurgaon DLF_Ci
ty
04-MAR-86 6879 14-AUG-10 4
NUL
L
NULL NULL NULL NULL NULL 7809 10-JAN-11 5
2.3 Full Outer Join
A full outer join combines the effect of applying both left and right outer joins. Where records in
the full outer joined tables do not match, the result set will have NULL values for every column
of the table that lacks a matching row. For those records that do match, a single row will be
produced in the result set (containing fields populated from both tables).
20
SELECT * FROM Persons FULL OUTER JOIN Accounts ON Persons.P_Id =
Accounts.P_Id
Result:
P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id
1 Goel Gaurish Gurgaon South_C
ity1
11-JUL-92 5423 12-NOV-11 1
2 Dash Bimal Ghaziabad Shipra_
Sun_Cit
y
23-DEC-78 4561 24-JUL-12 2
3 Chawla Preeti Gurgaon South_C
ity2
19-OCT-85 NULL NULL NUL
L
4 Ravi Kanth Gurgaon DLF_Ci
ty
04-MAR-86 6879 14-AUG-10 4
NUL
L
NULL NULL NULL NULL NULL 7809 10-JAN-11 5
3. Self Join
A self join is a join of a table to itself. This table appears twice in the FROM clause and is
followed 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_Id
Result:
FirstName Address
Gaurish Gurgaon
Bimal Ghaziabad
Chawla Gurgaon
Kanth Gurgaon
ALIAS(Formerly known asSYNONYMS)
When selecting data from many tables, it becomes difficult to write complex queries. To solve
this problem we can create aliases (shorthand notations) and use them at the place of table
names. Aliases were formerly known as Synonyms.
21
Syntax:
create alias per for Persons
create alias acc for Accounts
We can also drop the created aliases:
drop alias per
drop alias acc
VIEWS
A view is a SQL query that is permanently stored in the database and assigned a name. The
results of the stored query are visible through the view, and SQL lets you access these query
results as if they were a real table in the database.But unlike a real table, a view does not exist in
the database as a stored set of data values.
A common use of views is to restrict a user's access to only selected rows or columns of a table.
Types of views:
1. Horizontal view
2. Vertical view
Horizontal View:
It restricts a user‟s access to selected rows
Syntax to create a view:
Create view view_name as select column_names from table_name where some_column =
some_value
Example:
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 which
are having „Gurgaon‟ as their Address field.
Vertical View:
It restricts a user‟s access to selected columns
Syntax to create a view:
Create view view_name as select column_name1, column_name2, ….fromtable_name
Example:
CREATE VIEW GGG AS SELECT FirstName, LastName, City FROM Persons
22
Result:
Above example will create a view with the name “GGG” which selects specifiedcolumns.
INDEXES
An index is a structure that provides rapid access to the rows of a table based on the values of
one or more columns. The DBMS uses the index as you might use the index of a book. The
index stores data values and pointers to the rows where those data values occur. In the index the
data values are arranged in ascending or descending order, so that the DBMS can quickly search
the index to find a particular value. It can then follow the pointer to locate the row containing the
value. 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 the
DESCRIPTION column. The other provides access based on the primary key of the table, which
is 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 the
users. Most DBMS products alwaysestablish an index for the primary key of a table, because
they anticipate that access to the table will most frequently be via the primary key.
23
Syntax to create an index:
Unique is used to specify that the combination of columns being indexed must contain a unique
value for every row of the table.
Example:
CREATE UNIQUE INDEX prsn_indx ON Persons (P_Id, LastName)
TRIGGERS
Triggers are those procedures stored in PL/SQL that run (fire) implicitly when any user
actionoccurs. These actions include:
DML - Insert, Update, Delete
DDL - Create, Alter
Database events – logon/logoff, errors, startup/shutdown
Syntax:
Create trigger trigger_name on table_name for event_name (insert/update/delete) as action (SQL
command that specifies your action)
Example:
CREATE TRIGGER trig1
ON Persons
FOR INSERT
AS UPDATE Accounts SET Accounts.P_Id = Inserted.P_Id from Accounts, Inserted
Description:
The first part of the trigger tells that the trigger is to be invoked when an INSERT is attempted
on table Persons. The trigger‟s action is defined after the keyword AS. In this case the action is
to update the table Accounts. The row being inserted is referred to using the pseudo-table
nameinserted within the UPDATE statements.
24
Note:There are two temporary tables Inserted & Deleted which are created automatically by the
DBMS. These tables make our task easier while writing queries.
DUAL TABLE
The DUAL table is a special one-column table present by default in all Oracle database
installations. It is suitable for use in selecting a pseudo column such as SYSDATE or USER. The
table has a single VARCHAR2(1) column called DUMMY that has a value of 'X'.
Example:
Select SYSDATE from DUAL
Select USER from DUAL
Select 1+2+3 from DUAL
SCHEMAS
A schema is a named entity within the database and includes the definitions for:
Tables
Views
Domains (function like extended data types used to define columns in a table)
Privileges
Character 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 privileges
Example:
CREATE SCHEMA GGG AUTHORIZATION Gaurish
CREATE TABLE People (Name varchar (30), Age number (2))
CREATE TABLE Places (City varchar (30), State varchar (30))
GRANT ALL PRIVILEGES ON People TO PUBLIC
GRANT SELECT ON Places TO Bimal
25
CLUSTERING
A cluster is a schema object that contains data from one or more tables, all of which have one or
more columns in common. Oracle Database stores together all the rows from all the tables that
share 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 system
privilege.
To create a cluster in another user's schema, you must have CREATEANYCLUSTER
system privilege.
Syntax:
Schema: Specify the schema to contain the cluster. If you omit schema, Oracle creates the
cluster in your current schema.
Cluster: Specify the name of the cluster to be created. After you create a cluster, you add tables
to it. A cluster can contain a maximum of 32 tables. You can access clustered tables with SQL
statements just as you can access non-clustered tables.
26
Column: Specify one or more names of columns in the cluster key. You can specify up to 16
cluster key columns. These columns must correspond in both datatype and size to columns in
each 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 key
value or the same hash value. Use K or M to specify this space in kilobytes or megabytes. This
space determines the maximum number of cluster or hash values stored in a data block. If SIZE
is not a divisor of the data block size, Oracle uses the next largest divisor. If SIZE is larger than
the data block size, Oracle uses the operating system block size, reserving at least one data block
for 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 stores
together rows having the same cluster key value. Each distinct cluster key value is stored only
once 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 can
issue any data manipulation language (DML) statements against a table in the cluster. This index
is called the cluster index.
HashKeys Clause:Specify the HASHKEYS clause to create a hash cluster and specify the
number of hash values for a hash cluster. In a hash cluster, Oracle stores together rows that have
the same hash key value. The hash value for a row is the value returned by the cluster's hash
function.
Parallel clause: The parallel_clause lets you parallelize the creation of the cluster.
27
SYSTEM TABLES
System tables provide information regarding the structure of the database itself. Each vendor has
its own structure for these tables. System tables are owned by SYS user. Some examples of
system 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 CATALOGS
The catalog is a collection of named database schemas. The catalog also contains a set of system
tables (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, and
maintained by the DBMS itself. These system tables contain data that describes the structure of
the database. The tables in the system catalog are automatically created when the database is
created.
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
EXPLAIN PLANS
The EXPLAINPLAN statement displays execution plans chosen by the optimizer for SELECT,
UPDATE, INSERT, and DELETE statements. A statement execution plan is the sequence of
operations 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 statement
An access method for each table mentioned in the statement
A join method for tables affected by join operations in the statement
Data operations like filter, sort, or aggregation
In addition to the row source tree, the plan table contains information about the following:
Optimization, such as the cost and cardinality of each operation
Partitioning, such as the set of accessed partitions
Parallel execution, such as the distribution method of join inputs
The EXPLAINPLAN results let you determine whether the optimizer selects a particular
execution plan, such as, nested loops join. The results also help you to understand the optimizer
decisions, such as why the optimizer chose a nested loops join instead of a hash join, and lets
you understand the performance of a query.
Execution plans can differ due to the following:
Different Schemas
Different Costs
Different Schemas:
The execution and explain plan occur on different databases.
The user explaining the statement is different from the user running the statement. Two
users might be pointing to different objects in the same database, resulting in different
execution 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 the
costs are different. Some factors that affect the costs include the following:
Data volume and statistics
Bind variable types and values
Initialization parameters set globally or at session level
Explain Plan Restrictions: Oracle Database does not support EXPLAINPLAN for statements
performing implicit type conversion of date bind variables. With bind variables in general, the
EXPLAINPLAN output might not represent the real execution plan.
29
Figure -1
Figure -2
30
Figure – 1
Select * from PS_DEMAND_PHYS_INV where business_unit = 'EURLC'
In figure – 1 only one condition is given which is resulting in FULL SCAN and a
high cost and hence poor performance. We should take care that full scan doesn‟t
occur in the execution plan of a query.
Figure – 2
Select * 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 decrease
in cost and good performance.
31
APPENDICES
A
ALIAS 21
B
BUILT-IN FUNCTIONS 10
C
CLUSTERING 25
D
DATA TYPES
(ORACLE Specific)
Character Data Types 8
(ORACLE SPECIFIC)
DATE Data type 9
LOB Data Types 9
Numeric Data Types 8
DATA TYPES: (ORACLE Specific) 8
Database Architecture 4
Multi-Database Architecture 4
Multi-Location Architecture 5
Single-Database Architecture 4
DUAL TABLE 24
E
Equi Join
Cross or Cartesian Join 17
Natural Join 17
EXPLAIN PLANS 28
I
INDEXES 22
Inner Join
Equi Join 17
J
JOINS 16
O
Outer Join
Full Outer Join 20
Left Outer Join 18
Right Outer Join 19
S
SCHEMAS 24
SQL – Introduction 3
SQL Commands with Example 11
SYSTEM CATALOGS 27
SYSTEM TABLES 27
T
TRIGGERS 23
Types of Commands in SQL 11
DCL 11
DDL 11
DML 11
TCL 11
TYPES OF JOINS 16
Inner Join 16
Outer Join 18
Self Join 20
Types of Keys in SQL 6
Composite Primary Key 7
Foreign Key 6
Primary Key 6
Unique Key 6
V
VIEWS 21
Horizontal View 21
Vertical View 22

Contenu connexe

Tendances

What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?CPD INDIA
 
Intro to T-SQL - 1st session
Intro to T-SQL - 1st sessionIntro to T-SQL - 1st session
Intro to T-SQL - 1st sessionMedhat Dawoud
 
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Massimo Cenci
 
MDF and LDF in SQL Server
MDF and LDF in SQL ServerMDF and LDF in SQL Server
MDF and LDF in SQL ServerMasum Reza
 
Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)
Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)
Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)Massimo Cenci
 
Sql server difference faqs- 6
Sql server difference faqs- 6Sql server difference faqs- 6
Sql server difference faqs- 6Umar Ali
 
PHP - Getting good with MySQL part I
PHP - Getting good with MySQL part IPHP - Getting good with MySQL part I
PHP - Getting good with MySQL part IFirdaus Adib
 
Sql a practical introduction
Sql   a practical introductionSql   a practical introduction
Sql a practical introductionHasan Kata
 
Intro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionIntro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionMedhat Dawoud
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuingGurpreet singh
 
Sql server lesson3
Sql server lesson3Sql server lesson3
Sql server lesson3Ala Qunaibi
 
File handling in qbasic
File handling in qbasicFile handling in qbasic
File handling in qbasicSmritiGurung4
 

Tendances (18)

What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?
 
Sql 2009
Sql 2009Sql 2009
Sql 2009
 
Intro to T-SQL - 1st session
Intro to T-SQL - 1st sessionIntro to T-SQL - 1st session
Intro to T-SQL - 1st session
 
Files
FilesFiles
Files
 
Sq lite module5
Sq lite module5Sq lite module5
Sq lite module5
 
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
 
MDF and LDF in SQL Server
MDF and LDF in SQL ServerMDF and LDF in SQL Server
MDF and LDF in SQL Server
 
Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)
Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)
Recipe 14 - Build a Staging Area for an Oracle Data Warehouse (2)
 
Sql server difference faqs- 6
Sql server difference faqs- 6Sql server difference faqs- 6
Sql server difference faqs- 6
 
DBMS Practical File
DBMS Practical FileDBMS Practical File
DBMS Practical File
 
PHP - Getting good with MySQL part I
PHP - Getting good with MySQL part IPHP - Getting good with MySQL part I
PHP - Getting good with MySQL part I
 
DBMS
DBMSDBMS
DBMS
 
Sql a practical introduction
Sql   a practical introductionSql   a practical introduction
Sql a practical introduction
 
Mysql database
Mysql databaseMysql database
Mysql database
 
Intro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionIntro to T-SQL – 2nd session
Intro to T-SQL – 2nd session
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuing
 
Sql server lesson3
Sql server lesson3Sql server lesson3
Sql server lesson3
 
File handling in qbasic
File handling in qbasicFile handling in qbasic
File handling in qbasic
 

En vedette

oracle joins and sql joins
oracle joins and sql joinsoracle joins and sql joins
oracle joins and sql joinsshripal singh
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joinsredro
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Serverprogrammings guru
 

En vedette (6)

oracle joins and sql joins
oracle joins and sql joinsoracle joins and sql joins
oracle joins and sql joins
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joins
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
SQL Joins
SQL JoinsSQL Joins
SQL Joins
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 

Similaire à SQL, Oracle, Joins

Similaire à SQL, Oracle, Joins (20)

Oracle
OracleOracle
Oracle
 
Dbmsunit v
Dbmsunit vDbmsunit v
Dbmsunit v
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
SQL
SQLSQL
SQL
 
SQL
SQLSQL
SQL
 
SQL Tutorial
SQL TutorialSQL Tutorial
SQL Tutorial
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
PO WER - Piotr Mariat - Sql
PO WER - Piotr Mariat - SqlPO WER - Piotr Mariat - Sql
PO WER - Piotr Mariat - Sql
 
Sql server
Sql serverSql server
Sql server
 
Unit 3 rdbms study_materials-converted
Unit 3  rdbms study_materials-convertedUnit 3  rdbms study_materials-converted
Unit 3 rdbms study_materials-converted
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEM
 
Sql material
Sql materialSql material
Sql material
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
Sql and mysql database concepts
Sql and mysql database conceptsSql and mysql database concepts
Sql and mysql database concepts
 
Data massage! databases scaled from one to one million nodes (ulf wendel)
Data massage! databases scaled from one to one million nodes (ulf wendel)Data massage! databases scaled from one to one million nodes (ulf wendel)
Data massage! databases scaled from one to one million nodes (ulf wendel)
 
Oracle's history
Oracle's historyOracle's history
Oracle's history
 
SQL cheat sheet.pdf
SQL cheat sheet.pdfSQL cheat sheet.pdf
SQL cheat sheet.pdf
 
Introduction DBMS, RDBMS and SQL
Introduction DBMS, RDBMS and SQLIntroduction DBMS, RDBMS and SQL
Introduction DBMS, RDBMS and SQL
 

Dernier

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 

Dernier (20)

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 

SQL, Oracle, Joins

  • 1. 1 SQL (Structured Query Language) CREATED BY:- Gaurish Gopal Goel PeopleSoft Trainee AEQUOR INFORMATION TECHNOLOGIES 17th October 2012
  • 2. 2 CONTENTS TOPIC PAGE NO. SQL – Introduction………………………………………………………………………….3 Database Architecture……………………………………………………………………….4-6 Single-Database Architecture Multiple Database Architecture Multi-Location Architecture Types of Keys in SQL……………………………………………………………………….6-7 Primary Key Unique Key Foreign Key Composite Primary Key DATA TYPES: (ORACLE Specific)………………………………………………………..8-9 Character Numeric DATE LOB BUILT-IN FUNCTIONS…………………………………………………………………….10 Types of Commands in SQL…………………………………………………………………11-15 DDL DML DCL TCL JOINS………………………………………………………………………………………...16 TYPES OF JOINS……………………………………………………………………………16-20 Inner Join  Equi Join  Natural Join  Cross or Cartesian Join Outer Join  Left Outer Join  Right Outer Join  Full Outer Join Self Join ALIAS………………………………………………………………………………………..21 VIEWS……………………………………………………………………………………….21-22 Horizontal View Vertical View INDEXES…………………………………………………………………………………….22-23 TRIGGERS…………………………………………………………………………………...23-24 DUAL TABLE………………………………………………………………………………..24 SCHEMAS…………………………………………………………………………………...24-25 CLUSTERING……………………………………………………………………………….25-26 SYSTEM TABLES…………………………………………………………………………...27 SYSTEM CATALOGS……………………………………………………………………….27 EXPLAIN PLANS……………………………………………………………………………28-30
  • 3. 3 SQL – Introduction SQL is a tool for organizing, managing, and retrieving data stored by a computer database. The name "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 and relationships among the stored data items. • Data retrieval: SQL allows a user or an application program to retrieve stored datafrom the database and use it. • Data manipulation: SQL allows a user or an application program to update the database by adding new data, removing old data, and modifying previously storeddata. • Access control: SQL can be used to restrict a user's 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 they do not interfere with one another. • Data integrity: SQL defines integrity constraints in the database, protecting it fromcorruption due to inconsistent updates or system failures.
  • 4. 4 Database Architecture Architecture describes the structure of the contents of the database specified by SQL1 Standard. There are two types of architecture: 1. Single-Database Architecture 2. Multiple-Database Architecture 3. Multi-Location Architecture Single-Database Architecture: Above figure shows singledatabase architecture where DBMS supports one systemwide database. Examples of such databases are: DB2, Oracle etc. An advantage of this architecture is that the tables in the various applications can easily reference one another. A disadvantage of this architecture is that the database will grow huge over time as more and more applications are added to it. The problems of managing a database of that size - performing backups, recovering data, analyzing performance, and so onusually require a full-time database administrator. Multi-Database Architecture: The below figure clearly shows three different databases with a unique name assigned to each of the 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 is that it divides the data management tasks into smaller, more manageable pieces. The main disadvantage of the multi-database architecture is that the individual databases may become unconnected to one another. Typically a table in one database cannot contain a foreign key reference to a table in a different database. Often the DBMS does not support queries across database boundaries, making it impossible to relate data from two applications.
  • 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. In addition there is one more drawback i.e. there is no master database that keeps track of all the databases where they are located in the system‟s directory. Types of Keys in SQL Keys are those fields which are used to uniquely identify the records in a database. The following 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 field uniquely 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 table is called a foreign key.  Can accept NULL as well as duplicate values.
  • 7. 7  The CUST column is a foreign key for the CUSTOMERS table, relating each order to the customer who placed it.  The REP column is a foreign key for the SALESREPS table, relating each order to the salesperson who took it.  The MFR and PRODUCT columns together are a composite foreign key for the PRODUCTS 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 and PRODUCT_ID are combined to act as primary key.
  • 8. 8 DATA TYPES: (ORACLE Specific) Data types are broadly classified into: 1. Character data types 2. Numeric data types 3. Date data types 4. LOB data types Character 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-130 to 9.99...9 x 10125 with up to 38 significant digits. Negative numbers from -1 x 10-130 to 9.99...99 x 10125 with 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 no scale is specified, the scale is zero. You can specify a scale and no precision:  column_name NUMBER (*, scale)
  • 9. 9 2. Floating-Point Numbers: There are two numeric data types for floating-point numbers:  BINARY_FLOAT (32-bit, single-precision floating-point number datatype)  BINARY_DOUBLE(64-bit, double-precision floating-point number datatype) Use binary precision that enables faster arithmetic calculations and usually reduces storage 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 function with 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 manipulate large blocks of unstructured data (such as text, graphic images, video clips, and sound waveforms) 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 BUILT-IN FUNCTIONS FUNCTION RETURNS BIT_LENGTH (string)Number of bits in a bit string CAST (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 string CONVERT (String USINGconv)String converted as specified by a named conversionmethod CURRENT_DATECurrent date CURRENT_TIME (precision)Current time with the specified precision EXTRACT (part FROM source)Specified part (Day, Hour, etc.) from a DATETIME value LOWER (string)String converted to all lower case letters. OCTET_LENGTH (string)Number of 8-bit bytes in a character string POSITION (target IN source)Position where the target string appears in the source string SUBSTRING (source FROM n FOR len)A portion of the source string, beginning at the n-th character, for a length of len TRANSLATE (string USING trans) String translated as specified by a named translation Function TRIM (BOTH char FROM string) String with both leading and trailing occurrences of char trimmed off TRIM (LEADING char FROM string)String with any leading occurrences of char trimmed off TRIM (TRAILING char FROM string) String with any trailing occurrences of char trimmed off UPPER (string)String converted to all uppercase letters Note:There are some column functions in SQL such as: SUM ( ), AVG ( ), MIN ( ), MAX ( ), COUNT ( ), COUNT (*)
  • 11. 11 Types of Commands in SQL 1. 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 table 2. 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 data 3. DCL (Data Control Language)  Grant – Grants user access privileges  Revoke – Removes user access privileges 4. TCL (Transaction Control Language)  Commit – Ends the current transaction  Rollback – Aborts the current transaction SQLCommands with Example: 1. CREATE TABLE Syntax: 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 CONSTRAINT person_pk PRIMARY KEY (P_Id) ) Result: P_Id LastName FirstName Address City We can also make more than one columns as our primary keys under one constraint name. 2. INSERT INTO Syntax: 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 City 1 Goel Gaurish Gurgaon South_City1 2 Dash Bimal Ghaziabad Shipra_Sun_city 3 Chawla Preeti Gurgaon South_City2 3. ALTER TABLE Syntax: ALTER TABLE table_name MODIFY column_namedatatype Example: ALTER TABLE Persons ADD DateOfBirth date
  • 13. 13 Result: P_Id LastName FirstName Address City DateOfBirth 1 Goel Gaurish Gurgaon South_City1 2 Dash Bimal Ghaziabad Shipra_Sun_city 3 Chawla Preeti Gurgaon South_City2 We can also drop a column using this command : ALTER TABLE Persons DROP COLUMN DateOfBirth 4. UPDATE Syntax: UPDATE table_name SET column1=value, column2=value2 ... WHERE some_column=some_value Example: UPDATE Persons SET DateOfBirth=‟11-JUL-92‟ WHERE FirstName=‟Gaurish‟ AND LastName=‟Goel‟ Result: P_Id LastName FirstName Address City DateOfBirth 1 Goel Gaurish Gurgaon South_City1 11-JUL-92 2 Dash Bimal Ghaziabad Shipra_Sun_city 3 Chawla Preeti Gurgaon South_City2 While using UPDATE command make sure that you don‟t forget to put WHERE clause otherwise all the rows will be updated. 5. DELETE FROM Syntax: DELETE FROM table_name WHERE some_column=some_value Example: DELETE FROM Persons WHERE LastName='Chawla' AND FirstName='Preeti'  TRUNCATE is used to delete all rows in a table. It is a DDL commandand this action cannot be rolled back.
  • 14. 14 Result: P_Id LastName FirstName Address City DateOfBirth 1 Goel Gaurish Gurgaon South_City1 11-JUL-92 2 Dash Bimal Ghaziabad Shipra_Sun_city To delete all rows use this command : DELETE * FROMtable_name 6. SELECT Syntax: SELECT * FROM table_name SELECT column_name1, column_name2,….. FROM table_name WHERE some_column = some_value Example: SELECT FirstName, LastName, DateOfBirth FROM Persons WHERE Address = „Gurgaon‟ Result: FirstName LastName DateOfBirth Gaurish Goel 11-JUL-92 7. DROP TABLE Syntax: DROP TABLE table_name Example: DROP TABLE Persons 8. COMMITand ROLLBACK SQL supports database transactions through two SQL transaction processing statements: The COMMIT statement signals the successful end of a transaction. It tells the DBMS that the transaction is now complete; all of the statements that comprise the transaction have been executed, and the database is self-consistent. The ROLLBACK statement signals the unsuccessful end of a transaction. It tells the DBMS that the user does not want to complete the transaction; instead, the DBMS should
  • 15. 15 back out any changes made to the database during the transaction. In effect, the DBMS restores the database to its state before the transaction began. 9. GRANT and REVOKE The basic GRANTstatement is used to grant security privileges on database objects to specific users. Grant statement is normally used by the owner of the table to give access to other users. Grant statement includes the specific list of grant privileges, the name of the 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 Gaurish Grant 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 grant privileges to other users. The privileges that you have granted with the GRANT statement can be taken away with the REVOKE statement. The REVOKE statement has a structure that closely parallels the GRANT statement, specifying a specific set of privileges to be taken away, for a specific database object, from one or more user-ids. Example: REVOKE select, insert ON Persons FROM Gaurish
  • 16. 16 JOINS SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables. The JOIN keyword is used in SQL statements. Two tables are related to each other with keys. For example: There are two tables Persons and Accounts. Both are related by a common field P_Id. Persons Table P_Id LastName FirstName Address City 1 Goel Gaurish Gurgaon South_City1 2 Dash Bimal Ghaziabad Shipra_Sun_City Accounts Table Account_No Opening_Date P_Id 5423 12-NOV-11 1 4561 24-JUL-12 2 TYPES OF JOINS 1. Inner Join (also known as Simple Join) 1.1 Equi Join 1.1.1 Natural Join 1.1.2 Cross Join or Cartesian Join 2. Outer Join 2.1 Left Outer Join 2.2 Right Outer Join 2.3 Full Outer Join 3. Self Join 1. Inner Join: Inner join creates a new result table by combining column values of two tables (A and B) based upon the join-predicate.The query compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row.
  • 17. 17 Example-1: SELECT FirstName, Address, P.P_Id FROM Persons P, Accounts A WHERE P.P_ID = A.P_Id Example-2: SELECT FirstName, Address, P.P_Id FROM Persons P INNER JOIN Accounts A ON WHERE P.P_ID = A.P_Id Result of both examples: FirstName Address P.Id Gaurish Gurgaon 1 Bimal Ghaziabad 2 1.1 Equi Join An equi-join is a specific type of comparator-based join that uses only equality comparisons in the 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 Join A natural join is a type of equi-join where the join predicate arises implicitly by comparing all columns in both tables that have the same column-names in the joined tables. The resulting joined table contains only one column for each pair of equally named columns. SELECT * FROM Persons NATURAL JOIN Accounts 1.1.2 Cross or Cartesian Join CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it will produce rows which combine each row from the first table with each row from the second table. There are two ways of writing a cross join: SELECT * FROM Persons CROSS JOIN Accounts // Explicit Cross Join SELECT * FROM Persons, Accounts // Implicit Cross Join
  • 18. 18 Result: P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id 1 Goel Gaurish Gurgaon South_C ity1 11-JUL-92 5423 12-NOV-11 1 2 Dash Bimal Ghaziabad Shipra_ Sun_Cit y 5423 12-NOV-11 1 1 Goel Gaurish Gurgaon South_C ity1 11-JUL-92 4561 24-JUL-12 2 2 Dash Bimal Ghaziabad Shipra_ Sun_Cit y 4561 24-JUL-12 2 2. Outer Join An 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 Join The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). Persons Table P_Id LastName FirstName Address City DateOfBirth 1 Goel Gaurish Gurgaon South_City1 11-JUL-92 2 Dash Bimal Ghaziabad Shipra_Sun_City 23-DEC-78 3 Preeti Chawla Gurgaon South_City2 19-OCT-85 4 Ravi Kanth Gurgaon DLF_City 04-MAR-86 Accounts Table Account_No Opening_Date P_Id 5423 12-NOV-11 1 4561 24-JUL-12 2 6879 14-AUG-10 4 7809 10-JAN-11 5 SELECT * FROM Persons LEFT OUTER JOIN Accounts ON Persons.P_Id = Accounts.P_Id
  • 19. 19 Result: P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id 1 Goel Gaurish Gurgaon South_C ity1 11-JUL-92 5423 12-NOV-11 1 2 Dash Bimal Ghaziabad Shipra_ Sun_Cit y 23-DEC-78 4561 24-JUL-12 2 3 Chawla Preeti Gurgaon South_C ity2 19-OCT-85 NULL NULL NUL L 4 Kanth Ravi Gurgaon DLF_Ci ty 04-MAR-86 6879 14-AUG-10 4 2.2 Right Outer Join A right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in B. SELECT * FROM Persons RIGHT OUTER JOIN Accounts ON Persons.P_ID = Accounts.P_Id Result: P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id 1 Goel Gaurish Gurgaon South_C ity1 11-JUL-92 5423 12-NOV-11 1 2 Dash Bimal Ghaziabad Shipra_ Sun_Cit y 23-DEC-78 4561 24-JUL-12 2 4 Ravi Kanth Gurgaon DLF_Ci ty 04-MAR-86 6879 14-AUG-10 4 NUL L NULL NULL NULL NULL NULL 7809 10-JAN-11 5 2.3 Full Outer Join A full outer join combines the effect of applying both left and right outer joins. Where records in the full outer joined tables do not match, the result set will have NULL values for every column of the table that lacks a matching row. For those records that do match, a single row will be produced in the result set (containing fields populated from both tables).
  • 20. 20 SELECT * FROM Persons FULL OUTER JOIN Accounts ON Persons.P_Id = Accounts.P_Id Result: P_Id LastName FirstName Address City DateOfBirth Account_No Opening_Date P_Id 1 Goel Gaurish Gurgaon South_C ity1 11-JUL-92 5423 12-NOV-11 1 2 Dash Bimal Ghaziabad Shipra_ Sun_Cit y 23-DEC-78 4561 24-JUL-12 2 3 Chawla Preeti Gurgaon South_C ity2 19-OCT-85 NULL NULL NUL L 4 Ravi Kanth Gurgaon DLF_Ci ty 04-MAR-86 6879 14-AUG-10 4 NUL L NULL NULL NULL NULL NULL 7809 10-JAN-11 5 3. Self Join A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed 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_Id Result: FirstName Address Gaurish Gurgaon Bimal Ghaziabad Chawla Gurgaon Kanth Gurgaon ALIAS(Formerly known asSYNONYMS) When selecting data from many tables, it becomes difficult to write complex queries. To solve this problem we can create aliases (shorthand notations) and use them at the place of table names. Aliases were formerly known as Synonyms.
  • 21. 21 Syntax: create alias per for Persons create alias acc for Accounts We can also drop the created aliases: drop alias per drop alias acc VIEWS A view is a SQL query that is permanently stored in the database and assigned a name. The results of the stored query are visible through the view, and SQL lets you access these query results as if they were a real table in the database.But unlike a real table, a view does not exist in the database as a stored set of data values. A common use of views is to restrict a user's access to only selected rows or columns of a table. Types of views: 1. Horizontal view 2. Vertical view Horizontal View: It restricts a user‟s access to selected rows Syntax to create a view: Create view view_name as select column_names from table_name where some_column = some_value Example: 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 which are having „Gurgaon‟ as their Address field. Vertical View: It restricts a user‟s access to selected columns Syntax to create a view: Create view view_name as select column_name1, column_name2, ….fromtable_name Example: CREATE VIEW GGG AS SELECT FirstName, LastName, City FROM Persons
  • 22. 22 Result: Above example will create a view with the name “GGG” which selects specifiedcolumns. INDEXES An index is a structure that provides rapid access to the rows of a table based on the values of one or more columns. The DBMS uses the index as you might use the index of a book. The index stores data values and pointers to the rows where those data values occur. In the index the data values are arranged in ascending or descending order, so that the DBMS can quickly search the index to find a particular value. It can then follow the pointer to locate the row containing the value. 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 the DESCRIPTION column. The other provides access based on the primary key of the table, which is 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 the users. Most DBMS products alwaysestablish an index for the primary key of a table, because they anticipate that access to the table will most frequently be via the primary key.
  • 23. 23 Syntax to create an index: Unique is used to specify that the combination of columns being indexed must contain a unique value for every row of the table. Example: CREATE UNIQUE INDEX prsn_indx ON Persons (P_Id, LastName) TRIGGERS Triggers are those procedures stored in PL/SQL that run (fire) implicitly when any user actionoccurs. These actions include: DML - Insert, Update, Delete DDL - Create, Alter Database events – logon/logoff, errors, startup/shutdown Syntax: Create trigger trigger_name on table_name for event_name (insert/update/delete) as action (SQL command that specifies your action) Example: CREATE TRIGGER trig1 ON Persons FOR INSERT AS UPDATE Accounts SET Accounts.P_Id = Inserted.P_Id from Accounts, Inserted Description: The first part of the trigger tells that the trigger is to be invoked when an INSERT is attempted on table Persons. The trigger‟s action is defined after the keyword AS. In this case the action is to update the table Accounts. The row being inserted is referred to using the pseudo-table nameinserted within the UPDATE statements.
  • 24. 24 Note:There are two temporary tables Inserted & Deleted which are created automatically by the DBMS. These tables make our task easier while writing queries. DUAL TABLE The DUAL table is a special one-column table present by default in all Oracle database installations. It is suitable for use in selecting a pseudo column such as SYSDATE or USER. The table has a single VARCHAR2(1) column called DUMMY that has a value of 'X'. Example: Select SYSDATE from DUAL Select USER from DUAL Select 1+2+3 from DUAL SCHEMAS A schema is a named entity within the database and includes the definitions for: Tables Views Domains (function like extended data types used to define columns in a table) Privileges Character 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 privileges Example: CREATE SCHEMA GGG AUTHORIZATION Gaurish CREATE TABLE People (Name varchar (30), Age number (2)) CREATE TABLE Places (City varchar (30), State varchar (30)) GRANT ALL PRIVILEGES ON People TO PUBLIC GRANT SELECT ON Places TO Bimal
  • 25. 25 CLUSTERING A cluster is a schema object that contains data from one or more tables, all of which have one or more columns in common. Oracle Database stores together all the rows from all the tables that share 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 system privilege. To create a cluster in another user's schema, you must have CREATEANYCLUSTER system privilege. Syntax: Schema: Specify the schema to contain the cluster. If you omit schema, Oracle creates the cluster in your current schema. Cluster: Specify the name of the cluster to be created. After you create a cluster, you add tables to it. A cluster can contain a maximum of 32 tables. You can access clustered tables with SQL statements just as you can access non-clustered tables.
  • 26. 26 Column: Specify one or more names of columns in the cluster key. You can specify up to 16 cluster key columns. These columns must correspond in both datatype and size to columns in each 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 key value or the same hash value. Use K or M to specify this space in kilobytes or megabytes. This space determines the maximum number of cluster or hash values stored in a data block. If SIZE is not a divisor of the data block size, Oracle uses the next largest divisor. If SIZE is larger than the data block size, Oracle uses the operating system block size, reserving at least one data block for 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 stores together rows having the same cluster key value. Each distinct cluster key value is stored only once 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 can issue any data manipulation language (DML) statements against a table in the cluster. This index is called the cluster index. HashKeys Clause:Specify the HASHKEYS clause to create a hash cluster and specify the number of hash values for a hash cluster. In a hash cluster, Oracle stores together rows that have the same hash key value. The hash value for a row is the value returned by the cluster's hash function. Parallel clause: The parallel_clause lets you parallelize the creation of the cluster.
  • 27. 27 SYSTEM TABLES System tables provide information regarding the structure of the database itself. Each vendor has its own structure for these tables. System tables are owned by SYS user. Some examples of system 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 CATALOGS The catalog is a collection of named database schemas. The catalog also contains a set of system tables (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, and maintained by the DBMS itself. These system tables contain data that describes the structure of the database. The tables in the system catalog are automatically created when the database is created. 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 EXPLAIN PLANS The EXPLAINPLAN statement displays execution plans chosen by the optimizer for SELECT, UPDATE, INSERT, and DELETE statements. A statement execution plan is the sequence of operations 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 statement An access method for each table mentioned in the statement A join method for tables affected by join operations in the statement Data operations like filter, sort, or aggregation In addition to the row source tree, the plan table contains information about the following: Optimization, such as the cost and cardinality of each operation Partitioning, such as the set of accessed partitions Parallel execution, such as the distribution method of join inputs The EXPLAINPLAN results let you determine whether the optimizer selects a particular execution plan, such as, nested loops join. The results also help you to understand the optimizer decisions, such as why the optimizer chose a nested loops join instead of a hash join, and lets you understand the performance of a query. Execution plans can differ due to the following: Different Schemas Different Costs Different Schemas: The execution and explain plan occur on different databases. The user explaining the statement is different from the user running the statement. Two users might be pointing to different objects in the same database, resulting in different execution 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 the costs are different. Some factors that affect the costs include the following: Data volume and statistics Bind variable types and values Initialization parameters set globally or at session level Explain Plan Restrictions: Oracle Database does not support EXPLAINPLAN for statements performing implicit type conversion of date bind variables. With bind variables in general, the EXPLAINPLAN output might not represent the real execution plan.
  • 30. 30 Figure – 1 Select * from PS_DEMAND_PHYS_INV where business_unit = 'EURLC' In figure – 1 only one condition is given which is resulting in FULL SCAN and a high cost and hence poor performance. We should take care that full scan doesn‟t occur in the execution plan of a query. Figure – 2 Select * 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 decrease in cost and good performance.
  • 31. 31 APPENDICES A ALIAS 21 B BUILT-IN FUNCTIONS 10 C CLUSTERING 25 D DATA TYPES (ORACLE Specific) Character Data Types 8 (ORACLE SPECIFIC) DATE Data type 9 LOB Data Types 9 Numeric Data Types 8 DATA TYPES: (ORACLE Specific) 8 Database Architecture 4 Multi-Database Architecture 4 Multi-Location Architecture 5 Single-Database Architecture 4 DUAL TABLE 24 E Equi Join Cross or Cartesian Join 17 Natural Join 17 EXPLAIN PLANS 28 I INDEXES 22 Inner Join Equi Join 17 J JOINS 16 O Outer Join Full Outer Join 20 Left Outer Join 18 Right Outer Join 19 S SCHEMAS 24 SQL – Introduction 3 SQL Commands with Example 11 SYSTEM CATALOGS 27 SYSTEM TABLES 27 T TRIGGERS 23 Types of Commands in SQL 11 DCL 11 DDL 11 DML 11 TCL 11 TYPES OF JOINS 16 Inner Join 16 Outer Join 18 Self Join 20 Types of Keys in SQL 6 Composite Primary Key 7 Foreign Key 6 Primary Key 6 Unique Key 6 V VIEWS 21 Horizontal View 21 Vertical View 22