Sunday, 29 April 2018

Search for a VALUE in all COLUMNS of all TABLES in an entire SCHEMA oracle

Search a CHARACTER type
Let's look for the value KING in SCOTT schema.
SQL> variable val varchar2(10)
SQL> exec :val := 'KING'

PL/SQL procedure successfully completed.

SQL> SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
  2    SUBSTR (table_name, 1, 14) "Table",
  3    SUBSTR (column_name, 1, 14) "Column"
  4  FROM cols,
  5    TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
  6    || column_name
  7    || ' from '
  8    || table_name
  9    || ' where upper('
 10    || column_name
 11    || ') like upper(''%'
 12    || :val
 13    || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
 14  ORDER BY "Table"
 15  /

Wednesday, 23 August 2017

printing values from ref cursor using anonymous block

------------------------------------simple cursor------------------------------------------------------------------
set serveroutput on;
declare
cursor c_emp is
select ename,deptno,hiredate from emp
where months_between(sysdate,hiredate)/12 > 30
order by hiredate desc;
begin
for c_var in c_emp
loop
dbms_output.put_line(c_var.ename||' '||c_var.deptno||' '||c_var.hiredate);
end loop;
end;
-------------------------------------using for loop sub-qury ------------------------------------------------------
set serveroutput on;
declare

begin
for c_var in (
select ename,deptno,hiredate from emp
where months_between(sysdate,hiredate)/12 > 30
order by hiredate desc)
loop
dbms_output.put_line(c_var.ename||' '||c_var.deptno||' '||c_var.hiredate);
end loop;
end;
----------------------using cursor dml operation through multiple rows---------------------------------
set serveroutput on;
declare

begin
for c_var in (
select empno,sal,ename,deptno,hiredate from emp
where months_between(sysdate,hiredate)/12 > 30
order by hiredate desc)
loop
update emp set sal=c_var.sal+100 where empno=c_var.empno;
--dbms_output.put_line(c_var.empno||'  '||c_var.sal||' '||c_var.ename||' '||c_var.deptno||' '||c_var.hiredate);
end loop;
end;
/
select * from emp;
-----------------------------------displaying multiple data using ref_cursor----------------------------
create or replace
procedure ref_proc
(po_result out SYS_REFCURSOR )

as
begin
open po_result for
select empno,sal,ename,deptno,hiredate from emp
where months_between(sysdate,hiredate)/12 > 30
order by hiredate desc;

end;
-- -----------------displaying values from ref cursor using anonymous block---------------------
set serveroutput on;
set autoprint on;
var r refcursor;
DECLARE
  PO_RESULT SYS_REFCURSOR;
BEGIN

  REF_PROC(
    PO_RESULT => :r
  );
  /* Legacy output:
DBMS_OUTPUT.PUT_LINE('PO_RESULT = ' || PO_RESULT);
*/
--  :PO_RESULT := PO_RESULT; --<-- Cursor
END;


how to see and delete duplicate rows .

select mgr,count(*) from emp
group by mgr
having count(*) >1;

MGRCOUNT(*)
78393
76985
75662

DELETE FROM your_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM your_table
GROUP BY column1, column2, column3);

example-
select * from emp
where rowid not in (select min(rowid) from emp group by mgr);
EMPNOENAMEJOBMGRHIREDATESALCOMMDEPTNO
7844TURNERSALESMAN769808-09-19811500030
7900JAMESCLERK769803-12-1981950 30
7654MARTINSALESMAN769828-09-19811250140030
7698BLAKEMANAGER783901-05-19812850 30
7902FORDANALYST756603-12-19813000 20
7521WARDSALESMAN769822-02-1981125050030
7782CLARKMANAGER783909-06-19812450 10

Wednesday, 14 June 2017

CLUSTER


CLUSTER
Definition:
In Oracle, clustering is a way of ordering the physical placement of tables on a disk drive in such a way as
to speed up I/O access times. This is accomplished by sharing data blocks on the disk. Anything that
minimizes I/O or reduces contention in the physical file system will improve the overall performance of
the database.
A table cluster can be described as a set of tables that share the same data blocks, and that are grouped
together because they share common columns that are often used together. Index cluster tables can be
either multi-table or single-table.
When cluster tables are created, Oracle stores all of the rows for each of the tables in the same data
blocks. The cluster key value is the value of the cluster key columns for a particular row.
An index cluster uses an index to maintain row sequence, as opposed to a hash cluster, where the
symbolic key is hashed to the data block address.
A cluster provides an optional method of storing table data. A cluster is made up of a group of tables
that share the same data blocks. The tables are grouped together because they share common columns
and are often used together. For example, the emp and dept table share the deptno column. When you
cluster the emp and dept tables, Oracle Database physically stores all rows for each
department from both the emp and dept tables in the same data blocks.
Because clusters store related rows of different tables together in the same data blocks, properly used
clusters offer two primary benefits:
• Disk I/O is reduced and access time improves for joins of clustered tables.
• The cluster key is the column, or group of columns, that the clustered
tables have in common. You specify the columns of the cluster key when
creating the cluster. You subsequently specify the same columns when
creating every table added to the cluster. Each cluster key value is stored
only once each in the cluster and the cluster index, no matter how many rows
of different tables contain the value.
Therefore, less storage might be required to store related table and index data in a cluster than is
necessary in non-clustered table format. For example, in Figure 1, notice how each cluster key (each
deptno) is stored just once for many rows that contain the same value in both the emp and dept tables.
After creating a cluster, you can create tables in the cluster. However, before any rows can be inserted
into the clustered tables, a cluster index must be created. Using clusters does not affect the creation of
additional indexes on the clustered tables; they can be created and dropped as usual.
You should not use clusters for tables that are frequently accessed individually.

Data Dictionary Objects
user_clusters
user_clu_columns
user_cluster_hash _expressions
user_all_tables


Clustering is a method of storing tables that are intimately related and often joined together into the
same area on disk. The cluster key is the column or columns by which the tables are usually joined in a
query
By storing the field comprising the Cluster Key once instead of multiple times, storage is saved. The
arguably more significant advantage to Clustering is to expidite join queries. When a query is fired that
joins these 2 tables by Cluster Key, the joined rows would be fetched with a single IO operation.
A cluster is a data structure that improves retrieval performance
Example:
----------------------------------------------------------

create cluster empdept (did number(2));
----------------------------------------------------------
create index empdept_indx on cluster empdept;
----------------------------------------------------------
create table emp
(
eid number(10),
ename varchar2(100),
did number(2)
)
cluster empdept(did);
----------------------------------------------------------
create table dept
(
did number(2),
dname varchar2(100)
)
cluster empdept(did);
----------------------------------------------------------

Monday, 5 June 2017

PL/SQL packages


PL/SQL packages are schema objects that groups logically related PL/SQL types, variables and subprograms.
A package will have two mandatory parts:
•    Package specification
•    Package body or definition
Package Specification
The specification is the interface to the package. It just DECLARES the types, variables, constants, exceptions, cursors, and subprograms that can be referenced from outside the package. In other words, it contains all information about the content of the package, but excludes the code for the subprograms.
All objects placed in the specification are called public objects. Any subprogram not in the package specification but coded in the package body is called a private object.
The following code snippet shows a package specification having a single procedure. You can have many global variables defined and multiple procedures or functions inside a package.
CREATE PACKAGE cust_sal AS
   PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
When the above code is executed at SQL prompt, it produces the following result:
Package created.
Package Body
The package body has the codes for various methods declared in the package specification and other private declarations, which are hidden from code outside the package.
The CREATE PACKAGE BODY Statement is used for creating the package body. The following code snippet shows the package body declaration for the cust_sal package created above. I assumed that we already have CUSTOMERS table created in our database as mentioned in PL/SQL - Variables chapter.
CREATE OR REPLACE PACKAGE BODY cust_sal AS
   PROCEDURE find_sal(c_id customers.id%TYPE) IS
   c_sal customers.salary%TYPE;
   BEGIN
      SELECT salary INTO c_sal
      FROM customers
      WHERE id = c_id;
      dbms_output.put_line('Salary: '|| c_sal);
   END find_sal;
END cust_sal;
/
When the above code is executed at SQL prompt, it produces the following result:
Package body created.
Using the Package Elements
The package elements (variables, procedures or functions) are accessed with the following syntax:
package_name.element_name;
Consider, we already have created above package in our database schema, the following program uses the find_sal method of the cust_sal package:
DECLARE
   code customers.id%type := &cc_id;
BEGIN
   cust_sal.find_sal(code);
END;
/
When the above code is executed at SQL prompt, it prompt to enter customer ID and when you enter an ID, it displays corresponding salary as follows:
Enter value for cc_id: 1
Salary: 3000

PL/SQL procedure successfully completed.
Example:
The following program provides a more complete package. We will use the CUSTOMERS table stored in our database with the following records:
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  3000.00 |
|  2 | Khilan   |  25 | Delhi     |  3000.00 |
|  3 | kaushik  |  23 | Kota      |  3000.00 |
|  4 | Chaitali |  25 | Mumbai    |  7500.00 |
|  5 | Hardik   |  27 | Bhopal    |  9500.00 |
|  6 | Komal    |  22 | MP        |  5500.00 |
+----+----------+-----+-----------+----------+
THE PACKAGE SPECIFICATION:
CREATE OR REPLACE PACKAGE c_package AS
   -- Adds a customer
   PROCEDURE addCustomer(c_id   customers.id%type,
   c_name  customers.name%type,
   c_age  customers.age%type,
   c_addr customers.address%type,
   c_sal  customers.salary%type);
 
   -- Removes a customer
   PROCEDURE delCustomer(c_id  customers.id%TYPE);
   --Lists all customers
   PROCEDURE listCustomer;

END c_package;
/
When the above code is executed at SQL prompt, it creates the above package and displays the following result:
Package created.
CREATING THE PACKAGE BODY:
CREATE OR REPLACE PACKAGE BODY c_package AS
   PROCEDURE addCustomer(c_id  customers.id%type,
      c_name customers.name%type,
      c_age  customers.age%type,
      c_addr  customers.address%type,
      c_sal   customers.salary%type)
   IS
   BEGIN
      INSERT INTO customers (id,name,age,address,salary)
         VALUES(c_id, c_name, c_age, c_addr, c_sal);
   END addCustomer;
 
   PROCEDURE delCustomer(c_id   customers.id%type) IS
   BEGIN
       DELETE FROM customers
         WHERE id = c_id;
   END delCustomer;

   PROCEDURE listCustomer IS
   CURSOR c_customers is
      SELECT  name FROM customers;
   TYPE c_list is TABLE OF customers.name%type;
   name_list c_list := c_list();
   counter integer :=0;
   BEGIN
      FOR n IN c_customers LOOP
      counter := counter +1;
      name_list.extend;
      name_list(counter)  := n.name;
      dbms_output.put_line('Customer(' ||counter|| ')'||name_list(counter));
      END LOOP;
   END listCustomer;
END c_package;
/
Above example makes use of nested table which we will discuss in the next chapter. When the above code is executed at SQL prompt, it produces the following result:
Package body created.
USING THE PACKAGE:
The following program uses the methods declared and defined in the package c_package.
DECLARE
   code customers.id%type:= 8;
BEGIN
      c_package.addcustomer(7, 'Rajnish', 25, 'Chennai', 3500);
      c_package.addcustomer(8, 'Subham', 32, 'Delhi', 7500);
      c_package.listcustomer;
      c_package.delcustomer(code);
      c_package.listcustomer;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Customer(1): Ramesh
Customer(2): Khilan
Customer(3): kaushik   
Customer(4): Chaitali
Customer(5): Hardik
Customer(6): Komal
Customer(7): Rajnish
Customer(8): Subham
Customer(1): Ramesh
Customer(2): Khilan
Customer(3): kaushik   
Customer(4): Chaitali
Customer(5): Hardik
Customer(6): Komal
Customer(7): Rajnish

PL/SQL procedure successfully completed

Before we write any code, we need to define what our package actually does; here is a description for
our package:-
• Maintain a bank balance
• Make withdrawals (reduce balance)
• Make deposits (increase balance)
• Query balance
Also, we can define some business rules at this point:-
• Balance cannot be overdrawn
• There should be some kind of limit to how much
can be withdrawn per transaction. We now have the definition of the bank account package, now for its implementation.
First, you need to create the package specification, this is done with the following statement:-
CREATE OR REPLACE PACKAGE package_name
IS|AS
<package-specification>
END [package name]
The name can be almost anything you like, the same restrictions apply as with all identifiers. Try to make the name useful, generally the package name will relate to what its contents relate to, for example, if a package contains functions and procedures for working with bank accounts, such as withdraw and deposit, then a good package
name might be bank_account. The package specification can be anything that would normally appear in the declarative section of a block of code (except for function and procedure bodies, this code is in the body).
The package specification and body can appear in a single file or separate files. The usual practice is to
give the source filename an extension of pkg for a single file or pks (pkh) and pkb for separate files
Looking at the description for our bank account
package, we can see that:-

• We require 3 public functions or procedures:-
1. Withdrawal
2. Deposit
3. Balance query

• We require private data
1. Current balance
2. Maximum allowed per withdrawal

Using packages, we can protect our data; by making data such as balance private and providing procedures or functions to access this data, we are assured that nothing else can modify this data.
Now, let's create our package specification:-
CREATE OR REPLACE PACKAGE bank_account
IS
-- Procedure for making a withdrawal
PROCEDURE withdraw(p_amount IN NUMBER);
-- Procedure for making a deposit
PROCEDURE deposit(p_amount IN NUMBER);
-- Function to query the balance
FUNCTION balance RETURN NUMBER;
END;
That’s it!!! Our Package specification is done. This can be thought of as the public interface for our package, i.e. anything that appears in here is visible and within scope for all programs outside the package. Keeping the package specification in a separate file facilitates modifications later, this means that you can change the body of a package (so long as the spec is not affected) without affecting any programs which use the package. It also allows you to hide your implementation. We now need to create the package body, this is where the actual code appears for all public subprograms as well as any other private objects. You create the body with the following statement:-
CREATE OR REPLACE PACKAGE BODY package_name
IS|AS
<package-body>
END [package name]
As you can see, the only major difference for the body is the inclusion of the word BODY in the first line.

The following code will create our package body:-
CREATE OR REPLACE PACKAGE BODY bank_account
IS
--
-- Private data objects
--
-- Hold account balance, initialised to 0
v_balance NUMBER := 0;
-- Hold maximum withdrawl amount
v_max_withdrawl CONSTANT NUMBER := 250;
--
-- Private functions/procedures
--
-- Print text to screen
PROCEDURE p(p_text IN VARCHAR2)
IS
BEGIN
DBMS_OUTPUT.put_line(p_text);
END;
--
-- Public function/procedure definitions
--
-- Procedure for making a withdrawal
PROCEDURE withdraw(p_amount IN NUMBER)
IS
l_new_balance NUMBER:= v_balance - p_amount;
BEGIN
IF p_amount > l_max_withdrawal THEN
-- Ensure amount is within limit
p('Withdrawals limited to '||
TO_CHAR(l_max_withdrawl)||
' per transaction');
-- No overdrafts allowed
ELSIF l_new_balance < 0 THEN
-- No overdrafts allowed
p('No overdraft available');
p('Cash available : '
||TO_CHAR(v_balance));
ELSE
v_balance := v_balance - p_amount;
p('Here is your cash!');
END IF;
END withdraw;
-- Procedure for making a deposit
PROCEDURE deposit(p_amount IN NUMBER)
IS
BEGIN
IF p_amount <= 0 THEN
p('Deposit must be at least £1');
ELSE
v_balance := v_balance + p_amount;
p('Thankyou!');
END IF;
END;
-- Function to query the balance
FUNCTION balance RETURN NUMBER
IS
BEGIN
RETURN v_balance;
END;
END;
To make use of this package, you might do the following:-
BEGIN
DBMS_OUTPUT.put_line(BANK_ACCOUNT.balance);
BANK_ACCOUNT.withdraw(100);
BANK_ACCOUNT.deposit(500);
DBMS_OUTPUT.put_line(BANK_ACCOUNT.balance);
BANK_ACCOUNT.withdraw(275);
DBMS_OUTPUT.put_line(BANK_ACCOUNT.balance);
END;

Wednesday, 31 May 2017

PRAGMA EXCEPTION_INIT in oracle pl/sql

PRAGMA EXCEPTION_INIT
A pragma is a special instruction to the PL/SQL compiler. It is important to note that pragmas
are processed at the time of the compilation. The EXCEPTION_INIT pragma allows you to associate an
Oracle error number with the name of a user-defined error. After you associate an error name with an
Oracle error number, you can reference the error and write a handler for it.
/*
PLSQL Program to demonstrate how to handle PRE-DEFINED EXCEPTIONs
*/
DECLARE
E_EmpRemaining EXCEPTION;
PRAGMA EXCEPTION_INIT ( E_EmpRemaining , -2292 );
V_Deptno Emp.Deptno%TYPE := &Deptno;
BEGIN
DELETE FROM Dept
WHERE Deptno = V_Deptno;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('The given information is not found in the Database >. Check
for proper values........');
ELSE
NULL;
END IF;
ROLLBACK;
EXCEPTION
WHEN E_EmpRemaining THEN
DBMS_OUTPUT.PUT_LINE ( 'Unable to delete the Department Number ' || V_Deptno ||
' as the Employees are existing . Validate your relations and then try once again.' );
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE( ' The given information is missing in the Database . Check for
proper vslues.......' );
END;

/
/*
PLSQL Program to demonstrate PRAGMA.
*/
DECLARE
E_EmpExists EXCEPTION;
V_Count NUMBER(2);
V_SalSum NUMBER(6);
PRAGMA EXCEPTION_INIT ( E_EmpExists , -2292);
V_Empno Emp.Empno%TYPE := &Empno;
BEGIN
DELETE FROM Emp
WHERE Empno = V_Empno;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE (' The given Employee Number '|| V_Empno || ' is misssing
in the Database . Check for proper values.......');
ROLLBACK;
ELSE
COMMIT;
END IF;
EXCEPTION
WHEN E_EmpExists THEN
DBMS_OUTPUT.PUT_LINE( ' Unable to delete the Employee Details '|| V_Empno|| ' as
the Employee are existing. Validate your relations and then try once again...........' );
WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE ( ' The given information in the Database . Please Check for
proper values................' );
END;
/
/*
PLSQL Program to demonstrate PRAGMA.
*/
DECLARE
E_NotNullViolation EXCEPTION;
PRAGMA EXCEPTION_INIT( E_NotNullViolation , -1400 );
BEGIN
INSERT INTO Emp ( Empno , Ename , Job , Sal , Comm , Deptno )
VALUES( &Empno , 'HIMAN' , 'ANALYST', 2500 , NULL, &Deptno);
COMMIT;
EXCEPTION
WHEN E_NotNullViolation THEN
DBMS_OUTPUT.PUT_LINE(' A field which cannot be NULL is not attended . Please check
properly......');
END;
/
/*
PLSQL Program to demonstrate PRAGMA.
*/
DECLARE
E_NotNullViolation EXCEPTION;
PRAGMA EXCEPTION_INIT( E_NotNullViolation , -1400);

E_CheckViolation EXCEPTION;
PRAGMA EXCEPTION_INIT( E_CheckViolation , -2290);
BEGIN
INSERT INTO Emp VALUES
( &Empno , '&Ename' , '&Job' , &MGR , SYSDATE , &Sal , &Comm , &Deptno);
COMMIT;
EXCEPTION
WHEN E_CheckViolation THEN
DBMS_OUTPUT.PUT_LINE ( ' A field with CKECK Constraint is not attended
properly..............' );
WHEN E_NotNullViolation THEN
DBMS_OUTPUT.PUT_LINE( ' A Field with NOT NULL Constraint is not attended
properly...........' );
END;
/

DDL and DML operation in oracle

DDL
Data Definition Language
An Oracle database is comprised of the physical structures used to store,
manage, secure, and retrieve data.
A tablespace is the logical structure that allows you to manage a group of
datafiles.
Datafiles are the physical datafiles on disk.
The table is the object that stores data in a database.
Oracle provides a wide variety of table types. The default table type is heaporganized.
For most applications, a heap-organized table is an effective
structure for storing and retrieving data.
More on Datatypes---
¡Note If you insert values into a NUMBER(n,m) column and you exceed precision n, you get an error
message. If you exceed scale m, the Oracle DBMS rounds the value.
The Oracle DBMS supports many datatype synonyms for portability with other DBMS
implementations and for compliance with the ANSI/ISO standard. For example, CHARACTER is
identical to CHAR; DECIMAL(n,m) is identical to NUMBER(n,m); and NUMBER even has multiple synonyms,
such as INTEGER, REAL, and SMALLINT.

Each Oracle datatype has its own precision or length limits
shows 2000 and 4000 for the CHAR and VARCHAR2
datatype limits, respectively. You might wonder in which unit these numbers are expressed. That
depends on the value of the NLS_LENGTH_SEMANTICS parameter. The default for the
Oracle DBMS is to use BYTE length semantics
Creating a Heap-Organized Table
You use the CREATE TABLE statement to create tables. When creating a table, at minimum you must
specify the table name, column name(s), and data types associated with the columns. The Oracle default

table type is heap-organized. The term heap means that the data isnft stored in a specific order in the
table (instead, itfs a heap of data). Herefs a simple example of creating a heap-organized table with four
columns:
create table d_sources(
d_source_id number not null,
source_type varchar2(32),
create_dtt date default sysdate not null,
update_dtt timestamp(5)
);
If you donft specify a tablespace, then the table is created in the default permanent tablespace of the
user that creates the table
Implementing Virtual Columns
With Oracle Database 11g and higher, you can create a virtual column as part of your table
definition. A virtual column is based on one or more existing columns from the same table
and/or a combination of constants, SQL functions, and user-defined PL/SQL functions.
Virtual columns arenft stored on disk; theyfre evaluated at runtime when the SQL query
executes. Virtual columns can be indexed and can have stored statistics.
create table inv(
inv_id number
,inv_count number
,inv_status as (
case when inv_count <= 100 then 'GETTING LOW'
when inv_count > 100 then 'OKAY'
end)
);
SQL> insert into inv (inv_id, inv_count) values (1,100);
SQL> select * from inv;
Here is some sample output:
INV_ID INV_COUNT INV_STATUS
---------- ---------- -----------
1 100 GETTING LOW
Creating a Table from a Query
create table cwp_user_profile_101910
as select * from cwp_user_profile;
create table cwp_user_profile_test
as select * from cwp_user_profile
where 1=2;
Modifying a Table
Renaming a Table
There are a couple of reasons for renaming a table:
....To make the table conform to standards

....To better determine whether the table is being used before you drop it
This example renames a table from INV_MGMT to INV_MGMT_OLD:
SQL> rename inv_mgmt to inv_mgmt_old;
Adding a Column
Use the ALTER TABLE ... ADD statement to add a column to a table. This example adds a column to the
INV table:
SQL> alter table inv add(inv_count number);
Altering a Column
Occasionally, you need to alter a column to adjust its size or change its data type. Use the
ALTER TABLE
... MODIFY statement to adjust the size of a column. This example changes the size of a
column to 256
characters:
SQL> alter table inv modify inv_desc varchar2(256);
If any rows have a NULL value for the column youfre modifying to NOT NULL, then you must
first update the column to contain a value. Here is an example of modifying a column to
NOT NULL:
SQL> alter table inv modify(inv_desc not null);
You can also alter the column to have a default value. The default value is used any time a
record is
inserted into the table but no value is provided for a column:
SQL> alter table inv modify(inv_desc default 'No Desc');
If you want to remove the default value of a column, then set it to be NULL:
SQL> alter table inv modify(inv_desc default NULL);
Renaming a Column
There are a couple of reasons to rename a column:
....Sometimes requirements change, and you want to modify the column name to
better reflect what the column is used for.
....If youfre planning to drop a column, it doesnft hurt to rename the column first to
better determine whether any users or applications are accessing the column.
SQL> alter table inv rename column inv_count to inv_amt;
Dropping a Column
SQL> alter table inv drop (inv_name);
SQL> alter table inv set unused (inv_name);

SQL> alter table inv drop unused columns;
Displaying Table DDL
SQL> set long 10000
SQL> select dbms_metadata.get_ddl('TABLE','EMP') from dual;
Dropping a Table
SQL> drop table inventory;
If you attempt to drop a parent table that has a primary key or unique keys referenced as a foreign
key in a child table, you see an error such as
ORA-02449: unique/primary keys in table referenced by foreign keys
You need to either drop the referenced foreign-key constraint(s) or use the CASCADE CONSTRAINTS
option when dropping the parent table:
SQL> drop table inventory cascade constraints;
You must be the owner of the table or have the DROP ANY TABLE system privilege to drop a table. If
you have the DROP ANY TABLE privilege, you can drop a table in a different schema by prepending the
schema name to the table name:
SQL> drop table inv_mgmt.inventory;
Undropping a Table
Suppose you accidentally drop a table, and you want to restore it. First, verify that the table you want to
restore is in the recycle bin:
SQL> show recyclebin;
Here is some sample output:
ORIGINAL NAME RECYCLEBIN NAME OBJECT TYPE DROP TIME
---------------- ------------------------------ ------------ -------------------
PURCHASES BIN$YzqK0hN3Fh/gQHdAPLFgMA==$0 TABLE 2009-02-18:17:23:15
Next, use the FLASHBACK TABLE...TO BEFORE DROP statement to recover the dropped table:
SQL> flashback table purchases to before drop;
Note You canft FLASHBACK TABLE...TO BEFORE DROP for a table created in the SYSTEM tablespace
Removing Data from a Table
You can use either the DELETE statement or the TRUNCATE statement to remove records from a table. You
need to be aware of some important differences between these two approaches
Features of DELETE and TRUNCATE

Using DELETE
One big difference is that the DELETE statement can be either committed or rolled back. Committing a
DELETE statement makes the changes permanent:
SQL> delete from inv;
SQL> commit;
If you issue a ROLLBACK statement instead of COMMIT, the table contains data as it was before the
DELETE was issued.
Using TRUNCATE
TRUNCATE is a DDL statement. This means Oracle automatically commits the statement (and the current
transaction) after it runs, so there is no way to roll back a TRUNCATE statement. If you need the option of
choosing to roll back (instead of committing) when removing data, then you should use the DELETE
statement. However, the DELETE statement has the disadvantage that it generates a great deal of undo
and redo information. Thus for large tables, a TRUNCATE statement is usually the most efficient way to
remove data.
SQL> truncate table computer_systems;
Data Manipulation.
how to change the contents of an Oracle database. The SQL commands to change the database contents are commonly referred to
as Data Manipulation Language (DML) commands.
The first four sections of this chapter cover the DML commands INSERT, UPDATE, DELETE,
and MERGE.
The INSERT Command
Standard INSERT Commands
The standard INSERT command supports the following two ways to insert rows:
. Use the VALUES clause, followed by a list of column values (between parentheses).
This method allows you to insert only one row at a time per execution of the INSERT
command.
. Formulate a subquery, thus using existing data to generate new rows.
You can use the reserved word NULL to specify a null value for a specific column. You can also
specify the reserved word DEFAULT to instruct the Oracle DBMS to insert the default value associated

with the corresponding column
If you donft specify a value for a specific column in your INSERT
statement, there are two possibilities:
. If the column has an associated DEFAULT value, the Oracle DBMS will insert that value.
. If you did not define a DEFAULT value for the column, the Oracle DBMS inserts a null
value (provided, of course, that the column allows null values).
.
QL> CREATE TABLE SampleUPD
2 (
3 SampID NUMBER(2)
4 DEFAULT 99,
5 SampName VARCHAR2(10)
6 DEFAULT 'NOT GIVEN',
7 SampDate DATE
8 DEFAULT SYSDATE
9 );
Table created.

SQL> INSERT INTO SampleUPD
2 VALUES(1, 'SAMPLE01', '26-JUN-09');
1 row created.
SQL> INSERT INTO SampleUPD
2 VALUES(2, 'SAMPLE02', '27-JUN-09');
1 row created.
1 INSERT INTO SampleUPD(SampID, SampName)
2* VALUES(3, 'SAMPLE03')
SQL> /
1 row created.
SQL> ed
Wrote file afiedt.buf
1 INSERT INTO SampleUPD(SampID, SampDate)
2* VALUES(3, '21-JUN-09')
SQL> /
1 INSERT INTO SampleUPD(SampName, SampDate)
2* VALUES('SAMPLE04', '21-JUN-09')
SQL> /
1 row created.
SQL> ed
Wrote file afiedt.buf

1 INSERT INTO SampleUPD(SampID, SampName, SampDate)
2* VALUES(4, 'SAMPLE04', DEFAULT)
SQL> /
1 row created.
SQL> SELECT * FROM SampleUPD;
SAMPID SAMPNAME SAMPDATE
---------- ---------- ---------
1 SAMPLE01 26-JUN-09
2 SAMPLE02 27-JUN-09
3 SAMPLE03 29-JUN-09
3 NOT GIVEN 21-JUN-09
99 SAMPLE04 21-JUN-09
4 SAMPLE04 29-JUN-09
SQL> CREATE TABLE MyBonus
2 (
3 Empno NUMBER,
4 Bonus NUMBER DEFAULT 100
5 );
Table created.
SQL> SELECT E.Empno
2 FROM Emp E
3 WHERE Job = 'SALESMAN';
EMPNO
----------
7654

7499
7844
7521
SQL> INSERT INTO MyBonus(Empno)
2 (SELECT E.Empno
3 FROM Emp E
4 WHERE Job = 'SALESMAN');
4 rows created.
SQL> SELECT * FROM MyBonus;
EMPNO BONUS
---------- ----------
7654 100
7499 100
7844 100
7521 100
The UPDATE Command
You can change column values of existing rows in your tables with the UPDATE command
. UPDATE: The table you want to update
. SET: The change you want to apply
. WHERE: The rows to which you want to apply the change

the SET clause offers two alternatives:
. You can specify a comma-separated list of single-column changes. With this approach, you can use the DEFAULT keyword as
an expression. This allows you to change column default values in the data dictionary at any point in time without the need to
change the UPDATE commands in your applications.
. You can drive the change with a subquery. The subquery must provide the right number of values for the list of column names
specified between the parentheses. Of course, the datatypes should also match, or the Oracle DBMS should at least be able to
convert values to the appropriate datatypes on the fly.
1 UPDATE EMP
2 SET
3* Sal = NULL
SQL> UPDATE EMP
2 SET
3 Comm = NULL
4 WHERE Job = 'CLERK';
SQL> ROLLBACK;
SQL> SELECT Ename, Sal, Deptno, Job
2 FROM Emp
3 WHERE Ename = 'ALLEN';
ENAME SAL DEPTNO JOB
---------- ---------- ---------- ---------
ALLEN 1600 30 SALESMAN
SQL> UPDATE Emp

2 SET
3 Job = 'MANAGER',
4 Sal = 2500,
5 Deptno = 10
6 WHERE Ename = 'ALLEN';
1 row updated.
SQL> ed
Wrote file afiedt.buf
1 UPDATE Emp
2 SET
3 Job = 'MANAGER',
4 Sal = 2500,
5* Deptno = 10
SQL> /
14 rows updated.
SQL> SELECT Ename, Sal, Deptno, Job
2 FROM Emp;
ENAME SAL DEPTNO JOB
---------- ---------- ---------- ---------
KING 2500 10 MANAGER
BLAKE 2500 10 MANAGER
CLARK 2500 10 MANAGER
JONES 2500 10 MANAGER
MARTIN 2500 10 MANAGER
ALLEN 2500 10 MANAGER
TURNER 2500 10 MANAGER

JAMES 2500 10 MANAGER
WARD 2500 10 MANAGER
FORD 2500 10 MANAGER
SMITH 2500 10 MANAGER
ENAME SAL DEPTNO JOB
---------- ---------- ---------- ---------
SCOTT 2500 10 MANAGER
ADAMS 2500 10 MANAGER
MILLER 2500 10 MANAGER
14 rows selected.
SQL> ROLLBACK;
Rollback complete.
QL> UPDATE Emp
2 SET
3 Job = 'CLERK',
4 Sal = 600,
5 Deptno = 10
6 WHERE Ename = 'ALLEN';
1 row updated.
SQL> UPDATE Emp
2 SET
3 Job = 'ANALYST',
4 Sal = Sal + 1000
5 WHERE Ename = 'BLAKE'
6
SQL> SELECT Ename, Sal

2 FROM Emp
3 WHERE Ename = 'BLAKE';
ENAME SAL
---------- ----------
BLAKE 2850
SQL> UPDATE Emp
2 SET
3 Job = 'ANALYST',
4 Sal = Sal + 1000
5 WHERE Ename = 'BLAKE';
1 row updated.
SQL> SELECT Ename, Sal
2 FROM Emp
3 WHERE Ename = 'BLAKE';
ENAME SAL
---------- ----------
BLAKE 3850
SQL> ed
Wrote file afiedt.buf
1 UPDATE Emp
2 SET
3 Job = (SELECT Job
4 FROM Emp
5 WHERE Ename = 'MILLER'),
6 Sal = 1000 + (SELECT Sal

7 FROM Emp
8 WHERE Ename = 'ALLEN'),
9 Deptno = (SELECT Deptno
10 FROM Emp
11 WHERE Ename = 'TURNER')
12* WHERE Ename = 'BLAKE'
SQL> /
1 row updated.
SQL> UPDATE Emp
2 SET
3 (Job, Deptno) = (SELECT Job, Deptno
4 FROM Emp
5 WHERE Empno = 7499)
6 WHERE Empno = 7698;
1 row updated.
The DELETE Command
The simplest data manipulation command is DELETE, This command also operates at the table level, and you use the WHERE
clause to restrict the set of rows you want to delete from the table. If you omit the WHERE clause, the DELETE command
results in an empty table.
Note the difference between the following two commands:
SQL> drop table departments;
SQL> delete from departments;

The DROP TABLE command not only removes the contents of the table, but also the table
itself, including all dependent objects/structures such as indexes and privileges. DROP TABLE is a
data definition (DDL) command. The DELETE command does not change the database structure,
but only the contents.it is a data manipulation (DML) command. Moreover, the effects of a
DROP TABLE command cannot be undone with a ROLLBACK command, as opposed to the effects of
a DELETE command, which can.
Example of a DELETE Command
SQL> delete from salgrades
2 where grade = 5;
1 row deleted.
SQL> rollback;
Rollback complete.
SQL>
Alternative DELETE Command,Using a Subquery
SQL> delete from (select *
2 from salgrades
3 where grade = 5);
1 row deleted.
SQL> rollback;
Rollback complete.
SQL>
The TRUNCATE command allows you to delete all rows of a table in a
more efficient way than with the DELETE command. The TRUNCATE command belongs to the
category of the data definition (DDL) commands,
The MERGE Command
It is able to perform insertions, updates, and deletions in a single statement. This makes
the MERGE command very efficient in data warehouse environments, where the tables
are often populated/updated from external sources.
SQL> cl scr
SQL> CREATE TABLE MyBonus
2 (
3 Empno NUMBER,
4 Bonus NUMBER DEFAULT 100
5 );
Table created.
SQL> SELECT E.Empno
2 FROM Emp E
3 WHERE Job = 'SALESMAN';
EMPNO

----------
7654
7499
7844
7521
SQL> INSERT INTO MyBonus(Empno)
2 (SELECT E.Empno
3 FROM Emp E
4 WHERE Job = 'SALESMAN');
4 rows created.
SQL> SELECT * FROM MyBonus;
EMPNO BONUS
---------- ----------
7654 100
7499 100
7844 100
7521 100
SQL> SELECT Empno, Sal, Deptno
2 FROM Emp
3 WHERE Deptno = 30;
EMPNO SAL DEPTNO
---------- ---------- ----------
7698 2850 30
7654 1250 30
7499 1600 30
7844 1500 30
7900 950 30
7521 1250 30
6 rows selected.
SQL> MERGE INTO MyBonus B
2 USING (SELECT Empno, Sal, Deptno
3 FROM Emp
4 WHERE Deptno = 30) S
5 ON (B.Empno = S.Empno)
6 WHEN MATCHED THEN
7 UPDATE
8 SET B.Bonus = B.Bonus + S.Sal * 0.1
9 DELETE
10 WHERE (S.Sal > 4000)
11 WHEN NOT MATCHED THEN
12 INSERT(B.Empno, B.Bonus)
13 VALUES(S.Empno, S.Sal * 0.1)
14 WHERE(S.Sal <= 4000);
6 rows merged.

SQL> SELECT * FROM MyBonus;
EMPNO BONUS
---------- ----------
7654 225
7499 260
7844 250
7521 225
7698 285
7900 95
6 rows selected
Savepoints
You can define ginterim points,h known as savepoints, within your transactions. During a
transaction, you can roll back to such savepoints without rolling back the transaction as a whole,
thus maintaining the changes you made before the savepoint.
Using Savepoints Within a Transaction
SQL> delete from history where empno=7654;
2 rows deleted.
SQL> delete from employees where empno=7654;
1 row deleted.
SQL> savepoint ONE;
Savepoint created.
SQL> delete from offerings where course='ERM';
1 row deleted.
SQL> delete from courses where code ='ERM';
1 row deleted.
SQL> rollback to savepoint ONE;
Rollback complete.
SQL> select description
2 from courses
3 where code='ERM';
DESCRIPTION
----------------------------------------------
Data modeling with ERM
SQL> rollback;
Rollback complete.