Monday, October 22, 2012

SQL Statements

DDL


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

DML


Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

DCL


Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

TCL


Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

Wednesday, October 17, 2012

Abstract Datatypes:

Abstract Datatypes:

   Abstract Datatypes are datatypes that consist of one or more subtypes. Rather than being constrained to the standard Oracle datatypes of NUMBER, DATA, and VARCHAR2, abstract datatypes can more accurately describe your data.

Ex:-
     create type ADDRESS_TY as object
      (Street  VARCHAR2(20),
       City    VARCHAR2(10),
       State   CHAR(10),
       Pin     NUMBER);

     Now the datatype ADDRESS_TY is been created. You can use this datatype alongwith other datatypes. For ex. will create a standard datatype for people which contain Name and address of a person.

   create type PERSON_TY as object
    ( Name VARCHAR2(20),
      Address ADDRESS_TY);

Now PERSON_TY contains Name and address of a person  we can use this to create table.

    You can't insert data into PERSON_TY. The reason is straightforward: A datatype describes data, it does not store data. You cannot store data in a NUMBER datatype, and you cannot store data in a datatype that you define, either. To store data, you have to create a table that uses your datatype.

The following command create a table name CUSTOMER.

  create table CUSTOMER
  (Customer_ID NUMBER,
   Person    PERSON_TY);
 
 To Insert rows into CUSTOMER do following

  insert into CUSTOMER VALUES
   (1, PERSON_TY('HARI',ADDRESS_TY('#102 Lokhand wala','mumbai','MH',10101);
 
to select data from CUSTOMER table

    Select customer_ID, c.person.name
     from CUSTOMER C;

  First, Note that the access of the datatype's attribute requires the use of a table alias. A table alias, also known as a correlation variable, allows Oracle to resolve any ambiguity regarding the name of the object being selected. As a column name, Person.Name points to the Name attribute within the PERSON_TY datatype. The format for the column name is
     correlation.Column.Attribute

   to select Street which is availabe in ADDRESS_TY
 correlation.Column.column.Attribute
   
    C.PERSON.ADDRESS.STREET  

Autonomous Transactions:

Autonomous Transactions:
------------------------------------------

The easiest way to understand autonomous transactions is to see them in action.

CREATE TABLE at_test (
      id               NUMBER            NOT NULL,
     description  VARCHAR2(50)  NOT NULL
   );

INSERT INTO at_test (id, description) VALUES (1, 'Description for 1');
INSERT INTO at_test (id, description) VALUES (2, 'Description for 2');

SELECT * FROM at_test;

        ID DESCRIPTION
---------- --------------------------------------------------
         1 Description for 1
         2 Description for 2

2 rows selected.


Next, we insert another 8 rows using an anonymous block declared as an autonomous transaction, which contains a commit statement.



DECLARE
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  FOR i IN 3 .. 10 LOOP
    INSERT INTO at_test (id, description)
    VALUES (i, 'Description for ' || i);
  END LOOP;
  COMMIT;
END;
/

PL/SQL procedure successfully completed.

SELECT * FROM at_test;

        ID DESCRIPTION
---------- --------------------------------------------------
         1 Description for 1
         2 Description for 2
         3 Description for 3
         4 Description for 4
         5 Description for 5
         6 Description for 6
         7 Description for 7
         8 Description for 8
         9 Description for 9
        10 Description for 10

10 rows selected.


As expected, we now have 10 rows in the table. If we now issue a rollback statement we get the following result.


ROLLBACK;
SELECT * FROM at_test;

        ID DESCRIPTION
---------- --------------------------------------------------
         3 Description for 3
         4 Description for 4
         5 Description for 5
         6 Description for 6
         7 Description for 7
         8 Description for 8
         9 Description for 9
        10 Description for 10

8 rows selected.


The 2 rows inserted by our current session (transaction) have been rolled back, while the rows inserted by the autonomous transactions remain.

The presence of the PRAGMA AUTONOMOUS_TRANSACTION compiler directive made the anonymous block run in its own transaction, so the internal commit statement did not affect the calling session.

Clusters

Clustering :

It is a mechanism to bind the data together.. to achieve clustering clusters are used...

syntax for creating a cluster :

create cluster
( cluster_column   )

ex :
create cluster deptno_cluster
( deptno number );

Syntax for Creating a cluster Table :

create table
(
column_name ,
.
.
cluster_column
)cluster cluster_name( cluster_column )

create table emp_cluster_tab
(
empno number,
ename varchar2(10),
sal number,
deptno number
)cluster deptno_cluster( deptno )

Note : Cluster tables cant be used before indexing the cluster...

Indexes :

Usage : It is used for improving the performance of retrieval of data whenever the search condition is specified is an indexed column..

syntax :

create index
on table table_name( column_name )

create index ename_ind on table emp( ename )

select * from emp where ename = 'SMITH'

Rules for using Indexes :

* Table should contain more than 20000 records

* Table row's should be large with more no. of null values in a column..

* If the table's data is more and only 2-4% of its data should be retrieved

* If a column is very frequently used in a where or join condition..

Note :
* The info. about the indexes can be retrieved from user_indexes..

select * from user_indexes where index_name like 'ENAME_IND'

* To retrieve the info. about the columns on which indexes are defined can be retrieved from user_ind_columns..

select column_name from user_ind_columns
where table_name = 'EMP';

unique index : If a column is defined with an unique index then it will implictly define an unique constraint on that column..

syntax :
create unique index
on table table_name( column )

create unique index eno_ind on emp( empno )

Cluster Index : To index a cluster it is used..
syntax :
create index
on cluster cluster_name;

create index deptno_cluster_index
on cluster deptno_cluster;


insert into emp_cluster_tab
values( 101,'sekhar',15000,10 );

select * from emp_cluster_tab;

Note :
* The information about the clusters can be retrieved from user_clusters..

Codd Rules

Rule 1: The information rule:

    All information in the database is to be represented in one and only one way,
ie in the form of rows and columns.



Rule 2: The guaranteed access rule:

    All data must be accessible.
   If you are able to store,  you should able to retrieve.

Rule 3: Systematic treatment of null values:

    The DBMS must allow each field to remain null (or empty). Specifically, it must support a representation of "missing information and inapplicable information" that is systematic.

Treatment of null values should be same irrespective of datatype.

Rule 4: Active online catalog based on the relational model:

     That is, users must be able to access the database's structure (catalog) using the same query language that they use to access the database's data.


Rule 5: The comprehensive data sublanguage rule:

   
Rule 6: The view updating rule:

    All views that are theoretically updatable must be updatable by the system.


Rule 7: High-level insert, update, and delete:

    The system must support set-at-a-time insert, update, and delete operators.

 This rule states that insert, update, and delete operations should be supported for any retrievable set rather than just for a single row in a single table.

Rule 8: Physical data independence:

    Changes to the physical level (how the data is stored, whether in arrays or linked lists etc.) must not require a change to an application based on the structure.

Rule 9: Logical data independence:

    Changes to the logical level (tables, columns, rows, and so on) must not require a change to an application based on the structure. Logical data independence is more difficult to achieve than physical data independence.

Rule 10: Integrity independence:

    Integrity constraints must be specified separately from application programs and stored in the catalog. It must be possible to change such constraints as and when appropriate without unnecessarily affecting existing applications.

Rule 11: Distribution independence:

   
Rule 12: The nonsubversion rule:

    If the system provides a low-level (record-at-a-time) interface, then that interface should not subvert the system,





Execute Immediate

EXECUTE IMMEDIATE:
----------------------------------

One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDIATE" statement (native SQL). Examples:

begin
  EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';
end;

begin
execute Immediate 'TRUNCATE TABLE emp';
end;


Exist , Merge Etc...

Exists:
-------------

The EXISTS condition is considered "to be met" if the subquery returns at least one row.

The syntax for the EXISTS condition is:

SELECT columns
FROM tables
WHERE EXISTS ( subquery );

Ex:
---

SELECT *
FROM dept
WHERE EXISTS
  (select *
    from emp
    where dept.deptno = emp.deptno);


--------------------------------------

Not Exists:


SELECT *
FROM dept
WHERE NOT EXISTS
  (select *
    from emp
    where dept.deptno = emp.deptno);


-------------------------------------

Merge:


create table student10 ( sno number(3),
             sname varchar2(20),
             marks number(3));

insert into student10 values ( 101, 'arun',30);
insert into student10 values ( 102, 'anil',40);
insert into student10 values ( 103, 'kiran',50);



create table student20 ( sno number(3),
             sname varchar2(20),
             marks number(3));


insert into student20 values ( 101, 'JOHN',30);
insert into student20 values ( 105, 'SMITH',50);



merge into student10 s1
using student20 s2
on ( s1.sno = s2.sno)
when matched
then update set sname=s2.sname, marks = s2.marks
when not matched
then insert (sno,sname,marks ) values (s2.sno,s2.sname,s2.marks);



------------------------------
Decode :

select empno,sal,job , decode (job, 'CLERK' , sal*2,   
                    'MANAGER', sal*3
                             ,sal  ) new_sal
from emp;   


select ename,sal, deptno, decode(deptno, 10, 'CA',
                    20, 'SCIENTIST',
                        'EMPLOYEE') NEW_NAME
from emp;


------------------------------------------

Case :

select empno,sal,job , case job when 'CLERK' then sal*2
                   when 'MANAGER' then sal*3
                                                  else sal
                                    end new_sal
from emp;   


Case 2nd example:
------------------------
SELECT ename, sal, deptno,
       CASE deptno
          WHEN 10
             THEN 'ten'
          WHEN 20
             THEN 'twenty'
          WHEN 30
             THEN 'thirty'
          ELSE NULL
       END dept_no
  FROM emp;

----------------------------------------

Rank :

In Oracle/PLSQL, the rank function returns the rank of a value in a group of values.

The rank function can be used two ways - as an Aggregate function or as an Analytic function.

---
Rank used as aggregate function:

select rank (800) within  group (order by sal) rank from emp;

select rank (850) within  group (order by sal) rank from emp;

select rank (5000) within  group (order by sal) rank from emp;


Rank used as analytical function:

As an Analytic function, the rank returns the rank of each row of a query

select ename, sal,
rank() OVER (ORDER BY sal) rank
from emp;


--------------------------
NULLIF :

In Oracle/PLSQL, the NULLIF function compares expr1 and expr2. If expr1 and expr2 are equal, the NULLIF  function returns NULL. Otherwise, it returns expr1.

The syntax for the NULLIF function is:

    NULLIF( expr1, expr2 )



select NULLIF(12,12) from dual;   --  returns NULL

select NULLIF(12,13) from dual;   -- returns 12

-------------------------------

Joins

 select * from emp

EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO - Total records 15

--insert into emp(EMPNO, ENAME, JOB, SAL) values(7979, 'KILLER', 'ANALYST', 1200);

--commit;

select * from dept

DEPTNO, DNAME, LOC - Total records 4


/* Cartesian Product */

select * from emp, dept;


/* Equijoins */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DNAME, dept.LOC
from emp emp, dept
where emp.DEPTNO = dept.DEPTNO;

/* AND Operator */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DNAME, dept.LOC
from emp emp, dept
where emp.DEPTNO = dept.DEPTNO
--AND dept.DEPTNO = 30
AND emp.sal >= 1500;

/* Non-Equijoins */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DNAME, dept.LOC
from emp emp, dept
where emp.DEPTNO = dept.DEPTNO
and emp.SAL between 1500 and 5000;


/* LEFT Outer Joins */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp, dept
where emp.DEPTNO = dept.DEPTNO(+);

/* RIGHT Outer Joins */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp, dept
where emp.DEPTNO(+) = dept.DEPTNO;


/* Self Joins */

select employee.ENAME || ' works for ' || manager.ENAME "Emp and Manager"
from emp employee, emp manager
where employee.MGR = manager.EMPNO;


/* Cross Joins */

select *
from emp Cross Join dept;


/* Natural Joins */

select EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, DNAME, LOC
from emp Natural Join dept;

--where emp.DEPTNO = dept.DEPTNO;

/* USING Clause */

select EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, DNAME, LOC
from emp Join dept
USING(DEPTNO);

/* ON Clause */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp JOIN dept
ON (emp.DEPTNO = dept.DEPTNO);

/* INNER JOIN */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp INNER JOIN dept
ON (emp.DEPTNO = dept.DEPTNO);

/* LEFT OUTER JOIN */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp
LEFT OUTER JOIN dept
ON (emp.DEPTNO = dept.DEPTNO);

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp, dept
where emp.DEPTNO = dept.DEPTNO(+);

/* RIGHT OUTER JOIN */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp
RIGHT OUTER JOIN dept
ON (emp.DEPTNO = dept.DEPTNO);

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp, dept
where emp.DEPTNO(+) = dept.DEPTNO;

/* FULL OUTER JOIN */

select emp.EMPNO, emp.ENAME, emp.JOB, emp.MGR, emp.HIREDATE, emp.SAL, emp.COMM, emp.DEPTNO, dept.DEPTNO, dept.DNAME, dept.LOC
from emp emp
FULL OUTER JOIN dept
ON (emp.DEPTNO = dept.DEPTNO);

Large Objects

create table model_profiles
(
model_id number,
model_name varchar2(20),
photo blob,
profile clob,
protfolio bfile
);

insert into model_profiles
(model_id,model_name,photo,profile ) values( 101,'rekha',empty_blob(), 'This is my profile.........' );

select * from model_profiles; --Error...

select model_id, model_name, profile
from model_profiles;

c:\userprofiles\rekha.avi

sql> create directory userdb_dir
as 'c:\userprofiles';

Note : Inorder to create the directory object the user should have the Create Any Directory privilege...

bfilename : It is a method which is used for binding the file present in the OS level to the database...

update model_profiles
set protfolio = bfilename( userdb_dir, 'rekha.avi' )
where model_id = 101;

LOB and BFILE

// Large Objects Types: (LOBs)
--> BFILE,BLOB,CLOB and NCLOB
--> They allow U to store blocks of unstructured data such as text, graphic images, video clips and sound waves, upto 4 GB in size
--> LOBs also alow random, piece wise access to the data
--> LOB is made up of two distinct parts - Value and Locator
--> Value is the actual data that will be stored
--> Locater is an indicator that specifies the location of the object in the database
--> A column based on LOB type is called as LOB Column
--> The LOB column stores the locator of the object
--> The LOBs can be stored inside the db (Internal LOB or in-line) or outside the db (External LOB or off-line) ie., in the os files

a) BFILE:
--> Used to store large binary objects in os files outside db if its size is > 4 GB, inside db if size is <4 br="br" gb="gb">
b) BLOB :
--> To store Large binary objects inside the db (Upto 4 GB)

c) CLOB:
--> CLOB is similar to LONG datatype, except that CLOB are used to store large blocks of single-byte character data in the db

d) NCLOB:
--> is used to store large blocks of single-byte or multi byte NCHAR data in the database based on the National Language Character set

// Managing Large Objects:

i) Creating table with LOB columns :
Ex: Create table airbus_desc (airbusno char(5), airbus_det bfile, airbus_profile clob);

ii) Inserting values in LOBs:
--> To insert value in the BFILE, the function bfilename is used.
--> It takes the os path of the directory and the name of the file
Ex: Insert into airbus_desc values ('AB01',bfilename('c:\orant\bin\desc_dir','airbus_desc.doc'), 'The description of the plane is as follows:');

iii) Displaying data from LOBs :
--> Data from LOBs cannot be displayed, except for CLOB by using Select statment
Ex:
Select airbusno_airbus_profile from airbus_desc;

Collections



Oracle now supports three types of collections:
  • PL/SQL tables are singly dimensioned, unbounded, sparse collections of homogeneous elements and are available only in PL/SQL.These are now called index-by tables.
  • Nested tables are also singly dimensioned, unbounded collections of homogeneous elements. They are initially dense but can become sparse through deletions. Nested tables are available in both PL/SQL and the database (for example, as a column in a table).
  • VARRAYs, like the other two collection types, are also singly dimensioned collections of homogeneous elements. However, they are always bounded and never sparse. Like nested tables, they can be used in PL/SQL and in the database. Unlike nested tables, when you store and retrieve a VARRAY, its element order is preserved.
Using a nested table or VARRAY, you can store and retrieve nonatomic data in a single column. For example, the employee table used by the HR department could store the date of birth for each employee's dependents in a single column, as shown below.


Id (NUMBER)
Name (VARCHAR2)
Dependents_ages (Dependent_birthdate_t)
10010
Zaphod Beeblebrox
12-JAN-1763
4-JUL-1977
22-MAR-2021
10020
Molly Squiggly
15-NOV-1968
15-NOV-1968
10030
Joseph Josephs

10040
Cepheus Usrbin
27-JUN-1995
9-AUG-1996
19-JUN-1997
10050
Deirdre Quattlebaum
21-SEP-1997

It's not terribly difficult to create such a table. First we define the collection type:
CREATE TYPE Dependent_birthdate_t AS VARRAY(10) OF DATE;
Now we can use it in the table definition:
CREATE TABLE employees (
   id NUMBER,
   name VARCHAR2(50),
   ...other columns...,
   Dependents_ages Dependent_birthdate_t
);
We can populate this table using the following INSERT syntax, which relies on the type's default constructor to transform a list of dates into values of the proper datatype:
INSERT INTO employees VALUES (42, 'Zaphod Beeblebrox', ...,
   Dependent_birthdate_t( '12-JAN-1765', '4-JUL-1977', '22-MAR-2021'));

Differences
One chief difference between nested tables and VARRAYs surfaces when we use them as column datatypes. Although using a VARRAY as a column's datatype can achieve much the same result as a nested table, VARRAY data must be predeclared to be of a maximum size, and is actually stored "inline" with the rest of the table's data.
Nested tables, by contrast, are stored in special auxiliary tables called store tables, and there is no pre-set limit on how large they can grow. For this reason, Oracle Corporation says that VARRAY columns are intended for "small" arrays, and that nested tables are appropriate for "large" arrays.

Nested Table

Nested Table:
  Nested table is a collection of rows, represented as a column within the main table. For each record within the main table, the nested table may contain multiple rows. In one sense, it's a way of storing a one-to-many relationship within one table, Consider a table that contains information about departments, each of which may have many projects in progress at any one time. In a strictly relational model, you would create two separate tables - DEPT and PROJECT.
  nested table allow you to store the information about projects within the DEPT table. The PROJECT table records can be accessed directly via the DEPT table, without the need to perform a join. The ability to select the data without traversing joins may make data easier to access for users. Even if you do not define methods for accessing the nested data, you have clearly associated the department and project data. In a strictly relational model, the association between the DEPT and PROJECT tables would be accomplished via foreign key relationships.



SQL> create or replace type emp_ty as object
  2  (desg varchar2(10),
  3  dname varchar2(10),
  4  doj date);
  5  /

Type created.

SQL> create type emp_nt as table of emp_ty;
  2  /

Type created.

SQL> create table empdata
  2  (ename varchar2(10),
  3  details emp_nt)
  4  nested table details store as emp_nt_tab;

Table created.

SQL> desc empdata
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ENAME                                              VARCHAR2(10)
 DETAILS                                            EMP_NT

SQL> set describe depth 2
SQL> desc empdata
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ENAME                                              VARCHAR2(10)
 DETAILS                                            EMP_NT
   DESG                                             VARCHAR2(10)
   DNAME                                            VARCHAR2(10)
   DOJ                                              DATE


SQL> ed
Wrote file afiedt.buf

  1  insert into empdata values (
  2  'Raju',
  3  emp_nt(
  4  emp_ty('Clerk','Sales','12-Sep-05'),
  5  emp_ty('Asst','Mrkt','15-Oct-04'),
  6* emp_ty('Mngr','Sales','13-Aug-05')))
SQL> /

1 row created.

SQL> select * from empdata;

ENAME
----------
DETAILS(DESG, DNAME, DOJ)
--------------------------------------------------------------------------------
Raju
EMP_NT(EMP_TY('Clerk', 'Sales', '12-SEP-05'), EMP_TY('Asst', 'Mrkt', '15-OCT-04'
), EMP_TY('Mngr', 'Sales', '13-AUG-05'))


SQL>  select ename,n.desg,n.doj from empdata,table(empdata.details) n;

ENAME      DESG       DOJ
---------- ---------- ---------
Raju       Clerk      12-SEP-05
Raju       Asst       15-OCT-04
Raju       Mngr       13-AUG-05

Partition Table

Partitions

  Partition is a technique which is very useful when the database is very large and has to be accessed a number of times. One of the drawbacks of having  a partitioned table is that it cannot have user-defined types in it.


ex:

  Create table ord_mast(orderno varchar2(5) primary key,odate date,vencode varchar2(5),O_status char(1) check (O_status in ('p','c')) partition by range(orderno)
(partition om1 values less than (o010), partition om2 values less than (o020));

Inserting records into partitioned table:

  The records are stored in the partitions of a table based on the partition key specified. The partition key specified in the insert statement is compared with partition bound defined when creating the partition table.


sql> insert into ord_mast values ('o001','10-12-99','v001','p');

sql> insert into ord_mast values ('o010','10-1-99','v002','c');

sql> insert into ord_mast values ('o012','1-12-99','v001','c');


Querying the partitions individually an be performed as under.


  sql> select * from ord_mast partition(om2);


REF Cursor

Introduction to REF CURSOR

A REF CURSOR is basically a data type.  A variable created based on such a data type is generally called a cursor variable.  A cursor variable can be associated with different queries at run-time.

Let us start with a small sub-program as follows:



%ROWTYPE with REF CURSOR

In the previous section, I retrieved only one column (ename) of information using REF CURSOR.  Now I would like to retrieve more than one column (or entire row) of information using the same.  Let us consider the following example:

declare
  type r_cursor is REF CURSOR;
  c_emp r_cursor;
  er emp%rowtype;
begin
  open c_emp for select * from emp;
  loop
      fetch c_emp into er;
      exit when c_emp%notfound;
      dbms_output.put_line(er.ename || ' - ' || er.sal);
  end loop;
  close c_emp;
end;

**************************************************

As defined earlier, a REF CURSOR can be associated with more than one SELECT statement at run-time.  Before associating a new SELECT statement, we need to close the CURSOR.  Let us have an example as follows:

declare
  type r_cursor is REF CURSOR;
  c_emp r_cursor;
  type rec_emp is record
  (
    name  varchar2(20),
    sal   number(6)
  );
  er rec_emp;
begin
  open c_emp for select ename,sal from emp where deptno = 10;
  dbms_output.put_line('Department: 10');
  dbms_output.put_line('--------------');
  loop
      fetch c_emp into er;
      exit when c_emp%notfound;
      dbms_output.put_line(er.name || ' - ' || er.sal);
  end loop;
  close c_emp;
  open c_emp for select ename,sal from emp where deptno = 20;
  dbms_output.put_line('Department: 20');
  dbms_output.put_line('--------------');
  loop
      fetch c_emp into er;
      exit when c_emp%notfound;
      dbms_output.put_line(er.name || ' - ' || er.sal);
  end loop;
  close c_emp;
end;

************************************************

WHERE CURRENT OF:

WHERE CURRENT OF clause is used in some UPDATE statements.

The WHERE CURRENT OF clause is an UPDATE or DELETE statement states that the most recent row fetched from the table should be updated.

We must declare the cursor with FOR UPDATE clause to use this feature.

When the session opens the cursor with the FOR UPDATE clause, all rows in the return set will hold row-level locks. Other sessions can only query for the rows, but cannot update or delete.


declare
cursor c1
is
select empno,ename,sal from emp
where comm is null
for update of comm;

var_comm number(4);
begin
for cur_rec in c1 loop
if cur_rec.sal < 2000 then
var_comm:=200;
elsif cur_rec.sal <4000 br="br" then="then">var_comm:=400;
else
var_comm:=100;
end if;

update emp set comm=var_comm
where current of c1;

end loop;
end;
/

PL/SQl Queries


1) WRITE A PROGRAM TO PRINT HELLO WORLD
BEGIN
DBMS_OUTPUT.PUT_LINE ('HELLO WORLD');
END;
/

2) WRITE A PROGRAM TO PRINT EVEN NUMBERS FROM 1 TO 100
DECLARE
N NUMBER(3) :=0;
BEGIN
WHILE N<=100
LOOP
N :=N+2;
DBMS_OUTPUT.PUT_LINE(N);
END LOOP;
END;
/

3) WRITE A PROGRAM TO FIND SUM OF NUMBERS FROM 1 TO 100
DECLARE
N NUMBER(3):=1;
S NUMBER(4):=0;
BEGIN
WHILE N<=100
LOOP
S := S+N;
N :=N+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('THE SUM IS '||S);
END;

4) WRITE A PROGRAM TO ACCEPT A NUMBER AND FIND SUM OF THE DIGITS
DECLARE
N NUMBER(5):=&N;
S NUMBER:=0;
R NUMBER(2):=0;
BEGIN
WHILE N !=0
LOOP
R:=MOD(N,10);
S:=S+R;
N:=TRUNC(N/10);

END LOOP;
DBMS_OUTPUT.PUT_LINE('SUM OF DIGITS OF GIVEN NUMBER IS '||S);
END;
/


5) Write a program to accept a number and print it in reverse order
DECLARE
N NUMBER(5):=&N;
REV NUMBER(5):=0;
R NUMBER(5):=0;
BEGIN
WHILE N !=0
LOOP
R:=MOD(N,10);
REV:=REV*10+R;
N:=TRUNC(N/10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('THE REVERSE OF A GIVEN NUMBER IS '||REV);
END;
/

6) Write a program accept the value of A,B&C display which is greater
DECLARE
A NUMBER(4,2):=&A;
B NUMBER(4,2):=&B;
C NUMBER(4,2):=&C;
BEGIN
IF (A>B AND A>C) THEN
DBMS_OUTPUT.PUT_LINE('A IS GREATER '||''||A);
ELSIF B>C THEN
DBMS_OUTPUT.PUT_LINE('B IS GREATE '||''||B);
ELSE
DBMS_OUTPUT.PUT_LINE('C IS GREATER '||''||C);
END IF;
END;
/

7) Write a program accept a string and check whether it is palindrome or not
DECLARE
S VARCHAR2(10):='&S';
L VARCHAR2(20);
TEMP VARCHAR2(10);
BEGIN

FOR I IN REVERSE 1..LENGTH(S)

LOOP
L:=SUBSTR(S,I,1);
TEMP:=TEMP||''||L;
END LOOP;
IF TEMP=S THEN
DBMS_OUTPUT.PUT_LINE(TEMP ||''||' IS PALINDROME');
ELSE
DBMS_OUTPUT.PUT_LINE(TEMP ||''||' IS NOT PALINDROME');
END IF;
END;
/

8) WAP to accept the empno and display all the details of emp. If emp does not exist display the message
DECLARE
EMPNOV NUMBER:=&EMPNO;
EMPV EMP%ROWTYPE;
BEGIN
SELECT * INTO EMPV FROM EMP WHERE EMPNO=EMPNOV;
DBMS_OUTPUT.PUT_LINE('EMPNO '||EMPV.EMPNO);
DBMS_OUTPUT.PUT_LINE('ENAME '||EMPV.ENAME);
DBMS_OUTPUT.PUT_LINE('JOB '||EMPV.JOB);
DBMS_OUTPUT.PUT_LINE('SALARY '||EMPV.SAL);
DBMS_OUTPUT.PUT_LINE('HIREDATE '||EMPV.HIREDATE);
DBMS_OUTPUT.PUT_LINE('DEPTNO '||EMPV.DEPTNO);
DBMS_OUTPUT.PUT_LINE('MGRNO '||EMPV.MGR);
DBMS_OUTPUT.PUT_LINE('COMMISSION '||EMPV.COMM);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('EMP NUMBER DOES NOT EXIST');
END;
/


9) Write a program to accept the grade and display emps belongs to that grade?
DECLARE
GRADEV SALGRADE.GRADE%TYPE:=&GRADE;
CURSOR A IS
SELECT EMP.*,GRADE FROM EMP,SALGRADE WHERE SAL BETWEEN LOSAL AND HISAL AND GRADE=GRADEV;
B A%ROWTYPE;
BEGIN
OPEN A;
LOOP
FETCH A INTO B;
EXIT WHEN A%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('EMP NO IS ' || B.EMPNO);

DBMS_OUTPUT.PUT_LINE('ENAME IS ' || B.ENAME);
DBMS_OUTPUT.PUT_LINE('SAL IS ' || B.SAL);
DBMS_OUTPUT.PUT_LINE('MGR NO IS ' || B.MGR);
DBMS_OUTPUT.PUT_LINE('COMM IS ' || B.COMM);
DBMS_OUTPUT.PUT_LINE('HIREDATE IS ' || B.HIREDATE);
DBMS_OUTPUT.PUT_LINE('GRADE IS ' || B.GRADE);
DBMS_OUTPUT.PUT_LINE('EMP JOB IS ' || B.JOB);
DBMS_OUTPUT.PUT_LINE('*************************');
END LOOP;
CLOSE A;
END;
/


10) Write a program to accept a deptno and display who are working in that dept?
DECLARE
DEPTV EMP.DEPTNO%TYPE:=&DEPTNO;
CURSOR A IS
SELECT * FROM EMP WHERE DEPTNO=DEPTV;
B A%ROWTYPE;
BEGIN
OPEN A;
LOOP
FETCH A INTO B;
EXIT WHEN A%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('EMP NO IS ' || B.EMPNO);
DBMS_OUTPUT.PUT_LINE('ENAME IS ' || B.ENAME);
DBMS_OUTPUT.PUT_LINE('SAL IS ' || B.SAL);
DBMS_OUTPUT.PUT_LINE('MGR NO IS ' || B.MGR);
DBMS_OUTPUT.PUT_LINE('COMM IS ' || B.COMM);
DBMS_OUTPUT.PUT_LINE('HIREDATE IS ' || B.HIREDATE);
DBMS_OUTPUT.PUT_LINE('DEPTNO IS ' || B.DEPTNO);
DBMS_OUTPUT.PUT_LINE('EMP JOB IS ' || B.JOB);
DBMS_OUTPUT.PUT_LINE('*************************');
END LOOP;
CLOSE A;
END;
/

11) Write a program to display all the information of emp table?
DECLARE
CURSOR A IS
SELECT * FROM EMP;
B A%ROWTYPE;
BEGIN
OPEN A;
LOOP

FETCH A INTO B;
EXIT WHEN A%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('EMP NO IS ' || B.EMPNO);
DBMS_OUTPUT.PUT_LINE('ENAME IS ' || B.ENAME);
DBMS_OUTPUT.PUT_LINE('SAL IS ' || B.SAL);
DBMS_OUTPUT.PUT_LINE('MGR NO IS ' || B.MGR);
DBMS_OUTPUT.PUT_LINE('COMM IS ' || B.COMM);
DBMS_OUTPUT.PUT_LINE('HIREDATE IS ' || B.HIREDATE);
DBMS_OUTPUT.PUT_LINE('DEPTNO IS ' || B.DEPTNO);
DBMS_OUTPUT.PUT_LINE('EMP JOB IS ' || B.JOB);
DBMS_OUTPUT.PUT_LINE('*************************');
END LOOP;
CLOSE A;
END;
/

12) Write a program to accept a range of salary (that is lower boundary and higher boundary) and print the details of emps along with loc,grade and exp?
DECLARE
LOSALV SALGRADE.LOSAL%TYPE:=&LOSAL;
HISALV SALGRADE.HISAL%TYPE:=&HISAL;
EXP NUMBER(5,2);
CURSOR A IS
SELECT EMP.*,LOC,GRADE FROM EMP,DEPT,SALGRADE WHERE EMP.DEPTNO=DEPT.DEPTNO
AND SAL BETWEEN LOSALV AND HISALV
AND SAL BETWEEN LOSAL AND HISAL;
B A%ROWTYPE;
BEGIN
OPEN A;
LOOP
FETCH A INTO B;
EXIT WHEN A%NOTFOUND;
EXP:=MONTHS_BETWEEN(SYSDATE,B.HIREDATE)/12;
DBMS_OUTPUT.PUT_LINE('EMP NO IS ' || B.EMPNO);
DBMS_OUTPUT.PUT_LINE('ENAME IS ' || B.ENAME);
DBMS_OUTPUT.PUT_LINE('EMP JOB IS ' || B.JOB);
DBMS_OUTPUT.PUT_LINE('LOC IS ' || B.LOC);
DBMS_OUTPUT.PUT_LINE('EXP IS ' || EXP);
DBMS_OUTPUT.PUT_LINE('GRADE IS ' || B.GRADE);
DBMS_OUTPUT.PUT_LINE('*************************');
END LOOP;
CLOSE A;
END;
/



13) Write a function to accept the empno and return exp with minimum 3 decimal?
CREATE OR REPLACE FUNCTION E_DETAILS(EMPNOV NUMBER) RETURN NUMBER
IS
HIREDATEV EMP.HIREDATE%TYPE;
EXP NUMBER(6,3);
BEGIN
SELECT HIREDATE INTO HIREDATEV FROM EMP WHERE EMPNO=EMPNOV;
EXP:=MONTHS_BETWEEN(SYSDATE,HIREDATEV)/12;
RETURN EXP;
END;
/

14) Write a database trigger halt the transaction on Sunday on EMP table
CREATE OR REPLACE TRIGGER SUN_TRI
AFTER INSERT OR UPDATE OR DELETE ON EMP
DECLARE
DY VARCHAR2(200);
BEGIN
DY:=TO_CHAR(SYSDATE,'DY');
IF DY='SUN' THEN
RAISE_APPLICATION_ERROR(-20005,'TODAY IS SUNDAY TRANSACTION NOT ALLOWED TODAY');
END IF;
END;
/

15) Write a database trigger halt the transaction of USER SCOTT on table EMP
CREATE OR REPLACE TRIGGER SCOTT_TRI
BEFORE INSERT OR UPDATE OR DELETE ON EMP
BEGIN
IF USER = 'SCOTT' THEN
RAISE_APPLICATION_ERROR(-20006,'TRANSACTION NOT ALLOWED FOR SCOTT');
END IF;
END;
/

16) Write a database trigger stroe the username ,type of transaction ,date of transaction and time of transaction of table emp into the table EMP_LOG
CREATE OR REPLACE TRIGGER TRANS_TYPE

AFTER INSERT OR UPDATE OR DELETE ON EMP

DECLARE
V VARCHAR2(50);
BEGIN
IF INSERTING THEN
V:='I';
ELSIF UPDATING THEN
V:='U';
ELSE
V:='D';
END IF;
INSERT INTO EMP_LOG VALUES (USER,V,SYSDATE,TO_CHAR(SYSDATE,'HH:MI:SS'));
END;
/
17) Write a database trigger store the deleted data of EMP table in EMPDEL table
CREATE OR REPLACE TRIGGER DEL_TRI
BEFORE DELETE ON EMP
FOR EACH ROW
BEGIN
INSERT INTO EMPDEL
VALUES (:OLD.EMPNO,:OLD.ENAME,:OLD.JOB,:OLD.MGR,:OLD.HIREDATE,:OLD.SAL,:OLD.COMM,
:OLD.DEPTNO,SYSDATE,TO_CHAR(SYSDATE,'HH:MI:SS));
END;
/

18) Write a database trigger halt the transaction of EMP table if the deptno is does not exist in the dept table
CREATE OR REPLACE TRIGGER DEPT_NO
BEFORE INSERT OR UPDATE OR DELETE ON EMP
FOR EACH ROW
DECLARE
DNO NUMBER:=0;
BEGIN
SELECT COUNT(*) INTO DNO FROM DEPT WHERE DEPTNO=:NEW.DEPTNO;
DBMS_OUTPUT.PUT_LINE(DNO);
IF DNO=0 THEN
RAISE_APPLICATION_ERROR(-20009,'DEPTNO NOT EXIST IN DEPT TABLE....');
END IF;
END;
/

SQL Queries



DROP  TABLE emp
/
DROP  TABLE dept
/
DROP  TABLE bonus
/
DROP  TABLE salgrade
/
DROP  TABLE dummy
/
CREATE  TABLE emp(empno NUMBER(4) NOT NULL,ename VARCHAR2(10),job VARCHAR2(9),mgr NUMBER(4),hiredate DATE,sal NUMBER(7, 2),comm NUMBER(7, 2),deptno NUMBER(2))
/
INSERT INTO emp
     VALUES (7369
            ,'SMITH'
            ,'CLERK'
            ,7902
            ,TO_DATE('17-DEC-1980', 'DD-MON-YYYY')
            ,800
            ,NULL
            ,20)
/
INSERT INTO emp
     VALUES (7499
            ,'ALLEN'
            ,'SALESMAN'
            ,7698
            ,TO_DATE('20-FEB-1981', 'DD-MON-YYYY')
            ,1600
            ,300
            ,30)
/
INSERT INTO emp
     VALUES (7521
            ,'WARD'
            ,'SALESMAN'
            ,7698
            ,TO_DATE('22-FEB-1981', 'DD-MON-YYYY')
            ,1250
            ,500
            ,30)
/
INSERT INTO emp
     VALUES (7566
            ,'JONES'
            ,'MANAGER'
            ,7839
            ,TO_DATE('2-APR-1981', 'DD-MON-YYYY')
            ,2975
            ,NULL
            ,20)
/
INSERT INTO emp
     VALUES (7654
            ,'MARTIN'
            ,'SALESMAN'
            ,7698
            ,TO_DATE('28-SEP-1981', 'DD-MON-YYYY')
            ,1250
            ,1400
            ,30)
/
INSERT INTO emp
     VALUES (7698
            ,'BLAKE'
            ,'MANAGER'
            ,7839
            ,TO_DATE('1-MAY-1981', 'DD-MON-YYYY')
            ,2850
            ,NULL
            ,30)
/
INSERT INTO emp
     VALUES (7782
            ,'CLARK'
            ,'MANAGER'
            ,7839
            ,TO_DATE('9-JUN-1981', 'DD-MON-YYYY')
            ,2450
            ,NULL
            ,10)
/
INSERT INTO emp
     VALUES (7788
            ,'SCOTT'
            ,'ANALYST'
            ,7566
            ,TO_DATE('09-DEC-1982', 'DD-MON-YYYY')
            ,3000
            ,NULL
            ,20)
/
INSERT INTO emp
     VALUES (7839
            ,'KING'
            ,'PRESIDENT'
            ,NULL
            ,TO_DATE('17-NOV-1981', 'DD-MON-YYYY')
            ,5000
            ,NULL
            ,10)
/
INSERT INTO emp
     VALUES (7844
            ,'TURNER'
            ,'SALESMAN'
            ,7698
            ,TO_DATE('8-SEP-1981', 'DD-MON-YYYY')
            ,1500
            ,0
            ,30)
/
INSERT INTO emp
     VALUES (7876
            ,'ADAMS'
            ,'CLERK'
            ,7788
            ,TO_DATE('12-JAN-1983', 'DD-MON-YYYY')
            ,1100
            ,NULL
            ,20)
/
INSERT INTO emp
     VALUES (7900
            ,'JAMES'
            ,'CLERK'
            ,7698
            ,TO_DATE('3-DEC-1981', 'DD-MON-YYYY')
            ,950
            ,NULL
            ,30)
/
INSERT INTO emp
     VALUES (7902
            ,'FORD'
            ,'ANALYST'
            ,7566
            ,TO_DATE('3-DEC-1981', 'DD-MON-YYYY')
            ,3000
            ,NULL
            ,20)
/
INSERT INTO emp
     VALUES (7934
            ,'MILLER'
            ,'CLERK'
            ,7782
            ,TO_DATE('23-JAN-1982', 'DD-MON-YYYY')
            ,1300
            ,NULL
            ,10)
/
CREATE  TABLE dept(deptno NUMBER(2),dname VARCHAR2(14),loc VARCHAR2(13) )
/
INSERT INTO dept
     VALUES (10
            ,'ACCOUNTING'
            ,'NEW YORK')
/
INSERT INTO dept
     VALUES (20
            ,'RESEARCH'
            ,'DALLAS')
/
INSERT INTO dept
     VALUES (30
            ,'SALES'
            ,'CHICAGO')
/
INSERT INTO dept
     VALUES (40
            ,'OPERATIONS'
            ,'BOSTON')
/
CREATE  TABLE bonus(ename VARCHAR2(10),job VARCHAR2(9),sal NUMBER,comm NUMBER)
/
CREATE  TABLE salgrade(grade NUMBER,losal NUMBER,hisal NUMBER)
/
INSERT INTO salgrade
     VALUES (1
            ,700
            ,1200)
/
INSERT INTO salgrade
     VALUES (2
            ,1201
            ,1400)
/
INSERT INTO salgrade
     VALUES (3
            ,1401
            ,2000)
/
INSERT INTO salgrade
     VALUES (4
            ,2001
            ,3000)
/
INSERT INTO salgrade
     VALUES (5
            ,3001
            ,9999)
/

SQL-QUERIES
1.
Display all the information of the EMP table?
A) select * from emp;
2.
Display unique Jobs from EMP table?
A)
select distinct job from emp;
B)
select unique job from emp;
3.
List the emps in the asc order of their Salaries?
A) select * from emp order by sal asc;
4.
List the details of the emps in asc order of the Dptnos and desc of Jobs?
A)select * from emp order by deptno asc,job desc;
5.
Display all the unique job groups in the descending order?
A)select distinct job from emp order by job desc;
6.
Display all the details of all ‘Mgrs’
A)Select * from emp where empno in ( select mgr from emp) ;
7.
List the emps who joined before 1981.
A) select * from emp where hiredate < (’01-jan-81’);
8.
List the Empno, Ename, Sal, Daily sal of all emps in the asc order of Annsal.
A) select empno ,ename ,sal,sal/30,12*sal annsal from emp order by annsal asc;
9.
Display the Empno, Ename, job, Hiredate, Exp of all Mgrs
A) select empno,ename ,job,hiredate, months_between(sysdate,hiredate) exp from emp where empno in (select mgr from emp);
10.
List the Empno, Ename, Sal, Exp of all emps working for Mgr 7369.
A) select empno,ename,sal,exp from emp where mgr = 7369;
11.
Display all the details of the emps whose Comm. Is more than their Sal.
A) select * from emp where comm. > sal;
12.
List the emps in the asc order of Designations of those joined after the second half of 1981.
A) select * from emp where hiredate > (’30-jun-81’) and to_char(hiredate,’YYYY’) = 1981 order by job asc;
13.
List the emps along with their Exp and Daily Sal is more than Rs.100.
A) select * from emp where (sal/30) >100;
14.
List the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order.
A) select * from emp where job = ‘CLERK’ or job = ‘ANALYST’ order by job desc;
15.
List the emps who joined on 1-MAY-81,3-DEC-81,17-DEC-81,19-JAN-80 in asc order of seniority.
A) select * from emp where hiredate in (’01-may-81’,’03-dec-81’,’17-dec-81’,’19-jan-80’) order by hiredate asc;
16.
List the emp who are working for the Deptno 10 or20.
A) select * from emp where deptno = 10 or deptno = 20 ;
17.
List the emps who are joined in the year 81.
A) select * from emp where hiredate between ’01-jan-81’ and ’31-dec-81’;
18.
List the emps who are joined in the month of Aug 1980.
A)
select * from emp where hiredate between ’01-aug-80’ and ’31-aug-80’; (OR)
select * from emp where to_char(hiredate,’mon-yyyy’) =’aug-1980;
19.
List the emps Who Annual sal ranging from 22000 and 45000.
A) select * from emp where 12*sal between 22000 and 45000;
20.
List the Enames those are having five characters in their Names.
A) select ename from emp where length (ename) = 5;
21.
List the Enames those are starting with ‘S’ and with five characters.
A) select ename from emp where ename like ‘S%’ and length (ename) = 5;
22.
List the emps those are having four chars and third character must be ‘r’.
A) select * from emp where length(ename) = 4 and ename like ‘__R%’;
23.
List the Five character names starting with ‘S’ and ending with ‘H’.
A) select * from emp where length(ename) = 5 and ename like ‘S%H’;
24.
List the emps who joined in January.
A) select * from emp where to_char (hiredate,’mon’) = ‘jan’;
25.
List the emps who joined in the month of which second character is ‘a’.
A)
select * from emp where to_char(hiredate,’mon’) like ‘_a_’; (OR)
B) select * from emp where to_char(hiredate,’mon’) like ‘_a%’;
26.
List the emps whose Sal is four digit number ending with Zero.
A) select * from emp where length (sal) = 4 and sal like ‘%0’;
27.
List the emps whose names having a character set ‘ll’ together.
A) select * from emp where ename like ‘%LL%’;
28.
List the emps those who joined in 80’s.
A) select * from emp where to_char(hiredate,’yy’) like ‘8%’;
29.
List the emps who does not belong to Deptno 20.
A) select * from emp where deptno not in (20); (OR)
B) select * from emp where deptno != 20; (OR)
C) select * from emp where deptno <>20; (OR)
D) select * from emp where deptno not like ‘20’;
30.
List all the emps except ‘PRESIDENT’ & ‘MGR” in asc order of Salaries.
A)
Select * from emp where job not in (‘PRESIDENT’,’MANAGER’) order by sal asc;
B)
select * from emp where job not like ‘PRESIDENT’ and job not like ‘MANAGER’ order by sal asc;
C) Select * from emp where job != ‘PRESIDENT’ and job <> ‘MANAGER’ order by sal asc;
31.
List all the emps who joined before or after 1981.
A)
select * from emp where to_char (hiredate,’YYYY’) not in (‘1981’); (OR)
B)
select * from emp where to_char ( hiredate,’YYYY’) != ‘1981’; (OR)
C)
select * from emp where to_char(hiredate,’YYYY’) <> ‘1981’ ; (OR)
D) select * from emp where to_char (hiredate ,’YYYY’) not like ‘1981’;
32.
List the emps whose Empno not starting with digit78.
A) select * from emp where empno not like ‘78%’;
33.
List the emps who are working under ‘MGR’.
A) select e.ename || ‘ works for ‘ || m.ename from emp e ,emp m where e.mgr = m.empno ; (OR)
B) select e.ename || ‘ has an employee ‘|| m.ename from emp e , emp m where e.empno = m.mgr;
34.
List the emps who joined in any year but not belongs to the month of March.
A)
select * from emp where to_char (hiredate,’MON’) not in (‘MAR’); (OR)
B)
select * from emp where to_char (hiredate,’MON’) != ‘MAR’; (OR)
C)
select * from emp where to_char(hiredate,’MONTH’) not like ‘MAR%’ ; (OR)
D)
select * from emp where to_char(hiredate,’MON’) <> ‘MAR’;
35.
List all the Clerks of Deptno 20.
A)select * from emp where job =‘CLERK’ and deptno = 20;
36.
List the emps of Deptno 30 or 10 joined in the year 1981.
A) select * from emp where to_char(hiredate,’YYYY’) = ‘1981’ and (deptno =30 or deptno =10) ; (OR) select * from emp where to_char (hiredate,’YYYY’) in (‘1981’) and (deptno = 30 or deptno =10 ) ;
37.
Display the details of SMITH.
A) select * from emp where ename = ‘SMITH’ ;
38.
Display the location of SMITH.
A) select loc from emp e , dept d where e.ename = ‘SMITH’ and e.deptno = d.deptno ;
39.
List the total information of EMP table along with DNAME and Loc of all the emps Working Under ‘ACCOUNTING’ & ‘RESEARCH’ in the asc Deptno.
A)
select * from emp e ,dept d where (dname = ‘ACCOUNTING’ or dname =’RESEARCH’ ) and e.deptno = d.deptno order by e.deptno asc; (OR)
B)
select * from emp e ,dept d where d.dname in (‘ACCOUNTING’,’RESEARCH’) and e.deptno = d.deptno order by e.deptno asc;
40.
List the Empno, Ename, Sal, Dname of all the ‘MGRS’ and ‘ANALYST’ working in New York, Dallas with an exp more than 7 years without receiving the Comm asc order of Loc.
A)
select e.empno,e.ename,e.sal,d.dname from emp e ,dept d where d.loc in (‘NEW YORK’,’DALLAS’) and e.deptno = d.deptno and e.empno in (select e.empno from emp e where e.job in (‘MANAGER’,’ANALYST’) and (months_between(sysdate,e.hiredate)/12)> 7 and e.comm. is null)
order by d.loc asc;
41.
Display the Empno, Ename, Sal, Dname, Loc, Deptno, Job of all emps working at CJICAGO or working for ACCOUNTING dept with Ann Sal>28000, but the Sal should not be=3000 or 2800 who doesn’t belongs to the Mgr and whose no is having a digit ‘7’ or ‘8’ in 3rd position in the asc order of Deptno and desc order of job.
A) select E.empno,E.ename,E.sal,D.dname,D.loc,E.deptno,E.job
from emp E,dept D
where (D.loc = 'CHICAGO' or D.dname = 'ACCOUNTING') and E.deptno=D.deptno and E.empno in
(select E.empno from emp E where (12*E.sal) > 28000 and E.sal not in (3000,2800) and E.job !='MANAGER'
and ( E.empno like '__7%' or E.empno like '__8%'))
order by E.deptno asc , E.job desc;
42.
Display the total information of the emps along with Grades in the asc order.
A) select * from emp e ,salgrade s where e.sal between s.losal and s.hisal order by grade asc; (OR)
B) select * from emp e ,salgrade s where e.sal >= s.losal and e.sal <= s.hisal order by s.grade asc; (using between and is a bit simple)
43.
List all the Grade2 and Grade 3 emps.
A)
select * from emp e where e.empno in (select e.empno from emp e ,salgrade s where e.sal between s.losal and s.hisal and s.grade in(2,3)); (OR)
B) select * from emp e ,salgrade s where e.sal between s.losal and s.hisal and
s.grade in (2,3) ;
44.
Display all Grade 4,5 Analyst and Mgr.
A) select * from emp e, salgrade s where e.sal between s.losal and s.hisal and s.grade in (4,5) and e.empno in (select e.empno from emp e where e.job in (‘MANAGER’,’ANALYST’) );
45.
List the Empno, Ename, Sal, Dname, Grade, Exp, and Ann Sal of emps working for Dept10 or20.
A)
selectE.empno,E.ename,E.sal,S.grade,D.dname,(months_between(sysdate,E.hiredate)/12) "EXP" ,12*E.sal “ANN SAL”
from emp E,dept D ,salgrade S
where E.deptno in (10,20) and E.deptno = D.deptno and E.sal between S.losal and S.hisal ;
46.
List all the information of emp with Loc and the Grade of all the emps belong to the Grade range from 2 to 4 working at the Dept those are not starting with char set ‘OP’ and not ending with ‘S’ with the designation having a char ‘a’ any where joined in the year 1981 but not in the month of Mar or Sep and Sal not end with ‘00’ in the asc order of Grades
A) select e.empno,e.ename,d.loc,s.grade,e.sal from emp e ,dept d,salgrade s where e.deptno = d.deptno
and (d.dname not like 'OP%' and d.dname not like '%S') and e.sal between s.losal and s.hisal and s.grade in (2,3,4)
and empno in (select empno from emp where job like '%A%'and sal not like '%00' and (to_char (hiredate,'YYYY') = '1981'
and to_char(hiredate,'MON') not in ('MAR','SEP')));
47.
List the details of the Depts along with Empno, Ename or without the emps
A) select * from emp e,dept d where e.deptno(+)= d.deptno;
48.
List the details of the emps whose Salaries more than the employee BLAKE.
A) select * from emp where sal > (select sal from emp where ename = ‘BLAKE’);
49.
List the emps whose Jobs are same as ALLEN.
A) select * from emp where job = (select job from emp where ename = ‘ALLEN’);
50.
List the emps who are senior to King.
A)
select * from emp where hiredate < ( select hiredate from emp where ename = ‘KING’);
51.
List the Emps who are senior to their own MGRS.
A)
select * from emp w,emp m where w.mgr = m.empno and w.hiredate < m.hiredate ; (OR)
B)
select * from emp w,emp m where w.empno= m.mgr and
w.hiredate> m.hiredate;
52.
List the Emps of Deptno 20 whose Jobs are same as Deptno10.
A) select * from emp e ,dept d where d.deptno = 20 and e.deptno = d.deptno and e.job in ( select e.job from emp e,dept d where e.deptno = d.deptno and d.deptno =10);
53.
List the Emps whose Sal is same as FORD or SMITH in desc order of Sal.
A)
Select * from emp where sal in (select sal from emp where ( ename = ‘SMITH’ or ename = ‘FORD’ )) order by sal desc;
54.
List the emps Whose Jobs are same as MILLER or Sal is more than ALLEN.
A) select * from emp where job = (select job from emp where ename = ‘MILLER’ ) or sal>(select sal from emp where ename = ‘ALLEN’);
55.
List the Emps whose Sal is > the total remuneration of the SALESMAN.
A) select * from emp where sal >(select sum(nvl2(comm,sal+comm,sal)) from emp where job = ‘SALESMAN’);
56.
List the emps who are senior to BLAKE working at CHICAGO & BOSTON.
A)
select * from emp e ,dept d where d.loc in (‘CHICAGO’,’BOSTON’) and e.deptno = d.deptno and e.hiredate <(select e.hiredate from emp e where e.ename = ‘BLAKE’) ;
57.
List the Emps of Grade 3,4 belongs to the dept ACCOUNTING and RESEARCH whose Sal is more than ALLEN and exp more than SMITH in the asc order of EXP.
A)
select * from emp e where e.deptno in (select d.deptno from dept d where d.dname in (‘ACCOUNTING’,’RESEARCH’) ) and
e.sal >(select sal from emp where ename = ‘ALLEN’) and
e.hiredate <( select hiredate from emp where ename = ‘SMITH’) and
e.empno in (select e.empno from emp e ,salgrade s where e.sal between s.losal and s.hisal and s.grade in (3,4) )
order by e.hiredate desc;
58.
List the emps whose jobs same as SMITH or ALLEN.
A)
select * from emp where job in (select job from emp where ename = ‘SMITH’ or ename = ‘ALLEN’); (OR)
B) select * from emp where job in (select job from emp where ename in (‘SMITH’,’ALLEN’);
59.
Write a Query to display the details of emps whose Sal is same as of
a)
Employee Sal of EMP1 table.
b)
¾ Sal of any Mgr of EMP2 table.
c)
The sal of any person with exp of 5 years belongs to the sales dept of emp3 table.
d)
Any grade 2 employee of emp4 table.
e)
Any grade 2 and 3 employee working fro sales dept or operations dept joined in 89.
60.
Any jobs of deptno 10 those that are not found in deptno 20.
A) select e.job from emp e where e.deptno = 10 and e.job not in (select job from emp where deptno =20);
61.
List of emps of emp1 who are not found in emp2.
62.
Find the highest sal of EMP table.
A) select max(sal) from emp;
63.
Find details of highest paid employee.
A)
select * from emp where sal in (select max(sal) from emp);
64.
Find the highest paid employee of sales department.
A) select * from emp where sal in (select max(sal) from emp where deptno in (select d.deptno from
dept d where d.dname = 'SALES'));
65.
List the most recently hired emp of grade3 belongs to location CHICAGO.
A) select * from emp e where e.deptno in ( select d.deptno from dept d where d.loc = 'CHICAGO') and
e.hiredate in (select max(hiredate) from emp where empno in (select empno from emp e,salgrade s
where e.sal between s.losal and s.hisal and s.grade = 3)) ; (or)
select * from emp e,dept d where d.loc='chicago'
and hiredate in(select max(hiredate) from emp e,salgrade s
where sal between losal and hisal and grade=3);
66.
List the employees who are senior to most recently hired employee working under king.
A) select * from emp where hiredate < (select max(hiredate) from emp where mgr in
(select empno from emp where ename = 'KING')) ;
67.
List the details of the employee belongs to newyork with grade 3 to 5 except ‘PRESIDENT’ whose sal> the highest paid employee of Chicago in a group where there is manager and salesman not working under king
A) select * from emp where deptno in (select deptno from dept where dept.loc ='NEW YORK')
and empno in (select empno from emp e,salgrade s where e.sal between s.losal and s.hisal and
s.grade in (3,4,5) ) and job != 'PRESIDENT' and sal >(select max(sal) from emp where deptno in
(select deptno from dept where dept.loc = 'CHICAGO') and job in ('MANAGER','SALESMAN') and
mgr not in (select empno from emp where ename = 'KING'));
68.
List the details of the senior employee belongs to 1981.
A)
select * from emp where hiredate in (select min(hiredate) from emp where to_char( hiredate,’YYYY’) = ‘1981’); (OR)
B)
select * from emp where hiredate = (select min(hiredate) from emp where to_char(hiredate,’YYYY’) = ‘1981’);
69.
List the employees who joined in 1981 with the job same as the most senior person of the year 1981.
A)select * from emp where job in (select job from emp where hiredate in
(select min(hiredate) from emp where to_char(hiredate,’YYYY’) =’1981’));
70.
List the most senior empl working under the king and grade is more than 3.
A) select * from emp where hiredate in (select min(hiredate) from emp where empno in
(select empno from emp e ,salgrade s where e.sal between s.losal and s.hisal and s.grade in (4,5)))
and mgr in (select empno from emp where ename = 'KING');
71.
Find the total sal given to the MGR.
A)
select sum (sal) from emp where job = ‘MANAGER’; (OR)
B) select sum(sal) from emp where empno in(select mgr from emp);
72.
Find the total annual sal to distribute job wise in the year 81.
A) select job,sum(12*sal) from emp where to_char(hiredate,'YYYY') = '1981'
group by job ;
73.
Display total sal employee belonging to grade 3.
A)
select sum(sal) from emp where empno
in (select empno from emp e ,salgrade s
where e.sal between s.losal and s.hisal and s.grade = 3)
74.
Display the average salaries of all the clerks.
A) select avg(sal) from emp where job = ‘CLERK’;
75.
List the employeein dept 20 whose sal is >the average sal 0f dept 10 emps.
A) select * from emp where deptno =20 and sal >(select avg (sal) from emp where deptno = 10);
76.
Display the number of employee for each job group deptno wise.
A)
select deptno ,job ,count(*) from emp group by deptno,job; (or)
B) select d.deptno,e.job,count(e.job) from emp e,dept d where e.deptno(+)=d.deptno group by e.job,d.deptno;
77.
List the manage rno and the number of employees working for those mgrs in the ascending Mgrno.
A)
select w.mgr ,count(*) from emp w,emp m
where w.mgr = m.empno
group by w.mgr
order by w.mgr asc;
78.
List the department,details where at least two emps are working
A)
select deptno ,count(*) from emp group by deptno
having count(*) >= 2;
79.
Display the Grade, Number of emps, and max sal of each grade.
A) select s.grade ,count(*),max(sal) from emp e,salgrade s where e.sal between s.losal and s.hisal
group by s.grade;
80.
Display dname, grade, No. of emps where at least two emps are clerks.
A) select d.dname,s.grade,count(*) from emp e,dept d,salgrade s where e.deptno = d.deptno and
e.job = 'CLERK' and e.sal between s.losal and s.hisal group by d.dname,s.grade having count(*) >= 2;
81.
List the details of the department where maximum number of emps are working.
A)
select * from dept where deptno in
(select deptno from emp group by deptno
having count(*) in
(select max(count(*)) from emp group by deptno) ); (OR)
B)
select d.deptno,d.dname,d.loc,count(*) from emp e ,dept d
where e.deptno = d.deptno group by d.deptno,d.dname,d..loc
having count(*) = (select max(count(*) ) from emp group by deptno);
82.
Display the emps whose manager name is jones.
A)
select * from emp where mgr in
(select empno from emp where ename = ‘JONES’); (OR)
B)
select * from emp where mgr =
(select empno from emp where ename = ‘JONES’);
83.
List the employees whose salary is more than 3000 after giving 20% increment.
A)
SELECT * FROM EMP WHERE (1.2*SAL) > 3000 ;
84.
List the emps with dept names.
A) select e.empno,e.ename,e.job,e.mgr,e.hiredate,e.sal,e.comm,e.deptno,d.dname
from emp e ,dept d where e.deptno = d.deptno;
85.
List the emps who are not working in sales dept.
A)
select * from emp where deptno not in
(select deptno from emp where dname = ‘SALES’);
86.
List the emps name ,dept, sal and comm. For those whose salary is between 2000 and 5000 while loc is Chicago.
A) select e.ename,e.deptno,e.sal,e.comm from emp e ,dept d where e.deptno = d.deptno and
d.loc = 'CHICAGO' and e.sal between 2000 and 5000;
87.
List the emps whose sal is greater than his managers salary
A) select * from emp w,emp m where w.mgr = m.empno and w.sal > m.sal;
88.
List the grade, EMP name for the deptno 10 or deptno 30 but sal grade is not 4 while they joined the company before ’31-dec-82’.
A) select s.grade ,e.ename from emp e,salgrade s where e.deptno in (10,20) and
hiredate < ('31-DEC-82') and (e.sal between s.losal and s.hisal and s.grade not in (4));
89.
List the name ,job, dname, location for those who are working as MGRS.
A)
select e.ename,e.job,d.dname,d.loc from emp e ,dept d
where e.deptno = d.deptno and
e.empno in (select mgr from emp ) ;
90.
List the emps whose mgr name is jones and also list their manager name.
A) select w.empno,w.ename,w.job,w.mgr,w.hiredate,w.sal,w.deptno,m.ename from emp w ,emp m
where w.mgr = m.empno and m.ename = 'JONES';
91.
List the name and salary of ford if his salary is equal to hisal of his grade.
A) select e.ename,e.sal from emp e ,salgrade s where e.ename = 'FORD' and e.sal between s.losal and s.hisal and e.sal = s.hisal ;
92.
Lit the name, job, dname ,sal, grade dept wise
A)
select e.ename,e.job,d.dname,e.sal,s.grade from emp e,dept d,salgrade s
where e.deptno = d.deptno and e.sal between s.losal and s.hisal
order by e.deptno ;
93.
List the emp name, job, sal, grade and dname except clerks and sort on the basis of highest sal.
A)
select e.ename,e.job,e.sal,s.grade,d.dname from emp e ,dept d ,salgrade s where e.deptno = d.deptno and e.sal between s.losal and s.hisal and
e.job not in('CLERK')
order by e.sal desc;
94.
List the emps name, job who are with out manager.
A) select e.ename,e.job from emp e where mgr is null;
95.
List the names of the emps who are getting the highest sal dept wise.
A)
select e.ename,e.deptno from emp e where e.sal in
(select max(sal) from emp group by deptno) ;
96.
List the emps whose sal is equal to the average of max and minimum
A) select * from emp where sal =(select (max(sal)+min(sal))/2 from emp);
97.
List the no. of emps in each department where the no. is more than 3.
A) select deptno,count(*) from emp group by deptno having count(*) < 3;
98.
List the names of depts. Where atleast 3 are working in that department.
A)
select d.dname,count(*) from emp e ,dept d where e.deptno = d.deptno
group by d.dname
having count(*) >= 3 ;
99.
List the managers whose sal is more than his employess avg salary.
A)
select * from emp m where m.empno in (select mgr from emp)
and m.sal > (select avg(e.sal) from emp e wheree.mgr = m.empno )
The subquery does the same as (
100.
List the name,salary,comm. For those employees whose net pay is greater than or equal to any other employee salary of the company.
A)
select e.ename,e.sal,e.comm from emp e where nvl2(e.comm.,e.sal+e.comm.,e.sal) >= any (select sal from emp); (OR)
B)
select ename,sal,comm. from emp where sal+nvl(comm.,0) >= any (select sal from emp);/
101.
List the emp whose sala) select distinct W.empno,W.ename,W.sal
from (select w.empno,w.ename,w.sal from emp w,emp m where
w.mgr = m.empno and w.sal(select * from emp where empno in (select mgr from emp)) A
where W.sal > A.sal; (OR)
B) select * from emp w,emp m where w.mgr = m.empno and w.sal < m.sal
and w.sal > any (select sal from emp where empno in (select mgr from emp));
102.
List the employee names and his average salary department wise.
A)
select d.deptno, round(avg(nvl2(e1.comm, e1.sal+e1.comm, e1.sal))) avg, e2.ename from emp e1, emp e2, dept d where d.deptno =e1.deptno and d.deptno = e2.deptno group by d.deptno, e2.ename; (or)
B) select d.maxsal,e.ename,e.deptno as "current sal" from emp e,
(select avg(Sal) maxsal,deptno from emp group by deptno) d
where e.deptno=d.deptno;
103. Find out least 5 earners of the company.
A) s
elect * from emp e where 5> (select count(*) from emp where e.sal >sal); (or)
B)
select rownum rank,empno,ename,job,sal from (select * from emp order by sal asc) where rownum < 6 ; (or)
C)
select * from emp e where 5 >(select count(distinct sal) from emp where e.sal > sal);
104. Find out emps whose salaries greater than salaries of their managers.
A) s
elect * from emp w,emp m where w.mgr = m.empno and w.sal> m.sal; (OR)
B)
select * from emp e ,(select * from emp where empno in (select mgr from emp)) a
where e.sal >a.sal and e.mgr = a.empno
105. List the managers who are not working under the president.
A) select * from emp where empno in(select mgr from emp) and mgr not in
(select empno from emp where job = 'PRESIDENT')
106. List the records from emp whose deptno isnot in dept.
107. List the Name , Salary, Comm and Net Pay is more than any other employee.
A) Select e.ename,e.sal,e.comm,nvl2(comm,sal+comm,sal) NETPAY
from emp e
where nvl2(comm,sal+comm,sal) > any (select sal from emp where empno =e.empno) ;
108. List the Enames who are retiring after 31-Dec-89 the max Job period is 20Y.
A) s
elect ename from emp where add_months(hiredate,240) > '31-DEC-89';
B) select ename from emp
where add_months(hiredate,240) > to_date(’31-DEC-89’,’DD-MON-RR’);
109. List those Emps whose Salary is odd value.
A) s
elect * from emp where mod(sal,2) = 1;
110. List the emp’s whose Salary contain 3 digits.
A) s
elect * from emp where length (sal) = 3;
111. List the emps who joined in the month of DEC.
A) s
elect * from emp where to_char(hiredate,’MON’) =’DEC’; (OR)
B)
select * from emp where to_char(hiredate,’MON’) in (‘DEC’); (OR)
C)
select * from emp where to_char(hiredate,’MONTH’) like ‘DEC%’;
11
2. List the emps whose names contains ‘A’.
A) select * from emp where ename like ‘%A%’;
113. List the emps whose Deptno is available in his Salary.
A) select * from emp where instr(sal,deptno) > 0;
114. List the emps whose first 2 chars from Hiredate=last 2 characters of Salary.
A) select * from emp
where substr(hiredate,1,2) = substr(sal,length(sal)-1,length(sal));
115. List the emps Whose 10% of Salary is equal to year of joining.
A) select * from emp where to_char(hiredate,'YY') in (select .1*sal from emp);
116. List first 50% of chars of Ename in Lower Case and remaining are upper Case.
A)
select lower(substr(ename,1,round(length(ename)/2)))
||substr(ename,round(length(ename)/2)+1,length(ename)) from emp ; (OR)
B) select lower(substr(ename,1,ciel(length(ename)/2)))
|| substr(ename,ciel(length(ename)/2)+1,length(ename)) from emp ;
117. List the Dname whose No. of Emps is =to number of chars in the Dname.
A) s
elect * from dept d where length(dname) in (select count(*) from emp e where e.deptno = d.deptno ); (or)
B)
select d.dname,count(*) from emp e ,dept d where e.deptno = d.deptno group by d.dname having count(*) = length (d.dname);
118. List the emps those who joined in company before 15th of the month.
A) s
elect * from emp where to_char(hiredate,'DD') < '15';
119. List the Dname, no of chars of which is = no. of emp’s in any other Dept.
A) s
elect * from dept d where length(dname) in (select count(*) from emp where d.deptno <> deptno group by deptno ); (or)
B)
select * from dept where length(dname) = any (select count(*) from emp where d.deptno <> deptno group by deptno);
C)
select * from dept d , (select count(*) s,e.deptno "M"from emp e group by e.deptno) d1
where length(dname)=d1.s and d1.M <>d.deptno;
120. List the emps who are working as Managers.
A) s
elect * from where job = ‘MANAGER’; (or)
B)
select * from emp where empno in (select mgr from emp );
121. List THE Name of dept where highest no.of emps are working.
A) select dname from dept where deptno in
(select deptno from emp group by deptno
having count(*) in
(select max(count(*)) from emp group by deptno) );
122. Count the No.of emps who are working as ‘Managers’(using set option).
A)se
lect count(*)
from(select * from emp minus select * from emp where job != 'MANAGER')
123. List the emps who joined in the company on the same date.
A) s
elect * from emp e where hiredate in
(select hiredate from emp where e.empno <> empno);
124. List the details of the emps whose Grade is equal to one tenth of Sales Dept.
A) select * from emp e,salgrade s
where e.sal between s.losal and s.hisal and
s.grade = 0.1* (select deptno from dept where dname = 'SALES');
125. List the name of the dept where more than average no. of emps are working.
A) select d.dname from dept d, emp e where e.deptno = d.deptno
group by d.dname
having count(*) > (select avg(count(*)) from emp group by deptno);
126. List the Managers name who is having max no.of emps working under him.
A
)select m.ename,count(*) from emp w,emp m
where w.mgr = m.empno
group by m.ename
having count(*) = (select max(count(*)) from emp group by mgr);
(OR)
B) select * from emp where empno = (select mgr from emp group by mgr having count(*) = (select max(count(*)) from emp group by mgr)) ;
127. List the Ename and Sal is increased by 15% and expressed as no.of Dollars.
A) select ename,to_char(1.15*sal,'$99,999') as "SAL" from emp; (only for $ it works)
B) select ename,'$'||1.15*sal “SAL” from emp;
128. Produce the output of EMP table ‘EMP_AND_JOB’ for Ename and Job.
A) select ename|| job as "EMP_AND_JOB" from emp ;
129. Produce the following output from EMP.
EMP
LOYEE
SMITH (clerk)
ALLEN (Salesman)
A) select ename || ‘(‘|| lower(job)||’)’ as “EMPLOYEE” from emp;
130) List the emps with Hire date in format June 4, 1988.
A) s
elect empno,ename,sal, to_char(hiredate,'MONTH DD,YYYY') from emp;
13
1) Print a list of emp’s Listing ‘just salary’ if Salary is more than 1500, on target if Salary is 1500 and ‘Below 1500’ if Salary is less than 1500.
A) s
elect empno,ename,sal|| ‘JUST SALARY’ "SAL" from emp where sal > 1500 union
select empno,ename, sal|| ‘ON TARGET’ "SAL" from emp where sal = 1500
union
select empno,ename, sal|| ‘BELOW 1500’ "SAL" from emp where sal < 1500; (OR)
B)select empno,ename,sal,job,
case
when sal = 1500 then 'ON TARGET'
when sal < 1500 then 'BELOW 1500'
when sal > 1500 then 'JUST SALARY'
else 'nothing'
end "REVISED SALARY"
from emp;
132) Write a query which return the day of the week for any date entered in format ‘DD-MM-YY’.
A) s
elect to_char(to_date('& s','dd-mm-yy'),'day') from dual ;
133) Write a query to calculate the length of service of any employee with the company, use DEFINE to avoid repetitive typing of functions.
A) D
EFINE service = ((months_between(sysdate,hiredate))/12)
B)
Select empno,ename,&service from emp where ename = ‘& name’;
134) Give a string of format ‘NN/NN’, verify that the first and last two characters are numbers and that the middle character is’/’. Print the expression ‘YES’ if valid, ‘NO’ if not valid. Use the following values to test your solution. ‘12/34’,’01/1a’, ‘99/98’.
A)
135) Emps hired on or before 15th of any month are paid on the last Friday of that month those hired after 15th are paid on the first Friday of the following month. Print a list of emps their hire date and the first pay date. Sort on hire date.
A) s
elect ename,hiredate,next_day(last_day(hiredate),'FRIDAY')-7 from emp where to_char(hiredate,'DD') <=15
union
select ename,hiredate,next_day(last_day(hiredate),'FRIDAY') from emp where to_char(hiredate,'DD') > 15;
136) Count the no. of characters with out considering spaces for each name.
A) s
elect length(replace(ename,’ ‘,null)) from emp;
13
7) Find out the emps who are getting decimal value in their Sal without using like operator.
A) s
elect * from emp where instr(sal,’.’,1,1) > 0;
138) List those emps whose Salary contains first four digit of their Deptno.
A) s
elect * from emp where instr(to_char(sal,,9999),deptno,1,1)>0 and instr(to_char(sal,9999),deptno,1,2)> 0 ;
13
9) List those Managers who are getting less than his emps Salary.
A) s
elect distinct m.ename,m.sal from emp w,emp m where w.mgr = m.empno and w.sal>m.sal;
B)
select * from emp w where sal < any ( select sal from emp where w.empno=mgr);
C)
select * from emp w where empno in ( select mgr from emp where
w.sal140) Print the details of all the emps who are sub-ordinates to Blake.
A) s
elect * from emp where mgr in (select empno from emp where ename = 'BLAKE');
14
1) List the emps who are working as Managers using co-related sub-query.
A) s
elect * from emp where empno in (select mgr from emp);
142) List the emps whose Mgr name is ‘Jones’ and also with his Manager name.
A) s
elect w.ename,m.ename,(select ename from emp where m.mgr = empno) "his MANAGER"
from emp w,emp m where w.mgr = m.empno and m.ename = 'JONES'; (or)
B) select e.ename,w.ename,m.ename from emp e,emp w,emp m where e.mgr = w.empno and w.ename = ‘JONES’ and w.mgr = m.empno;
143) Define a variable representing the expression used to calculate on emps total annual remuneration use the variable in a statement, which finds all emps who can earn 30000 a year or more.
A) Set define on
B)
Define annual = 12*nvl2(comm.,sal+comm.,sal) (here define variable is a session variable)
C)
Select * from emp where &annual > 30000;
144) Find out how may Managers are their in the company.
A) s
elect count(*) from emp where job = ‘MANAGER’; (or)
B)
select count(*) from emp where empno in (select mgr from emp); (or)
C)
select count(distinct m.empno) from emp w,emp m where w.mgr = m.empno ;
14
5) Find Average salary and Average total remuneration for each Job type. Remember Salesman earn commission.secommm
A) s
elect avg(sal),avg(sal+nvl(comm,0)) from emp;
146) Check whether all the emps numbers are indeed unique.
A) s
elect empno,count(*) from emp group by empno;
147) List the emps who are drawing less than 1000 Sort the output by Salary.
A)select * from emp where sal < 1000 order by sal;
148) List the employee Name, Job, Annual Salary, deptno, Dept name and grade who earn 36000 a year or who are not CLERKS.
A)se
lecte.ename,e.job,(12*e.sal)"ANNUALSALARY", e.deptno,d.dname,s.grade
from emp e,dept d ,salgrade s where e.deptno = d.deptno and e.sal between s.losal and s.hisal
and (((12*e.sal)>= 36000) or (e.job != 'CLERK'))
149) Find out the Job that was filled in the first half of 1983 and same job that was filled during the same period of 1984.
A) s
elect * from emp where (to_char(hiredate,'MM ') <= 06 and to_char(hiredate,'YYYY') = 1984) and job in (select job from emp where to_char(hiredate,'MM' ) <= 06 and to_char(hiredate,'YYYY') <= 1983) ;
150) Find out the emps who joined in the company before their Managers.
A) s
elect * from emp w,emp m where w.mgr = m.empno and
w.hiredate< m.hiredate;(or)
B) select * from emp e where hiredate < (select hiredate from emp where empno = e.mgr)
151) List all the emps by name and number along with their Manager’s name and number. Also List KING who has no ‘Manager’.
A) s
elect w.empno,w.ename,m.empno,m.ename from emp w,emp m where w.mgr= m.empno(+);
152) Find all the emps who earn the minimum Salary for each job wise in ascending order.
A) s
elect * from emp where sal in
(select min(sal) from emp group by job)
order by sal asc;
153) Find out all the emps who earn highest salary in each job type. Sort in descending salary order.
A) s
elect * from emp where sal in
(select max(sal) from emp group by job)
order by sal desc;
154) Find out the most recently hired emps in each Dept order by Hiredate.
A) s
elect * from emp e where hiredate in
(select max(hiredate) from emp where e.deptno = deptno )
order by hiredate;
155) List the employee name,Salary and Deptno for each employee who earns a salary greater than the average for their department order by Deptno.
A) s
elect * from emp e
where sal > (select avg(sal) from emp where e.deptno = deptno );
B) select e.ename,e.sal,e.deptno from emp e,(select avg(sal) A,deptno D from
emp group by deptno) D1 where D1.D = e.deptno and e.sal > D1.A;
156) List the Deptno where there are no emps.
A) s
elect deptno ,count(*) from emp
group by deptno
having count(*) = 0;
157) List the No.of emp’s and Avg salary within each department for each job.
A) s
elect count(*),avg(sal),deptno,job from emp
group by deptno,job;
158) Find the maximum average salary drawn for each job except for ‘President’.
A) s
elect max(avg(sal)) from emp where job != 'PRESIDENT' group by job;
159) Find the name and Job of the emps who earn Max salary and Commission.
A) s
elect * from emp where sal = (select max(sal) from emp) and comm. is not null;
160) List the Name, Job and Salary of the emps who are not belonging to the department 10 but who have the same job and Salary as the emps of dept 10.
A) s
elect ename,job,sal from emp where deptno != 10 and job in (select job from emp where deptno = 10)
and sal in (select sal from emp where deptno = 10);
161) List the Deptno, Name, Job, Salary and Sal+Comm of the SALESMAN who are earning maximum salary and commission in descending order.
A)se
lect deptno,name,job,sal,sal+nvl(comm.,0) from emp where job = ‘SALESMAN’ and sal in (select max(sal+nvl(comm.,0)) from emp where comm. is not null)
Order by (sal +nvl(comm.,0)) desc;
162) List the Deptno, Name, Job, Salary and Sal+Comm of the emps who earn the second highest earnings (sal + comm.).
A) s
elect deptno,ename,sal,job,sal+nvl(comm,0) from emp e where 2 = (select count(distinct sal+nvl(comm,0)) from emp where (e.sal+nvl(comm.,0))<(sal+nvl(comm.,0));
163) List the Deptno and their average salaries for dept with the average salary less than the averages for all department
A) select deptno,avg(sal) from emp group by deptno
ha
ving avg(sal) <(select avg(Sal) from emp);
164) List out the Names and Salaries of the emps along with their manager names and salaries for those emps who earn more salary than their Manager.
A) s
elect w.ename,w.sal,m.ename,m.sal from emp w,emp m
where w.mgr = m.empno and w.sal > m.sal;
165) List out the Name, Job, Salary of the emps in the department with the highest average salary.
A) s
elect * from emp where deptno in
(select deptno from emp e
having avg(sal) =(select max(avg(sal)) from emp group by deptno)
group by deptno);
166) List the empno,sal,comm. Of emps.
A) s
elect empno,sal,comm. from emp;
167) List the details of the emps in the ascending order of the sal.
A) select * from emp order by sal asc;
168) List the dept in the ascending order of the job and the desc order of the emps print empno, ename.
A) s
elect * from emp e order by e.job asc,e.empno desc ;
169) Display the unique dept of the emps.
A)select * from dept where deptno in (select unique deptno from emp);
170) Display the unique dept with jobs.
A) s
elect unique deptno ,job from emp ;
171) Display the details of the blake.
A) s
elect * from emp where ename = ‘BLAKE’;
172) List all the clerks.
A) s
elect * from emp where job = ‘CLERK’;
173) list all the employees joined on 1st may 81.
A) s
elect * from emp where hiredate = ’01-MAY-81’;
174) List the empno,ename,sal,deptno of the dept 10 emps in the ascending order of salary.
A) s
elect e.empno,e.ename,e.sal,e.deptno from emp where e.deptno = 10
or
der by e.sal asc;
175) List the emps whose salaries are less than 3500.
A) s
elect * from emp where sal <3500 br="br">176) List the empno,ename,sal of all the emp joined before 1 apr 81.
A) s
elect e.empno ,e.ename .e.sal from emp where hiredate <’01-APR-81’;
177) List the emp whose annual sal is <25000 asc="asc" br="br" in="in" of="of" order="order" salaries.="salaries." the="the">A) s
elect * from emp where (12*sal) < 25000 order by sal asc;
178) List the empno,ename,annsal,dailysal of all the salesmen in the asc ann sal
A) s
elect e.empno,e.ename ,12*sal "ANN SAL" , (12*sal)/365 "DAILY SAL" from emp e
where e.job = 'SALESMAN'
order by "ANN SAL" asc ;
179) List the empno,ename,hiredate,current date & exp in the ascending order of the exp.
A) s
elect empno,ename,hiredate,(select sysdate from dual),((months_between(sysdate,hiredate))/12) EXP
from emp
order by EXP asc;
180) List the emps whose exp is more than 10 years.
A) select * from emp where ((months_between(sysdate,hiredate))/12) > 10;
181) List the empno,ename,sal,TA30%,DA 40%,HRA 50%,GROSS,LIC,PF,net,deduction,net allow and net sal in the ascending order of the net salary.
182) List the emps who are working as managers.
A) s
elect * from emp where job = ‘MANAGER’;
183) List the emps who are either clerks or managers.
A) s
elect * from emp where job in (‘CLERK’,’MANAGER’);
184) List the emps who have joined on the following dates 1 may 81,17 nov 81,30 dec 81
A) select * from emp where to_char(hiredate,’DD-MON-YY’) in
(’
01-MAY-81’,’17-NOV-81’,’30-DEC-81’);
185) List the emps who have joined in the year 1981.
A) select * from emp where to_char(hiredate,’YYYY’) = ‘1981’;
186) List the emps whose annual sal ranging from 23000 to 40000.
A) s
elect * from emp where (12* sal) between 23000 and 40000;
187) List the emps working under the mgrs 7369,7890,7654,7900.
A) select * from emp where mgr in ( 7369,7890,7654,7900);
188) List the emps who joined in the second half of 82.
A)select * from emp where hiredate between ’01-JUL-82’ and ’31-DEC-82’;
189) List all the 4char emps.
A) select * from emp where length (ename) = 4;
190) List the emp names starting with ‘M’ with 5 chars.
A) s
elect * from emp where ename like ‘M%’ and length (ename) = 5;
191) List the emps end with ‘H’ all together 5 chars.
A) s
elect * from emp where ename like ‘%H’ and length (ename) = 5;
192) List names start with ‘M’.
A) s
elect * from emp where ename like ‘M%’;
193) List the emps who joined in the year 81.
A) s
elect * from emp where to_char(hiredate,’YY’) = ‘81’;
194) List the emps whose sal is ending with 00.
A)
select * from where sal like ‘%00’;
195) List the emp who joined in the month of JAN.
A) s
elect * from emp where to_char(hiredate,’MON’) = ‘JAN’; (OR)
B)
select * from emp where to_char (hiredate,’MM’) = 1;
196) Who joined in the month having char ‘a’.
A) s
elect * from emp where to_char (hiredate,’MONTH’) like’%A%’; (OR)
B)
select * from emp where instr(to_char(hiredate,’MONTH’),’A’) >0;
197) Who joined in the month having second char ‘a’
A) s
elect * from emp where to_char(hiredate,’MON’) like ‘_A%’; (OR)
B)
select * from emp where instr(to_char(hiredate,’MON’),’A’) = 2;
198) List the emps whose salary is 4 digit number.
A) s
elect * from emp where length (sal) = 4;(OR)
B)
select * from emp where sal between 999 and 9999;
199) List the emp who joined in 80’s.
A) s
elect * from emp where to_char(hiredate,’YY’) between ‘80’ and ’89’; (OR)
B)
select * from emp where to_char(hiredate,’YY’) >= ‘80’ and to_char(hiredate,’YY’) < ‘90’;
200) List the emp who are clerks who have exp more than 8ys.
A) s
elect * from emp where job = ‘CLERK’ and (months_between(sysdate,hiredate) /12) > 8;
201) List the mgrs of dept 10 or 20.
A) s
elect * from emp where job = ‘MANAGER’ and (deptno = 10 or deptno =20);
202) List the emps joined in jan with salary ranging from 1500 to 4000.
A) s
elect * from emp where to_char(hiredate,’MON’) = ‘JAN’ and sal
be
tween 1500 and 4000;
203) List the unique jobs of dept 20 and 30 in desc order.
A) s
elect distinct job from emp where deptno in (20,30) order by job desc;
204) List the emps along with exp of those working under the mgr whose number is starting with 7 but should not have a 9 joined before 1983.
A) s
elect * from emp where (mgr like '7%' and mgr not like '%9%')
and to_char(hiredate,'YY') < '83';
205) List the emps who are working as either mgr or analyst with the salary ranging from 2000 to 5000 and with out comm.
A) s
elect * from emp where (job in (‘MANAGER’ ,’ANALYST’) ) and sal between 2000 and 5000 and comm is null;
206) List the empno,ename,sal,job of the emps with /ann sal <34000 be="be" but="but" comm.="comm." not="not" receiving="receiving" should="should" some="some" which="which">sal and desg should be sales man working for dept 30.
A) s
elect empno,ename,sal,job from emp where
12*(sal+nvl(comm,0)) < 34000 and comm is not null and comm207) List the emps who are working for dept 10 or 20 with desgs as clerk or analyst with a sal is either 3 or 4 digits with an exp>8ys but does not belong to mons of mar,apr,sep and working for mgrs &no is not ending with 88 and 56.
A) s
elect * from emp where
deptno in (10,20) and
job in ('CLERK','ANALYST') and
(length(sal) in (3,4)) and
((months_between(sysdate,hiredate))/12)> 8 and
to_char(hiredate,'MON') not in ('MAR','SEP','APR') and
(mgr not like '%88' and mgr not like '%56');
208) List the empno,ename,sal,job,deptno&exp of all the emps belongs to dept 10 or 20 with an exp 6 to 10 y working under the same mgr with out comm. With a job not ending irrespective of the position with comm.>200 with exp>=7y and sal<2500 0="0" 9="9" amp="amp" asc="asc" belongs="belongs" br="br" but="but" dept="dept" desc="desc" digits="digits" either="either" having="having" in="in" is="is" mgr="mgr" month="month" no="no" not="not" nov="nov" or="or" sep="sep" the="the" to="to" under="under" whose="whose" working="working">A)
209) List the details of the emps working at Chicago.
A) s
elect * from emp where deptno in (select deptno from dept where dept.loc = ‘CHICAGO’);
210) List the empno,ename,deptno,loc of all the emps.
A) s
elect e.empno,e.ename,e.deptno,d.loc from emp e ,dept d
where e.deptno = d.deptno ;
211) List the empno,ename,loc,dname of all the depts.,10 and 20.
A) s
elect e.empno,e.ename,e.deptno,d.loc,d.dname from emp e ,dept d
where e.deptno = d.deptno and e.deptno in (10,20);
212) List the empno, ename, sal, loc of the emps working at Chicago dallas with an exp>6ys.
A) s
elect e.empno,e.ename,e.deptno,e.sal,d.loc from emp e ,dept d
where e.deptno = d.deptno and d.loc in ('CHICAGO','DALLAS')
and (months_between(sysdate,hiredate)/12)> 6 ;
213) List the emps along with loc of those who belongs to dallas ,newyork with sal ranging from 2000 to 5000 joined in 81.
A) s
elect e.empno,e.ename,e.deptno,e.sal,d.loc from emp e ,dept d
where e.deptno = d.deptno and d.loc in ('NEW YORK','DALLAS')
and to_char(e.hiredate,'YY') = '81' and e.sal between 2000 and 5000;
214) List the empno,ename,sal,grade of all emps.
A) s
elect e.empno,e.ename,e.sal,s.grade from emp e ,salgrade s
where e.sal between s.losal and s.hisal ;
215) List the grade 2 and 3 emp of Chicago.
A) s
elect * from emp where empno in
(select empno from emp e,salgrade s where e.sal between s.losal and
s.hisal and s.grade in (2,3));
216) List the emps with loc and grade of accounting dept or the locs dallas or Chicago with the grades 3 to 5 &exp >6y
A) s
elect e.deptno,e.empno,e.ename,e.sal,d.dname,d.loc,s.grade from emp e,salgrade s,dept d
wh
eree.deptno = d.deptno and e.sal between s.losal and s.hisal
and s.grade in (3,5)
and ((months_between(sysdate,hiredate))/12) > 6
and ( d.dname = 'ACCOUNTING' or D.loc in ('DALLAS','CHICAGO'))
217) List the grades 3 emps of research and operations depts.. joined after 1987 and whose names should not be either miller or allen.
A) s
elect e.ename from emp e ,dept d,salgrade s
where e.deptno = d.deptno and d.dname in ('OPERATIONS','RESEARCH') and e.sal between s.losal and s.hisal
and e.ename not in ('MILLER','ALLEN')
and to_char(hiredate,'YYYY') >1987;
218) List the emps whose job is same as smith.
A) s
elect * from emp where job = (select job from emp where ename = 'SMITH');
219) List the emps who are senior to mi
220) List the emps whose job is same as either allen or sal>allen.
A) s
elect * from emp
where job = (select job from emp where ename = 'ALLEN')
or sal > (select sal from emp where ename = 'ALLEN');
221) List the emps who are senior to their own manager.
A) s
elect * from emp w,emp m where w.mgr = m.empno and
w.hiredate < m.hiredate;
222) List the emps whose sal greater than blakes sal.
A) s
elect * from emp
where sal>(select sal from emp where ename = ‘BLAKE’);
223) List the dept 10 emps whose sal>allen sal.
A) s
elect * from emp where deptno = 10 and
sal > (select sal from emp where ename = 'ALLEN');
224) List the mgrs who are senior to king and who are junior to smith.
A)se
lect * from emp where empno in
(select mgr from emp
where hiredate<(select hiredate from emp where ename = 'KING' )
and hiredate > (select hiredate from emp where ename = 'SMITH')) and mgr is
not null;
225) List the empno,ename,loc,sal,dname,loc of the all the emps belonging to king dept.
A) s
elect e.empno,e.ename,d.loc,e.sal,d.dname from emp e,dept d
where e.deptno=d.deptno and e.deptno in
(select deptno from emp where ename = 'KING'and emp.empno <> e.empno);
226) List the emps whose salgrade are greater than the grade of miller.
A) s
elect * from emp e,salgrade s
where e.sal between s.losal and s.hisal and s.grade >
(select s.grade from emp e,salgrade s where e.sal between s.losal and s.hisal and e.ename = 'MILLER') ;
227) List the emps who are belonging dallas or Chicago with the grade same as adamsor exp more than smith.
A) s
elect * from emp e ,dept d,salgrade s
where e.deptno= d.deptno and d.loc in ('DALLAS','CHICAGO') and e.sal between s.losal and s.hisal and
(s.grade in (select s.grade from emp e,salgrade s where e.sal between s.losal and s.hisal and e.ename = 'ADAMS')
or months_between (sysdate,hiredate) > (select months_between(sysdate,hiredate) from emp where ename = 'SMITH')) ;
228) List the emps whose sal is same as ford or blake.
A) s
elect * from emp where sal in (select sal from emp e where e.ename in ('FORD','BLAKE')and emp.empno <> e.empno);
229) List the emps whose sal is same as any one of the following.
A) s
elect * from emp where sal in
(select sal from emp e where emp.empno <> e.empno);
230) Sal of any clerk of emp1 table.
A) s
elect * from emp where job = ‘CLERK’;
231) Any emp of emp2 joined before 82.
A) select * from emp where to_char(hiredate,'YYYY') < 1982;
232) The total remuneration (sal+comm.) of all sales person of Sales dept belonging to emp3 table.
A) s
elect * from emp e
where (sal+nvl(comm,0)) in
(select sal+nvl(comm,0) from emp e,dept d where e.deptno=d.deptno
and d.dname = 'SALES'and e.job = 'SALESMAN');
233) Any Grade 4 emps Sal of emp 4 table.
A) s
elect * from emp4 e,salgrade s where e.sal between s.losal and s.hisal and s.grade = 4;
234) Any emp Sal of emp5 table.
A) s
elect * from emp5;
235) List the highest paid emp.
A) s
elect * from emp where sal in (select max(sal) from emp);
236) List the details of most recently hired emp of dept 30.
A) s
elect * from emp where hiredate in
(select max(hiredate) from emp where deptno = 30);
237) List the highest paid emp of Chicago joined before the most recently hired emp of grade 2.
A) s
elect * from emp
where sal = ( select max(sal) from emp e,dept d where e.deptno =
d.deptno and d.loc = ‘CHICAGO’ and
hiredate <(select max(hiredate) from emp e ,salgrade s
where e.sal between s.losal and s.hisal and s.grade = 2))
238) List the highest paid emp working under king.
A)se
lect * from emp where sal in
(select max(sal) from emp where mgr in
(select empno from emp where ename = 'KING'));