0% found this document useful (0 votes)
3 views9 pages

Oracle Answers

The document provides an overview of various SQL clauses and commands, including GROUP BY, ORDER BY, HAVING, DISTINCT, UPDATE, JOIN types, and procedures. It explains how to create and execute procedures, handle exceptions, and utilize triggers in SQL. Additionally, it covers set operations and provides examples for various SQL queries and procedures.

Uploaded by

aniruddh2573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Oracle Answers

The document provides an overview of various SQL clauses and commands, including GROUP BY, ORDER BY, HAVING, DISTINCT, UPDATE, JOIN types, and procedures. It explains how to create and execute procedures, handle exceptions, and utilize triggers in SQL. Additionally, it covers set operations and provides examples for various SQL queries and procedures.

Uploaded by

aniruddh2573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1.

GROUP BY CLAUSE
Another helpful clause is the group by clause. A group by clause arranges your
data rows into a group according to the columns you specify.
A query that includes group by clause is called a grouped query because it groups
that data from the SELECT tables and generates single summary row for each
group.
The columns named in the group by clause are called the grouping columns.
When GROUP BY clause is used, each item in the SELECT list must be single-
valued per group.
The select clause may contain only :
• Column names
• Aggregate functions
• Constants
• An expression involving combinations of the above.
Example : SELECT * FROM EMPLOYEE GROUP BY DEPT;

2. ORDER BY CLAUSE
ORDER BY clause is similar to the GROUP BY clause. The ORDER BY clause
enables you to sort your data in either ascending or descending order.
The ORDER BY clause consists of a list of column identifiers that the result is to
be sorted on, separated by columns. A column identifier may be either a column
name or a column number.
Example : SELECT * FROM EMPLOYEE ORDER BY F_NAME ASC;

3. HAVING CLAUSE
The Having clause is similar to the where clause. The Having clause does for
aggregate data what where clause does for individual rows. The having clause is
another search condition. In this case, however, the search is based on each group
of grouped table.
Example : SELECT * FROM EMPLOYEE GROUP BY STATUS, GENDER
HAVING GENDER = 'F';

4. DISTINCT CLAUSE
SELECT statement has an optional Keyword distinct. This keyword follows select
and return only those rows which have distinct values for the specified columns.
i.e. it eliminates duplicate values.
The keyword all allows to specify explicitly that the duplicates are not removed.
Example : SELECT DISTINCT DESIGNATION FROM EMPLOYEES;

5. UPDATE Statement
If you want to modify existing data in the database, UPDATE command can be
used to do that. With this statement you can update zero or more rows in a table.
The UPDATE statement references a single table and assigns an expression to at
least one column. The WHERE clause is optional; if an UPDATE statement does
not contain a WHERE clause, the assignment of a value to a column will be
applied to all rows in the table.
Example : Update Instructor
Set Position = 'Professor'
Where Instructor_id = 'P3021';

6. NON-EQUI JOIN
Whereas the equi-join uses an = sign in the WHERE statement, the non-equi-
join uses everything but an = sign.
For example :
SELECT O.NAME, O.PARTNUM,
P.PARTNUM, O.QUANTITY * P.PRICE
TOTAL FROM ORDERS O, PART P
WHERE O.PARTNUM > P.PARTNUM

7. EQUI JOIN
equi-join goal is to match the values of a column in one table to the corresponding
values in the second table. You can further qualify query by adding more
conditions in the WHERE
clause.
For example:
SELECT O.ORDEREDON, O.NAME, O.PARTNUM, P.PARTNUM,
P.DESCRIPTION FROM ORDERS O, PART P
WHERE O.PARTNUM = P.PARTNUM AND O.PARTNUM = 76

8. SELF JOIN
A self join is a join in which a table is joined with itself (which is also called
Unary relationships), especially when the table has a FOREIGN KEY which
references its own PRIMARY KEY. To join a table itself means that each row of
the table is combined with itself and with every other row of the table.
The self join can be viewed as a join of two copies of the same table. The table is
not actually copied, but SQL performs the command as though it were.

Example : SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee


Name", b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name"
FROM employee a, employee b WHERE a.emp_supv = b.emp_id;

9. SYNTAX FOR CREATING AND EXECUTING PROCEDURE


A procedure is created using CREATE PROCEDURE command.
Syntax :
CREATE [OR REPLACE] PROCEDURE procedure_name
[(argument [in/out/in out] datatype [,argument [in/out/in out] datatype…..])]
{IS / AS}
[variable declaration]
{PL/SQL block};

IN indicate the variable is passed by the calling program to procedure.


OUT indicate that the variable pass value from procedure to calling program.
IN OUT indicate that the variable can pass values both in and out of a procedure.
Datatype specify any PL/SQL datatype.

EXECUTING A PROCEDURE
To execute the stored procedure simply call it by name in EXECUTE command as
SQL> execute myproc1(7768);
This will execute myproc1 with the value 7768. The second method of calling the
procedure is Write the following code in an editor.
Declare
C_empno number;
Begin
Myproc1(&c_empno);
End;
/

10.VARIANCE and STDDEV

• VARIANCE
VARIANCE produces the square of the standard deviation, a number vital to
many statistical calculations. It works like this :
INPUT :
SQL> SELECT VARIANCE(HITS) FROM TEAMSTATS;
OUTPUT :
VARIANCE(HITS)
--------------
802.96667

STDDEV
The final group function, STDDEV, finds the standard deviation of a column of
numbers, as demonstrated by this example :
INPUT :
SQL> SELECT STDDEV(HITS) FROM TEAMSTATS;

OUTPUT :
STDDEV(HITS)
----------------------
28.336666

11.The FOR Loop

Syntax :
FOR variable IN [REVERSE] start..end
LOOP
<Action> END LOOP;
Example :
FOR Lcntr IN 1..20
LOOP
LCalc := Lcntr * 31;
END LOOP;

12.CREATE VIEW
The command to specify a view is CREATE VIEW. 'We give the view a table
name, a list of attribute names, and a query to specify the contents of view. If
none of the view attributes result from applying functions or arithmetic
operations, we do not have to specify attribute names for the view as they will
be the same as the names of the attributes of the defining tables.

Example:
Create view emp_detail (emp, comp, street, city)
As select C.emp_name, C.comp_name, E.street, E.city from Employee E,
company C where E.emp_name = C.emp_name;

13.SQL CURSOR ATTRIBUTES


The SQL cursor attributes are :
1. %ROWCOUNT : The number of rows processed by a SQL statement.
2. %FOUND : TRUE if at least one row was processed.
3. %NOTFOUND : TRUE if no rows were processed.
4. %ISOPEN : TRUE if cursor is open or FALSE if cursor has not been
opened or has been closed. Only used with explicit cursors.

14.EXPLICIT CURSOR
If SELECT statements in PL/SQL block return multiple rows then you have
to explicitly create a cursor which is called as explicit cursor. The set of rows
returned by a explicit cursor is called a result set. The row that is being
processed is called the current row. Oracle uses four commands to handle
Cursors. They are :
1. DECLARE : Defines the name and structure of the cursor together with the
SELECT statement.
2. OPEN : Executes the query and the number of rows to be returned
is determined.
3. FETCH : Loads the row addressed by the cursor pointer into variables and
moves the cursor pointer on to the next row ready for the next fetch.
4. CLOSE : Releases the data within the cursor and closes it.

For example :
DECLARE
CURSOR c_deptno IS SELECT ename,sal,deptno
FROM EMP;
15.EXCEPTION IN SQL

Exceptions occur when either an Oracle error occurs (this automatically raises
an exception) or you explicitly raise an error or a routine that executes
corrective action when detecting an error. Thus Exceptions are identifiers in
PL/SQL that are raised during the execution of a block to terminate its action.
There are two classes of exceptions, these are :
1. Predefined exception :
Oracle predefined errors which are associated with specific error codes.
2. User-defined exception :
Declared by the user and raised when specifically requested within a
block. You can associate a user-defined exception with an error code if
you wish.

16. TYPES OF TRIGGERS


The trigger can be activated by a SQL command or by system event or a user
event which are called triggering events.
According to these events, trigger types are :
1. TABLE triggers : Applied to DML commands (INSERT / DELETE /
UPDATE).
2. SYSTEM EVENT triggers : Such as startup, shutdown of the database and
server error message event.
3. USER EVENT triggers : Such as User logon and logoff, DDL commands
(CREATE, ALTER, DROP), DML commands (INSERT, DELETE,
UPDATE).

LONG QUESTIONS

1. SET OPERATIONS
The SQL operations UNION, INTERSECT and MINUS operate on relations and
correspond to the relational algebra operations , , – .
Like the union, intersect and set difference in relational algebra, the relations
participating in the operations must be compatible, i.e. they must have the same set of
attributes.

Union operator :
The syntax for this set operator is :
select_statement 1
Union select_statement 2 [ order_by_clause]

Intersect Operator :
The Intersect operator returns the rows that are common between two sets of rows.
The syntax for using the INTERSECT operator is :
select_statement-1
Intersect select_statement-2 [Order_By_clause]
The Minus Operator (Except operator) :
The syntax for using Minus operator is :
select_statement 1
Minus select_statement 2 [order by clause]

2. Create a trigger before inserting a row which checks whether the salary is 0
and raise application error.
create trigger tr_sal
before insert on emp
for each row
begin
if :new.sal = 0 then
Raise_application_error('-20010','Salary should be greater than 0');
end if;
end;

3. Create a trigger before deleting a row which checks whether the salary is not
0 and raise application error.

create trigger tr_sal


before delete on emp
for each row
begin
if :old.sal !=0 then
Raise_application_error('-20010','Reord can not be deleted');
end if;
end;

4. Write SQL CODE to Pass salary to procedure and procedure will give no. of
employee(s) having salary equal to given salary in the same variable. (Use IN
OUT variable)

CREATE OR REPLACE PROCEDURE myproc3


(p_sal IN OUT emp.sal%TYPE) /* arguments */
IS
v_count number;
BEGIN
Select count(*) into v_count From emp Where sal=p_sal;
P_sal:=v_count;
EXCEPTION WHEN NO_DATA_FOUND THEN
P_sal:=0;
END myproc3;

Calling procedure myproc3 using following code


Declare
C_sal emp.sal%TYPE;
Begin
C_sal:=&c_sal;
Myproc3(c_sal);
If c_sal=0 then
Dbms_output.put_line(‘No employee is having salary equal to accepted
salary’);
Else
Dbms_output.put_line(‘No. of emp. having salary = accepted salary are ’ ||
c_sal);
End if;
End;

5. Write SQL CODE to Pass dept to procedure and procedure will give no. of
employee(s) in given department in the same variable. (Use IN OUT
variable)

CREATE OR REPLACE PROCEDURE myproc4


(p_dept IN OUT emp.dept%TYPE) /* arguments */
IS
v_count number;
BEGIN
Select count(*) into v_count From emp Where dept=p_dept;
P_dept:=v_count;
EXCEPTION WHEN NO_DATA_FOUND THEN
P_dept:=0;
END myproc4;

Calling procedure myproc4 using following code


Declare
C_dept emp.dept%TYPE;
Begin
C_deptl:=&c_dept;
Myproc4(c_dept);
If c_dept=0 then
Dbms_output.put_line(‘No employee is in the dept’);
Else
Dbms_output.put_line(‘No. of emp. In the dept are ’ || c_dept);
End if;
End;

6. Accept empno and print its details(using cursor).


declare
v_no emp.empno%type:=&v_no;
v_name emp.ename%type;
v_job emp.job%type;
v_sal emp.sal%type;
begin
select ename, job, sal into v_name,v_job,v_sal
from emp where empno=v_no;
if sql%found then /* sql%found is true if empno=v_no */
dbms_output.put_line(v_name ||’ ‘||v_job||’ ‘||v_sal);
exception
when no_data_found then
dbms_output.put_line ('empno does not exists');
end;

7. Accept empno and check whether comm is null or not. If comm is null
raise an exception otherwise display comm.

DECLARE
v_comm emp.comm%type;
v_empno emp.empno%type;
check_comm exception;
BEGIN
v_empno:=&v_empno;
select comm into v_comm
from emp where empno=v_empno;
if v_comm is NULL then
raise check_comm;
else
dbms_output.put_line('comm = '||v_comm);
end if;
Exception
When no_data_found then
dbms_output.put_line('Empno does not exists');
When check_comm then
dbms_output.put_line('Empno getting null comm');
End;

8. Get the names and pay rates of employees with emp_no less than 123460
whose rate of pay is more than the rate of pay of at least one employee
with emp_no greater than or equal to 123460.

select name, pay_rate from Employee


where emp_no < 123460 and pay_rate > some
(select pay_rate from Employee
where emp_no ≥ 123460);

9. Find the names of all employees who are assigned to all positions that
require a Chef’s skill.
select S.Name from Employee S
where
(select posting_no from Duty_allocation D
where S.emp_no = D.emp_no)
contains
(select P.posting_no from position P
where P.skill = 'Chef')

10.Find the names and the rate of pay of all employees who are allocated a
duty.

select name, pay_rate from Employee


where EXISTS
(select * from Duty_allocation
where Employee.emp_no = Duty_allocation.emp_no)

*********

You might also like