Assignmemnt 3
Assignmemnt 3
Assignmemnt 3
References :- http://www.oracle-dba-online.com/
Introduction to Databases
DATABASE
RDBMS
The father of Relational Data Model was Dr. E.F. CODD. He developed the relational
data model by taking the concept from Relational Algebra in June-1970.
Relational Data Model is nothing but 12 Rules which are named after Codd as Codd
Rules. According to Codd a package can be called as RDBMS only if it satisfies the
Codd Rules.
ORACLE
ORACLE DATABASE
Every Oracle Database Contains Logical and Physical Structures. Logical Structures
are tablespaces, Schema objects, extents and segments. Physical Structures are
Datafiles, Redo Log Files, Control File.
A database is divided into logical storage units called tablespaces, which group
related logical structures together. Each Tablespace in turn consists of one are more
datafiles.
All the tables and other objects are stored in tablespace logically, but physically they
are stored in the datafiles associated with the tablespace.
Every Oracle database has a set of two or more redo log files. The set of redo log files
for a database is collectively known as the database's redo log. A redo log is made up
of redo entries (also called redo records).
The primary function of the redo log is to record all changes made to data. If a failure
prevents modified data from being permanently written to the datafiles, the changes
can be obtained from the redo log so work is never lost.
Every Oracle database has a control file. A control file contains the database name
and locations of all datafiles and redo log files.
Every Oracle database also has a Parameter File. Parameter file contains the name of
the Database, Memory Settings and Location of Control file.
CODDS RULES
1 Information Rule: All information in a relational database including table
names, column names are represented by values in tables. This simple view of
data speeds design and learning. User productivity is improved since
knowledge of only one language is necessary to access all data such as
description of the table and attribute definitions, integrity constraints. Action
can be taken when the constraints are violated. Access to data can be restricted.
All these information are also stored in tables.
3 Systematic Treatment of Nulls Rule: The RDBMS handles records that have
unknown or inapplicable values in a pre-defined fashion. Also, the RDBMS
distinguishes between zeros, blanks and nulls in the records hand handles such
values in a consistent manner that produces correct answers, comparisons and
calculations. Through the set of rules for handling nulls, users can distinguish
results of the queries that involve nulls, zeros and blanks. Even though the rule
doesnt specify what should be done in the case of nulls it specifies that there
should be a consistent policy in the treatment of nulls.
A table is the data structure that holds data in a relational database. A table is
composed of rows and columns.
A table in Oracle Ver. 7.3 can have maximum 255 Columns and in Oracle Ver. 8 and
above a table can have maximum 1000 columns. Number of rows in a table is
unlimited in all the versions.
A table can represent a single entity that you want to track within your system. This
type of a table could represent a list of the employees within your organization, or the
orders placed for your company's products.
A table can also represent a relationship between two entities. This type of a table
could portray the association between employees and their job skills, or the
relationship of products to orders. Within the tables, foreign keys are used to represent
relationships.
Although some well designed tables could represent both an entity and describe the
relationship between that entity and another entity, most tables should represent either
an entity or a relationship.
The following sessions explain how to create, alter, and drop tables. Some simple
guidelines to follow when managing tables in your database are included.
Designing Tables
Before creating a Table you have to decide what type of data each column can
contain. This is known as datatype. Lets Discuss what datatypes are available in
Oracle.
Datatypes
A datatype associates a fixed set of properties with the values that can be used in a
column of a table or in an argument of a procedure or function. These properties cause
Oracle to treat values of one datatype differently from values of another datatype. For
example, Oracle can add values of NUMBER datatype, but not values of RAW datatype.
Character datatypes
oCHAR
oNCHAR
oVARCHAR2 and VARCHAR
oNVARCHAR2
oCLOB
oNCLOB
oLONG
NUMBER datatype
Time and date datatypes:
oDATE
oINTERVAL DAY TO SECOND
oINTERVAL YEAR TO MONTH
oTIMESTAMP
oTIMESTAMP WITH TIME ZONE
oTIMESTAMP WITH LOCAL TIME ZONE
Binary datatypes
oBLOB
oBFILE
oRAW
oLONG RAW
Another datatype, ROWID, is used for values in the ROWID pseudocolumn, which
represents the unique address of each row in a table.
The following table summarizes the information about each Oracle built-in datatype.
CHAR Fixed-length character data of Fixed for every row in the table (with trailing
(size[BYTE | length size bytes or characters. blanks); maximum size is 2000 bytes per row,
CHAR]) default size is 1 byte per row. Consider the
character set (single-byte or multibyte) before
setting size.
VARCHAR2 Variable-length character data, Variable for each row, up to 4000 bytes per row.
(size[BYTE | with maximum length size bytes or Consider the character set (single-byte or
CHAR]) characters. multibyte) before setting size. A
maximum size must be specified.
NCHAR (size) Fixed-length Unicode character Fixed for every row in the table (with trailing
data of length size characters. blanks). Column size is the number of characters.
(The number of bytes is 2 times this number for
theAL16UTF16 encoding and 3 times this number
for the UTF8 encoding.) The upper limit is 2000
bytes per row. Default is 1 character.
NVARCHAR2 Variable-length Unicode character Variable for each row. Column size is the number
(size) data of length size characters. A of characters. (The number of bytes may be up to 2
maximum size must be specified. times this number for a the AL16UTF16 encoding
and 3 times this number for the UTF8 encoding.)
The upper limit is 4000 bytes per row. Default is 1
character.
LONG Variable-length character data. Variable for each row in the table, up to 232 - 1
bytes, or 2 gigabytes, per row. Provided for
backward compatibility.
NUMBER (p, s) Variable-length numeric data. Variable for each row. The maximum space
Maximum precision p and/or required for a given column is 21 bytes per row.
scale sis 38.
DATE Fixed-length date and time data, Fixed at 7 bytes for each row in the table. Default
ranging from Jan. 1, 4712 B.C.E. format is a string (such as DD-MON-RR) specified
by the NLS_DATE_FORMAT parameter.
to Dec. 31, 4712 C.E.
TIMESTAMP A value representing a date and Varies from 7 to 11 bytes, depending on the
(precision) time, including fractional seconds. precision. The default is determined by
(The exact resolution depends on theNLS_TIMESTAMP_FORMAT initialization
the operating system clock.) parameter.
TIMESTAMP A value representing a date and Fixed at 13 bytes. The default is determined by
(precision) time, plus an associated time zone theNLS_TIMESTAMP_TZ_FORMAT initialization
WITH TIME setting. The time zone can be an parameter.
ZONE offset from UTC, such as'-
5:0', or a region name, such
as 'US/Pacific'.
RAW (size) Variable-length raw binary data Variable for each row in the table, up to 2000 bytes
per row. A maximum size must be specified.
Provided for backward compatibility.
LONG RAW Variable-length raw binary data Variable for each row in the table, up to 231 - 1
bytes, or 2 gigabytes, per row. Provided for
backward compatibility.
ROWID Binary data representing row Fixed at 10 bytes (extended ROWID) or 6 bytes
addresses (restricted ROWID) for each row in the table.
When deciding which datatype to use for a column that will store alphanumeric data
in a table, consider the following points of distinction:
You can specify that a column contains a floating-point number, for example:
distance NUMBER
Or, you can specify a precision (total number of digits) and scale (number of digits to
right of decimal point):
Although not required, specifying precision and scale helps to identify bad input
values. If a precision is not specified, the column stores values as given. The
following table shows examples of how data different scale factors affect storage.
Use the TIMESTAMP datatype to store precise values, down to fractional seconds. For
example, an application that must decide which of two events occurred first might
use TIMESTAMP. An application that needs to specify the time for a job to execute might
use DATE.
Date Format
For input and output of dates, the standard Oracle default date format is DD-MON-RR.
For example:
'13-NOV-1992'
Be careful using a date format like DD-MON-YY. The YY indicates the year in the current
century. For example, 31-DEC-92 isDecember 31, 2092, not 1992 as you might
expect. If you want to indicate years in any century other than the current one, use a
different format mask, such as the default RR.
Time Format
Time is stored in 24-hour format, HH24:MI:SS. By default, the time in a date field is
12:00:00 A.M. (midnight) if no time portion is entered. In a time-only entry, the date
portion defaults to the first day of the current month. To enter the time portion of a
date, use theTO_DATE function with a format mask indicating the time portion, as in:
Once you have designed the table and decided about datatypes use the following SQL
command to create a table.
Empno NUMBER(5),
Ename VARCHAR2(15),
Hiredate DATE,
Sal NUMBER(7,2)
);
To insert rows in the table you can use SQL INSERT command.
To insert rows continuously in SQL Plus you can give the following
command.
To see the rows you have inserted give the following command.
To see the structure of the table i.e. column names and their
datatypes and widths. Give the following command.
SQL>desc emp
To see how many tables are in your schema give the following
command.
or
SQL>select * from tab;
Suppose you want to see only employee names and their salaries then you can type
the following statement
You can filter information using where conditions like suppose you want to see
only those employees whose salary is above 5000 then you can type the following
query with where condition
To see those employees whose salary is less than 5000 then the query will be
Logical Conditions
SELECT *
FROM emp
WHERE NOT
AND sal=3000;
Membership Conditions
WHERE deptno IN
(10,20);
Null Conditions
What is null?
WHERE deptno
IS NULL;
EXISTS Conditions
FROM dept d
WHERE EXISTS
WHERE d.deptno
= e.deptno);
LIKE Conditions
The LIKE conditions specify a test involving pattern matching. Whereas the equality
operator (=) exactly matches one character value to another, the LIKE conditions match
a portion of one character value to another by searching the first value for the pattern
specified by the second. LIKE calculates strings using characters as defined by the
input character set.
For example you want to see all employees whose name starts with S char. Then you
can use LIKE condition as follows
Similarly you want to see all employees whose name ends with d
You want to see all employees whose name starts with A and ends with d like
Abid, Adward, Arnold.
You want to see those employees whose name contains character a anywhere in the
string.
To see those employees whose name contain % sign. i.e. % sign has to be used as
literal not as wild char.
UNION Example
The following statement combines the results with the UNION operator, which eliminates
duplicate selected rows. This statement shows that you must match datatype (using
the TO_CHAR function) when columns do not exist in one or the other table:
UNION
The UNION operator returns only distinct rows that appear in either result, while
the UNION ALL operator returns all rows. TheUNION ALL operator does not eliminate duplicate
selected rows:
INTERSECT Example
The following statement combines the results with the INTERSECT operator, which returns only
those rows returned by both queries:
SELECT empno FROM emp
INTERSECT
SELECT empno FROM oldemp;
MINUS Example
The following statement combines results with the MINUS operator, which returns only rows
returned by the first query but not by the second:
Sorting Examples.
The following query sorts the employees according to ascending order of salaries.
The following query sorts the employees according to descending order of salaries.
The following query sorts the employees according to ascending order of names.
The following query first sorts the employees according to ascending order of names.If names
are equal then sorts employees on descending order of salaries.
You can also specify the positions instead of column names. Like in the following query,which
shows employees according to ascending order of their names.
The following query first sorts the employees according to ascending order of salaries.
If salaries are equal then sorts employees on ascending order of names
Single-row functions return a single result row for every row of a queried table or
view. These functions can appear in select
lists,WHERE clauses, START WITH and CONNECT BY clauses, and HAVING clauses.
Number Functions
Number functions accept numeric input and return numeric values. Most of these
functions return values that are accurate to 38 decimal digits.
ABS ACOS ASIN ATAN ATAN2 BITAND CEIL COS COSH EXP FLOOR
LN LOG
MOD POWER ROUND (number) SIGN SIN SINH SQRT TAN
TANH TRUNC (number)
ABS
ABS returns the absolute value of n.
Absolute
----------
87
ACOS
ACOS returns the arc cosine of n. Inputs are in the range of -1 to 1, and outputs are in
the range of 0 to pi and are expressed in radians.
----------
1.26610367
Similar to ACOS, you have ASIN (Arc Sine), ATAN (Arc Tangent) functions.
CIEL
Returns the lowest integer above the given number.
Example:
Ciel
---------
FLOOR
Example:
Floor
------------
3
COS
Example:
SIN
Example:
TAN
Example:
MOD
Example
The following example returns the remainder after dividing 30 by 4.
MOD
---------
POWER
Example
POWER
---------
EXP
Example
E RAISED TO 2
-------------
LN
Example
LN
------------
LOG
Example
LOG
---------
ROUND
Round
------------
3.46
TRUNC
Example
Round
------------
3.45
SQRT
Example
The following example returns the square root of 16.
SQRT
---------
Character Functions
LOWER
LOWER
-------------
sami
UPPER
UPPER
------------------
SAMI
INITCAP
INITCAP
------------------
Mohammed Sami
LENGTH
LENGTH
------------
13
SUBSTR
For example the following query returns sam from the string
mohammed sami.
Substr
--------
sam
INSTR
Example
INSTR
--------
REPLACE
Example
REPLACE
---------
Example
INSTR
--------
REPLACE
Example
REPLACE
---------
This function is used to encrypt characters. For example you can use
this function to replace characters in a given string with your coded
characters.
Example
select
translate('interface','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh
ijklmnopqrstuvwxyz',
'BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza')
Encrypt from dual;
Encrypt
-----------
joufsgbdf
SOUNDEX
Example
ENAME
---------
Smith
Smyth
Smythe
RPAD
Example
The following query rights pad ename with '*' until it becomes 10
characters.
Ename
----------
Smith*****
John******
Mohammed**
Sami******
LPAD
Example
The following query left pads ename with '*' until it becomes 10
characters.
Ename
----------
*****Smith
******John
**Mohammed
******Sami
LTRIM
Example
Ltrim
--------------
Interface
RTRIM
Example
Rtrim
------------
Interface
TRIM
Trims a given character from left or right or both from a given string.
Example
The following query removes zero from left and right of a given
string.
Trim
----------
34435
CONCAT
Example
The following Query combines ename with literal string is a and
jobid.
Concat
----------------
Smith is a clerk
John is a Manager
Sami is a G.Manager
COALESCE
Coalesce function returns the first not null value in the expression
list.
Example.
select
empno,ename,salary,comm,coalesce(salary+comm,salary,1000)
Net Sal from emp;
SCOTT 1000
DECODE
Example
select
decode(deptno,10,'Sales',20,'Accounts,30,'Production,
DEPTNAME
----------
Sales
Accounts
Unknown Dept.
Accounts
Production
Sales
R&D
Unknown Dept.
GREATEST
Example
GREATEST
--------
50
select greatest('SAMI','SCOTT','RAVI','SMITH','TANYA')
from dual;
GREATEST
--------
TANYA
LEAST
LEAST
--------
10
LEAST
--------
RAVI
NVL
NVL2(expr1,expr2)
Example
ENAME COMM
------ ----
Scott 300
Tiger 450
Ravi 300
NVL2
NVL2(expr1,expr2,expr3)
Example
2000 2000
3400 3400
NULLIF
NULLIF(expr1, expr2)
Nullif compares expr1 with expr2. If they are equal then returns null,
otherwise return expr1.
Example.
The following query shows old jobs of those employees who have
changed their jobs in the company by comparing the current job
with old job in oldemp table.
----- -------
SMITH CLERK
SAMI
SCOTT MANAGER
UID
Example
UID
----
20
USER
USER
---------
SCOTT
SYS_CONTEXT
SYS_CONTEXT returns the value of parameter associated with the
context namespace. You can use this function in both SQL and
PL/SQL statements.
EXAMPLE
USERNAME
---------
SCOTT
VSIZE
VSIZE(expr)
Example
ENAME BYTES
------ ------
SCOTT 5
SAMI 4
RAVI 4
KIRAN 5
Aggregate Functions
Example
Average Salary
------------------------
2400.40
SUM
SUM(ALL/DISTINCT expr)
Example
Total Salary
------------------------
26500
MAX
MAX(ALL/DISTINCT expr)
Example
The following query returns the max salary from the employees.
Maximum Salary
------------------------
4500
MIN
MIN(ALL/DISTINCT expr)
Example
------------------------
1200
COUNT
Returns the number of rows in the query. If you specify expr then
count ignore nulls. If you specify the asterisk (*), this function
returns all rows, including duplicates and nulls. COUNT never returns
null.
Example
COUNT
------
14
COUNT
------
12
STDDEV
STDDEV(ALL/DISTINCT expr)
Example
Stddev
-------
1430
VARIANCE
VARIANCE(ALL/DISTINCT expr)
Example
Variance
-------
1430
Joins
A join is a query that combines rows from two or more tables, views, or materialized
views. Oracle performs a join whenever multiple tables appear in the
query's FROM clause. The query's select list can select any columns from any of these
tables. If any two of these tables have a column name in common, you must qualify
all references to these columns throughout the query with table names to avoid
ambiguity.
Join Conditions
Most join queries contain WHERE clause conditions that compare two columns, each
from a different table. Such a condition is called ajoin condition. To execute a join,
Oracle combines pairs of rows, each containing one row from each table, for which
the join condition evaluates to TRUE. The columns in the join conditions need not also
appear in the select list.
Equijoins
select
emp.empno,emp.ename,emp.sal,emp.deptno,dept.dname,dept.ci
ty from emp,dept where emp.deptno=dept.deptno;
The above query can also be written like, using aliases, given below.
The above query can also be written like given below without using table qualifiers.
And if you want to see all the columns of both tables then the query can be written
like this.
Non equi joins is used to return result from two or more tables where exact join is not
possible.
For example we have emp table and salgrade table. The salgrade table contains grade
and their low salary and high salary. Suppose you want to find the grade of employees
based on their salaries then you can use NON EQUI join.
Self Joins
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 combines and returns rows of the table that satisfy the join
condition.
For example the following query returns employee names and their manager names
for whom they are working.
An inner join (sometimes called a "simple join") is a join of two or more tables that
returns only those rows that satisfy the join condition.
Outer Joins
An outer join extends the result of a simple join. An outer join returns all rows that
satisfy the join condition and also returns some or all of those rows from one table for
which no rows from the other satisfy the join condition.
To write a query that performs an outer join of tables A and B and returns all
rows from A (a left outer join), use the ANSILEFT [OUTER] JOIN syntax, or
apply the outer join operator (+) to all columns of B in the join condition. For
all rows in A that have no matching rows in B, Oracle returns null for any
select list expressions containing columns of B.
To write a query that performs an outer join of tables A and B and returns all
rows from B (a right outer join), use the ANSIRIGHT [OUTER] syntax, or apply
the outer join operator (+) to all columns of A in the join condition. For all
rows in B that have no matching rows in A, Oracle returns null for any select
list expressions containing columns of A.
To write a query that performs an outer join and and returns all rows from A
and B, extended with nulls if they do not satisfy the join condition (a full
outer join), use the ANSI FULL [OUTER] JOIN syntax.
For example the following query returns all the employees and department names and
even those department names where no employee is working.
select e.empno,e.ename,e.sal,e.deptno,d.dname,d.city
from emp e, dept d where e.deptno(+)=d.deptno;
That is specify the (+) sign to the column which is lacking values.
Cartesian Products
If two tables in a join query have no join condition, Oracle returns their Cartesian
product. Oracle combines each row of one table with each row of the other. A
Cartesian product always generates many rows and is rarely useful. For example, the
Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include
a join condition unless you specifically need a Cartesian product.
SUBQUERIES
For example, you want to see all the employees whose salary is above average salary.
For this you have to first compute the average salary using AVG function and then
compare employees salaries with this computed salary. This is possible using
subquery. Here the sub query will first compute the average salary and then main
query will execute.
Select * from emp where sal > (select avg(sal) from emp);
Similarly we want to see the name and empno of that employee whose salary is
maximum.
We want to see how many employees are there whose salary is above average.
We want to see those employees who are working in Hyderabad. Remember emp and
dept are joined on deptno and city column is in the dept table. Assuming that wherever
the department is located the employee is working in that city.
For example the following query returns the top 5 salaries from employees table.
Select sal from (select sal from emp order sal desc)
To see the sum salary deptwise you can give the following query.
Now to see the average total salary deptwise you can give a sub query in FROM
clause.
The above average total salary department wise can also be achieved in 9i using
WITH clause given below
WITH
group by deptno)
GROUP BY QUERIES
You can group query results on some column values. When you give a SELECT
statement without group by clause then all the resultant rows are treated as a single
group.
For Example, we want to see the sum salary of all employees dept wise. Then the
following query will achieved the result
Now we want to see total salary department wise where the dept wise total salary is
above 5000.
For this you have to use HAVING clause. Remember HAVING clause is used to filter
groups and WHERE clause is used to filter rows. You cannot use WHERE clause to
filter groups.
We want to see those departments and the number of employees working in them
where the number of employees is more than 2.
Instead of displaying deptno you can also display deptnames by using join conditions.
Now we want to see the cities name and the no of employees working in each city.
Remember emp and dept are joined on deptno and city column is in the dept table.
Assuming that wherever the department is located the employee is working in that
city.
where emp.deptno=dept.deptno
Group by dept.city;
ROLLUP
The ROLLUP operation in the simple_grouping_clause groups the selected rows based
on the values of the first n, n-1, n-2, ... 0 expressions in the GROUP BY specification, and
returns a single row of summary for each group. You can use the ROLLUP operation to
produce subtotal values by using it with the SUM function. When used
with SUM, ROLLUP generates subtotals from the most detailed level to the grand total.
Aggregate functions such as COUNT can be used to produce other kinds of
superaggregates.
Rows grouped on the values of the first 'n' expressions are called regular rows, and
the others are called superaggregate rows.
The following query uses rollup operation to show sales amount product wise and
year wise. To see the structure of the sales table refer to appendices.
CUBE
The CUBE operation in the simple_grouping_clause groups the selected rows based on
the values of all possible combinations of expressions in the specification, and returns
a single row of summary information for each group. You can use the CUBE operation
to produce cross-tabulation values.
The following query uses CUBE operation to show sales amount product wise and
year wise. To see the structure of the sales table refer to appendices.
CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without having
to invoke procedures.
For example the following query uses CASE expression to display Department Names
based on deptno.
The following statement finds the average salary of the employees in the employees
table using $2000 as the lowest salary possible:
SELECT AVG(CASE WHEN e.sal > 2000 THEN e.sal
ELSE 2000 END) "Average Salary" from emp e;
Examples.
Suppose you want to add rows from one table to another i.e. suppose we have
Old_Emp table and emp table with the following structure
Emp
Old_emp
Now we want to add rows from old_emp table to emp table. Then you can give the
following insert statement
Multitable Insert
Now we want to add the rows from SALES table Weekly_Sales Table in the
following Structure.
To achieve the above we can give a multi table INSERT statement given below
Insert all
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,Mon,mon_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,Tue,tue_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,Wed,wed_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,Thu,thu_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,Fri,fri_amt)
Into week_sales(prodid,prodname,weekday,amount)
Values (prodid,prodname,Sat,sat_amt)
Select prodid,prodname,mon_amt,tue_amt,wed_amt,thu_amt
Fri_amt,sat_amt from sales;
Update
Update statement is used to update rows in existing tables which is in your own
schema or if you have update privilege on them.
For example to raise the salary by Rs.500 of employee number 104. You can give the
following statement.
In the above statement if we did not give the where condition then all employees
salary will be raised by Rs. 500. Thats why always specify proper WHERE condition
if dont want to update all employees.
For example We want to change the name of employee no 102 from Sami to Mohd
Sami and to raise the salary by 10%. Then the statement will be.
101 Sami 99 90 89
102 Scott 34 77 56
103 Smith 45 82 43
Now to compute total which is sum of Maths,Phy and Chem and average.
update student set total=maths+phy+chem,
average=(maths+phy+chem)/3;
Suppose we added the city column in the employee table and now we want to set this
column with corresponding city column in department table which is join to employee
table on deptno.
Delete
Use the DELETE statement to delete the rows from existing tables which are in your
schema or if you have DELETE privilege on them.
If you dont mention the WHERE condition then all rows will be deleted.
Suppose we want to delete all employees whose salary is above 2000. Then give the
following DELETE statement.
Now we want to update sales_history table from sales table i.e. those rows which are
already present in sales_history, their amount should be updated and those rows which
are not present in sales_history table should be inserted.
After the statement is executed sales_history table will look like this.
SALES_HISTORY
Prod Month Amount
SONY JAN 2200
SONY FEB 3000
SONY
SONY MAR 2500
AKAI
SONY
APR
JAN
3200
3200 Data Definition Language
SONY MAY
JUN
3100
5000 (DDL) Statements
Data definition language (DDL) statements enable you to perform these tasks:
Create, alter, and drop schema objects
The CREATE, ALTER, and DROP commands require exclusive access to the specified
object. For example, an ALTER TABLE statement fails if another user has an open
transaction on the specified table.
The GRANT, REVOKE, ANALYZE, AUDIT, and COMMENT commands do not require exclusive
access to the specified object. For example, you can analyze a table while other users
are updating the table.
Oracle implicitly commits the current transaction before and after every DDL
statement.
Many DDL statements may cause Oracle to recompile or reauthorize schema objects.
DDL Statements are
Create
Example
Now Suppose you have emp table now you want to create a TAX table with the
following structure and also insert rows of those employees whose salary is above
5000.
Tax
Empno Number(5
Tax )
Number(1
0,2)
To do this we can first create TAX table by defining column names and datatypes and
then use INSERT into EMP SELECT . statement to insert rows from emp table. like
given below.
Instead of executing the above two statements the same result can be achieved by
giving a single CREATE TABLE AS statement.
You can also use CREATE TABLE AS statement to create copies of tables. Like to
create a copy EMP table as EMP2 you can give the following statement.
To copy tables without rows i.e. to just copy the structure give the following statement
Alter
Examples:
To add new columns addr, city, pin, ph, fax to employee table you can give the
following statement
To modify the datatype and width of a column. For example we you want to increase
the length of the column ename from varchar2(20) to varchar2(30) then give the
following command.
To decrease the width of a column the column can be decreased up to largest value it
holds.
To change the datatype the column must be empty in All Oracle Versions.
To drop columns.
From Oracle Ver. 8i you can drop columns directly it was not possible in previous
versions.
Remember you cannot drop the column if the table is having only one column.
If the column you want to drop is having primary key constraint on it then you have to
give cascade constraint clause.
To drop columns in previous versions of Oracle8.0 and 7.3. and to change the column
name in all Oracle versions do the following.
For example we want to drop pin and city columns and to change SAL column name
to SALARY.
To rename table emp2 to employee2 you can give the following command.
Drop
Use the drop statement to drop tables, functions, procedures, packages, views,
synonym, sequences, tablespaces etc.
Example
If emp2 table is having primary key constraint, to which other tables refer to, then you
have to first drop referential integrity constraint and then drop the table. Or if you
want to drop table by dropping the referential constraints then give the following
command
Truncate
Use the Truncate statement to delete all the rows from table permanently . It is same
as DELETE FROM <table_name> except
Truncate does not generate any rollback data hence, it cannot be roll backed.
If any delete triggers are defined on the table. Then the triggers are not fired
It deallocates free extents from the table. So that the free space can be use
by other tables.
Example