You are on page 1of 42

Drop

Alter
Create
Comment
Oracle 10g (SQL)

Truncat
Rename

Md.Moazzem Hossain (Anik)


Select
Update
Marge

Insert
Delete

Revoke
Grant

Commit
Rollback

Page 1
Save point
Oracle 10g (SQL)

Chapter: 01 Retrieving Data Using the SQL SELECTStatement


 Capabilities of SQL SELECTStatements
 Projection:Choose the columns in a table
 Selection:Choose the rows in a table
 Joining:Bring together data that is stored in different tables
 Basic SELECTStatement

 Selecting All Columns

 Arithmetic Expressions: Rules of Precedence:

Note: With the DATEand TIMESTAMPdata types, you can use the addition and subtraction
operators only

 Defining a Null Value


 A null is a value that is unavailable, unassigned, unknown, or inapplicable.
• A null is not the same as a zero or a blank space.
 Arithmetic expressions containing a null value evaluate to null

 Defining a Column Alias:

Md.Moazzem Hossain (Anik) Page 2


Oracle 10g (SQL)

 Concatenation Operator: (||)

 Using Literal Character Strings:

 Alternative Quote (q) Operator

Chapter 02: Restricting and Sorting Data


 Using the WHEREClause

 Restrict the rows that are returned by using the WHEREclause:


 The WHEREclause follows the FROMclause

 Comparison Conditions:

Md.Moazzem Hossain (Anik) Page 3


Oracle 10g (SQL)

 Logical Conditions:

 Using the ORDER BYClause:


 Sort retrieved rows with the ORDER BYclause:
– ASC:ascending order, default
– DESC:descending order
• The ORDER BYclause comes last in the SELECTstatement:

Using the &Substitution Variable:

 Temporarily store values with single-ampersand (&) and


double-ampersand (&&) substitution

Md.Moazzem Hossain (Anik) Page 4


Oracle 10g (SQL)

CHAPTER -03 Using Single-Row Functions to Customize Output:Two Types of SQL


Functions
FUNCTION

Single row function ( Return one result per row) Multi row function( Return one result per set of rows)
rows)rows)row)

Character Number Date Conversion General

 Case-  Character- NEXT_DAY NVL


manipulation Manipulation LAST_DAY NVL2
functions functions ROUND NULLIF
TRUNC COALESCE
MONTHS_BETWEEN CASE
ADD_MONTHS DECODE
LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH ROUND AVG
INSTR TRUNC COUNT
LPAD | MOD MAX
RPAD MIN
TRIM STDDEV
REPLACE SUM
VARIANCE DECODE

 Implicit data typeconversion  Explicit data typeconversion


functions functions

Md.Moazzem Hossain (Anik) Page 5


Oracle 10g (SQL)

 Using the Character-Manipulation Functions

 Number Functions

• ROUND: Rounds value to specified decimal


 Using the ROUNDFunction

 Using the TRUNCF unction • TRUNC: Truncates value to specified decimal.

Md.Moazzem Hossain (Anik) Page 6


Oracle 10g (SQL)

 Using the MODFunction • MOD: Returns remainder of division.

 Using Date Functions

 Assume SYSDATE = '25-JUL-03':

 Arithmetic with Dates

Note:SYSDATEis a SQL function that returns the current date and time. Your results may
differ from the example.

Md.Moazzem Hossain (Anik) Page 7


Oracle 10g (SQL)

 Implicit Data Type Conversion:

For expression evaluation, the Oracle Server can automatically


convert the following:

Note:CHARto NUMBERconversions succeed only if the character string represents a valid number.

 Using the TO_CHARFunction with Dates:

The format model:


• Must be enclosed by single quotation marks • Is case sensitive
• Can include any valid date format element
• Has an fmelement to remove padded blanks or suppress leading zeros
• Is separated from the date value by a comma

 Elements of the Date Format Model:

 Elements of the Date Format Mode

Md.Moazzem Hossain (Anik) Page 8


Oracle 10g (SQL)

Using the TO_CHAR Function with Dates:

Using the TO_CHARFunction with Numbers:

These are some of the format elements that you can use with the TO_CHARfunction to display a
number value as a character:
Using the TO_CHARFunction with Numbers

Using the TO_NUMBERand TO_DATEFunctions

 Convert a character string toa number format using the TO_NUMBERfunction:

 Convert a character string to a date format using the TO_DATEfunction:

 These functions have an fxmodifier. This modifier specifies the exact matching for the
character argument and date format model of a TO_DATEfunction

RRDate Format

Md.Moazzem Hossain (Anik) Page 9


Oracle 10g (SQL)

RRDate Format: Exampl: To find employees hired before 1990, use the RRdate format,
which produces the same results whether the command is run in 1999 or now:

Nesting Functions
 Single-row functions can be nested to any level.
 Nested functions are evaluated from the deepest level to the least deep level.

Md.Moazzem Hossain (Anik) Page 10


Oracle 10g (SQL)

NVL Function
Converts a null value to an actual value:
• Data types that can be used are date, character, and number.
• Data types must match:
– NVL(commission_pct,0)
– NVL(hire_date,'01-JAN-97')
– NVL(job_id,'No Job Yet')

Using the NVL2Function:

Using the NULLIFFunction:

Using the COALESCEFunction

 The COALESCE function returns the first non-null expression in the list

 Provide the use of IF-THEN-ELSE logic within a SQL statement


• Use two methods:
– CASEexpression
– DECODEfunction

Md.Moazzem Hossain (Anik) Page 11


Oracle 10g (SQL)

Chapter 4: Reporting Aggregated DataUsing the Group Functions.


 Group functions operate on sets of rows to give one result per group.

 We can use AVG and SUM for numeric data.


 You can use AVG, SUM, MIN, and MAX functions against columns that can store numeric data.

 Using the COUNTFunction. COUNT(*)returns the number of rows in a table:

Using the DISTINCTKeyword.


 COUNT(DISTINCT expr)returns the number of distinct non-null values of expr.
 Use the DISTINCTkeyword to suppress the counting of any duplicate values in a column.

 Group functions ignore null values in the column:

 The NVLfunction forces group functions to include null values:

Md.Moazzem Hossain (Anik) Page 12


Oracle 10g (SQL)

 Creating Groups of Data:


 You can divide rows in a table into smaller groups by using the GROUP BYclause.

 All columns in the SELECT list that are not in group functions must be in the GROUP BY
clause.

 The GROUP BY column does not have to be in the SELECT list.

 Using the GROUP BY Clause on Multiple Columns.

 Illegal Queries Using Group Functions:


 We cannot use the WHEREclause to restrict groups.
 We use the HAVINGclause to restrict groups.
 We cannot use group functions in the WHEREclause.

 Cannot use the WHEREclause to restrict groups

Md.Moazzem Hossain (Anik) Page 13


Oracle 10g (SQL)

 Restricting Group Results with the HAVING Clause


When you use the HAVING clause, the Oracle server restricts groups as follows:
• Rows are grouped.• The group function is applied.
• Groups matching the HAVING clause are displayed

Nesting Group Functions:

Chapter 5: Displaying Data from Multiple Tables.


 Types of Joins
Joins that are compliant with
All joins with out theSQL:1999 standard
theSQL:1999standard include the following:
 Equijoins
 Cross joins
 None qui joins
 Natural joins
 Outer joins
 USING clause
 Self-joins
 Full (or two-sided) outer join
 Cross joins
 Arbitrary join conditions for outer joins
 Natural joins• Full (or two-sided)

Md.Moazzem Hossain (Anik) Page 14


Oracle 10g (SQL)

 Joining Tables Using SQL:1999 Syntax.

 Creating Natural Joins:


The NATURAL JOIN clause is based on all columns in the two tables that have the
same name , equal values, but different data types, an error is returned.

 Creating Joins with the USING Clause:


 If several columns have the same names but the data types do not match, natural join
can be applied by using the USING clause to specify the columns that should be used for
an equijoin.
 Use the USING clause to match only one column when more than one column matches.
 Do not use a table name or alias in the referenced columns.
 The NATURAL JOIN and USING clauses are mutually exclusive.

 Using Table Aliases:


 Use table aliases to simplify queries.
 Use table aliases to improve performance.

 ON Clause:

Md.Moazzem Hossain (Anik) Page 15


Oracle 10g (SQL)

 Use the ON clause to specify a join condition. This lets you specify join
conditions separate from any search or filter conditions in theWHEREclause.

 Self-Joins Using the ON Clause:


 Sometimes you need to join a table to itself. To find the name of each employee’s
manager, you need to join the EMPLOYEES table to itself, or perform a self join.

 Creating Three-Way Joins with the ONClause:

 Non equijoins:
 A non equijoin is a join condition containing something other than an equality operator.

 INNER Versus OUTER Joins:


 the join of two tables returning only matched rows is called an inner join.
 A join between two tables that returns the results of the inner join as well as the
unmatched rows from the left (or right) tables is called a left (or right) outer join and the
results of a left and right join is a full outer join.
 LEFT OUTER JOIN:

Md.Moazzem Hossain (Anik) Page 16


Oracle 10g (SQL)

 RIGHT OUTER JOIN

 FULL OUTER JOIN

 Cartesian Products:
 A Cartesian product is formed when A join condition is omitted, invalid and
All rows in the first table are joined to all rows in the second table.
 To avoid a Cartesian product, always include a valid join condition.

 Creating Cross Joins


 The CROSS JOIN clause produces the cross-product of two tables.
 This is also called a Cartesian product between the two tables.

Md.Moazzem Hossain (Anik) Page 17


Oracle 10g (SQL)

Chapter 6: Using Subqueries to Solve Queries:


 Subquery Syntax:
 A subquery is a SELECT statement that is embedded in a clause of another SELECT
statement.

 Guidelines for Using Subqueries:


 A subquery must be enclosed in parentheses.
 Place subqueries on the right side of the comparison condition.
 The ORDER BYclause in the subquery is not needed unless you are performing Top-N
analysis.
 Use single-row operators with single-row subqueries, and use multiple-row operators
with multiple-row subqueries.
 Types of Subqueries:
 Single-row subqueries:Queries that return onlyone row from the inner
SELECTstatement
 Multiple-row subqueries:Queries that return more than one row from the inner
SELECTstatement
Single-Row Subqueries Multiple-Row Subqueries
 Return only one row.  Return more than one row.
 Use single-row comparison operators.  Use multiple-row comparison operators.

Md.Moazzem Hossain (Anik) Page 18


Oracle 10g (SQL)

 Executing Single-Row Subqueries:

 Using Group Functions in a Subquery:

 The HAVINGClause with Subqueries: You can use subqueries not only in the
WHERE clause but also in the HAVING clause.

 What Is Wrong with This Statement:


 One common error with subqueries occurs when more than one row is
returned for a single-row subquery
 To correct this error, change the =operator to IN.

Md.Moazzem Hossain (Anik) Page 19


Oracle 10g (SQL)

 Using the ANYOperator in Multiple-Row Subqueries:


 <ANY means less than the maximum. >ANY means more than the minimum.
=ANY is equivalent to IN.

 Using the ALLO perator in Multiple-Row Subqueries:


 >ALL means more than the maximum, and <ALL means less than the minimum.
The NOT operator can be used with IN, ANY, and ALL operators.

 Null Values in a Subquery:

 Alternatively, a WHERE clause can be included in the subquery to display all


employees who do not have any subordinates:

Md.Moazzem Hossain (Anik) Page 20


Oracle 10g (SQL)

Chapter 7: Using the Set Operators:

 Using the UNION Operator


 The UNIONoperator returns results from both queries after eliminating duplications.

 The number of columns and the data types of the columns being selected must be
identical in all the SELECT statements used in the query. The names of the columns need
not be identical.
 UNION operates over all of the columns being selected.
 NULL values are not ignored during duplicate checking.
 The IN operator has a higher precedence than the UNION operator.
 By default, the output is sorted in ascending order ofthe first column of theSELECTclause

 UNION ALLOperator
 The UNION ALL operator returns results from both queries, including all duplications.

Md.Moazzem Hossain (Anik) Page 21


Oracle 10g (SQL)

 The guidelines for UNION and UNION AL Lare the same, with the following two
exceptions that pertain to UNION ALL:
 Unlike UNION, duplicate rows are not eliminated and the output is not sorted by
default.
 The DISTINCT keyword cannot be used.

 INTERSECT Operator
 The INTERSECT operator returns rows that are common to both queries.

 The number of columns and the data types of the columns being selected by the
SELECT statements in the queries must be identical in all the SELECT statements used
in the query. The names of the columns need not be identical.
 Reversing the order of the intersected tables does not alter the result.
 INTERSECT does not ignore NULL values

 MINUSOperator:
 The MINUS operator returns rows in the first query that are not present in the second
query.

Chapter 08: Manipulating Data:

 INSERTStatement Syntax:
 You can add new rows to a table by issuing the INSERT statement.

 Note:This statement with the VALUESclause adds only one row at a time to a table.

Md.Moazzem Hossain (Anik) Page 22


Oracle 10g (SQL)

 Inserting Rows with Null Values

 The SYSDATE function records the current date and time

 Inserting Specific Date Values:

 Use &substitution in a SQL statement to prompt for values.

 Copying Rows from Another Table:


 You can use the INSERTstatement to add rows to a table where the values are
derived from existing tables. In place of the VALUESclause, you use a subquery

Md.Moazzem Hossain (Anik) Page 23


Oracle 10g (SQL)

 UPDATEStatement Syntax
 Modify existing rows with the UPDATEstatement:

 DELETE Statement
 You can remove existing rows by using the DELETE statement.

 Deleting Rows Based on Another Table

 TRUNCATE Statement
 Removes all rows from a table, leaving the table empty and the table structure intact.

Md.Moazzem Hossain (Anik) Page 24


Oracle 10g (SQL)

 Using a Subquery in an INSERTStatement

 Controlling Transactions

Md.Moazzem Hossain (Anik) Page 25


Oracle 10g (SQL)

Chapter 09: Database Objects.

 CREATE TABLE Statement


 You must have: – The CREATE TABLE privilege – A storage area
 You specify the: – Table name – Column name, column data type, and column size

 Confirm table creation. Or to describe the table.

 Data Types

 Datetime Data Types

Md.Moazzem Hossain (Anik) Page 26


Oracle 10g (SQL)

Constraints:
 Including Constraints:
Constraints enforce rules at the table level.
• Constraints prevent the deletion of a table if there are dependencies.
• The following constraint types are valid:
– NOT NULL – UNIQUE – PRIMARY KEY – FOREIGN KEY – CHECK

 Defining Constraints:

Md.Moazzem Hossain (Anik) Page 27


Oracle 10g (SQL)

 NOT NULLConstraint:
 The NOT NULL constraint ensures that the column contains no null values. Columns without
the NOT NULL constraint can contain null values by default. NOT NULL constraints must be
defined at the column level.

 UNIQUEConstraint:
 Defined at either the table level or the column level:

 PRIMARY KEY Constraint:

 FOREIGN KEY Constraint

Md.Moazzem Hossain (Anik) Page 28


Oracle 10g (SQL)

 FOREIGN KEY Constraint

 CHECK Constraint

 CREATE TABLE: Example:

 Violating Constraints:

 For example, if you attempt to update a record with a value that is tied to an integrity
constraint, an error is returned. In the example in the slide, department 55 does not exist in
the parent table, DEPARTMENTS, and so you receive the parent key violation ORA-02291.

Md.Moazzem Hossain (Anik) Page 29


Oracle 10g (SQL)

ALTER TABLE Statement:


Use the ALTER TABLEstatement to:
 Add a new column Modify an existing column  Define a default value for the
new column  Drop a column:
 Dropping a Table
All data and structure in the table are deleted. Any pending transactions are
committed. All indexes are dropped. All constraints are dropped.
 You cannot roll back the DROP TABLE statement.

Chapter 10: Creating Other Schema Objects:

 View: A view is a logical table based on a table or another view. A view contains no
data of its own but is like a window through which data from tables can be viewed or
changed.
 Advantages of Views

 Simple Views and Complex Views:

 View Syntax:

 Creating a View

Md.Moazzem Hossain (Anik) Page 30


Oracle 10g (SQL)

 Sequences:
 Can automatically generate unique numbers Is a sharable object
Can be used to create a primary key valueReplaces application code
Speeds up the efficiency of accessing sequence values when cached in memory

 CREATE SEQUENCE Statement: Syntax:

 Using a Sequence:
Insert a new department named “Support” in location ID 2500:

 View the current value for the DEPT_DEPTID_SEQ sequence:

 Modifying a Sequence:
Change the increment value, maximum value, minimum value,
cycle option, or cache option:

 To remove a sequence, use the DROPstatement:

Md.Moazzem Hossain (Anik) Page 31


Oracle 10g (SQL)

 Indexes:An Oracle server index is a schema object that can speed up the retrieval of
rows by using a pointer.
Create an index on one or more columns:

Improve the speed of query access to the LAST_NAME column in the EMPLOYEES table:

 Removing an Index

 Synonyms
Create an easier reference to a table that is owned by another user:

Create a shortened name for the DEPT_SUM_VU view

Drop a synonym:

Chapter 11 Managing Objects with Data Dictionary Views:

Md.Moazzem Hossain (Anik) Page 32


Oracle 10g (SQL)

 How to Use the Dictionary Views:

 Table Information:

 Column Information:

 Constraint Information:
You can find out the names of your constraints, the type of constraint, the table
name to which the constraint applies, the condition for check constraints, foreign
key constraint information, deletion rule for foreign key constraints, the status, and
many other types of information about your constraints.

Md.Moazzem Hossain (Anik) Page 33


Oracle 10g (SQL)

 Constraint Information (Column)

 View Information:

 Sequence Information:

 Synonym Information:

 Adding Comments to a Table: You can add comments to a table or column


by using the COMMENT statement:

Md.Moazzem Hossain (Anik) Page 34


Oracle 10g (SQL)

Chapter 12
Controlling User Access:
 Privileges:Privileges are the right to execute particular SQL statements. The
database administrator (DBA) is a high-level user with the ability to create users
and grant users access to the database and its objects.
 System privileges:
– Creating new users Create session
– Removing users – Create table
– Removing tables – create sequence
– Backing up tables – create view
 Object privileges: – create procedure
An object privilegeis a privilege or right to perform a particular action on a specific
table, view, sequence, or procedure. Each object has a particular set of grantable
privileges.
ALTER
DELETE
EXECUTE
INDEX
INSERT
REFERENCES
SELECT
UPDATE
 Creating Users:
The DBA creates users with the CREATE USERstatement

 User System Privileges:


After a user is created, the DBA can grant specific system privileges to that user.

 Granting System Privileges:


The DBA can grant specific system privileges to a user.

Md.Moazzem Hossain (Anik) Page 35


Oracle 10g (SQL)

A role is a named group of related privileges that can be granted to the user. This
method makes it easier to revoke and maintain privileges.

 Creating and Granting Privileges to a Role:

 Changing Your Password:

 Object Privileges:

Md.Moazzem Hossain (Anik) Page 36


Oracle 10g (SQL)

 Granting Object Privileges:

 Grant privileges to update specific columns to users and roles:

 Passing On Your Privileges:

 Revoking Object Privileges:


 You use the REVOKE statement to revoke privileges granted to other users.
Privileges granted to others through the WITH GRANT OPTION clause are also
revoked.

 Revoking Object Privileges:

Note: Current system privileges can be found in the SESSION_PRIVS dictionary view.

Md.Moazzem Hossain (Anik) Page 37


Oracle 10g (SQL)

Chapter 13: Managing Schema Objects:


 Use the ALTER TABLE statement to:
 Can rename table name,
 Add a new column,
 Modify an existing column,
 Define a default value for the new column,
 Drop a column,

 We can change the table name following syntax:


Alter table tablename
Rename to newname;

Example:
alter table anik
Rename to sahria;
 You use the ADD clause to add columns:

 You can change a column’s data type, size, and default value.

 Use the DROP COLUMNclause to drop columns you no longer


need from the table:

Md.Moazzem Hossain (Anik) Page 38


Oracle 10g (SQL)

 SET UNUSED Option:


 You use the SET UNUSED option to mark one or more columns as unused.

We can see the unused column following syntax:

Select *
From user_unused_col_tabs:

You use the DROP UNUSED COLUMNS.

 Adding a Constraint Syntax:


Add or drop a constraint, but not modify its structure
 Enable or disable constraints
 Add a NOT NULL constraint by using the MODIFY clause

Add a FOREIGN KEY constraint to the EMP2table indicating that


a manager must already exist as a valid employee in the EMP2 table.

 ON DELETE CASCADE:
Delete child rows when a parent key is deleted:

Md.Moazzem Hossain (Anik) Page 39


Oracle 10g (SQL)

 Deferring Constraints:
DEFERR ABLE or NOT DEFERRABLE INITIALLY DEFERRED or INITIALLY IMMEDIATE

 Dropping a Constraint:
Remove the manager constraint from the EMP2table:

Remove the PRIMARY KEY constraint on the DEPT2table and drop the
associated FOREIGN KEY constraint on the EMP2.DEPARTMENT_IDcolumn:

 Disabling Constraints:
Execute the DISABLE clause of the ALTER TABLE statement to deactivate integrity
constraint.
 Apply the CASCADE option to disable dependent integrity constraints.

 Enabling Constraints:
Activate an integrity constraint currently disabled in the table definition by using
the ENABLE clause.
A UNIQUE index is automatically created if you enable a UNIQUE key or a PRIMARY
KEY constraint

Md.Moazzem Hossain (Anik) Page 40


Oracle 10g (SQL)

 Cascading Constraints:
The CASCADE CONSTRAINTS clause is used along with the DROP COLUMN clause.
The CASCADE CONSTRAINTS clause drops all referential integrity constraints that
refer to the primary and unique keys defined on the dropped columns.
 The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined
on the dropped columns.

 Overview of Indexes:
Indexes are created:
• Automatically
– PRIMARY KEY creation – UNIQUE KEY creation
• Manually– CREATE INDEX statement – CREATE TABLE statement.

 Removing an Index:
Remove an index from the data dictionary by using the DROP INDEX command:

 DROP TABLE … PURGE:

Md.Moazzem Hossain (Anik) Page 41


Oracle 10g (SQL)

 FLASHBACK TABLE Statement:


Repair tool for accidental table modifications
– Restores a table to an earlier point in time
– Benefits: Ease of use, availability, fast execution
– Performed in place

 Creating a Directory for the External Table:


Create a DIRECTORYobject that corresponds to the directory on the file system
where the external data source resides.

 Creating an External Table:


You create external tables using the ORGANIZATION EXTERNAL clause of the CREATE
TABLE statement. You are not, in fact, creating a table. Rather, you are creating
metadata in the data dictionary that you can use to access external data.

Md.Moazzem Hossain (Anik) Page 42

You might also like