SQL
SQL
SQL
SQL
1. Which is the subset of SQL commands used to manipulate Oracle Database
structures, including tables?
Data Definition Language (DDL)
5. What is the parameter substitution symbol used with INSERT INTO command?
&
6. Which command displays the SQL command in the SQL buffer, and then executes it?
RUN
9. State true or false. !=, <>, ^= all denote the same operation.
True
10. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all
11. What command is used to get back the privileges offered by the GRANT command?
REVOKE
12. Which system tables contain information on privileges granted and privileges
obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD
13. Which system table contains information on constraints on all the tables created?
USER_CONSTRAINTS
16. What command is used to create a table by copying the structure of another table?
Answer :
CREATE TABLE .. AS SELECT command
Explanation :
To copy only the structure, the WHERE clause of the SELECT command should
contain a FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE
WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition
will be copied to the new table.
20. Which date function is used to find the difference between two dates?
MONTHS_BETWEEN
22. What is the advantage of specifying WITH GRANT OPTION in the GRANT
command?
The privilege receiver can further grant the privileges he/she has obtained from
the owner to any other user.
23. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.
24. What is the value of ‘comm’ and ‘sal’ after executing the following query if the initial
value of ‘sal’ is 10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;
sal = 11000, comm = 1000
27. Which function is used to find the largest integer less than or equal to a specific
value?
FLOOR
SQL – QUERIES
I. SCHEMAS
Table 1 : STUDIES
PNAME (VARCHAR), SPLACE (VARCHAR), COURSE (VARCHAR), CCOST
(NUMBER)
Table 2 : SOFTWARE
Table 3 : PROGRAMMER
LEGEND :
PNAME – Programmer Name, SPLACE – Study Place, CCOST – Course Cost, DEVIN
– Developed in, SCOST – Software Cost, DCOST – Development Cost, PROF1 –
Proficiency 1
QUERIES :
1. Find out the selling cost average for packages developed in Oracle.
2. Display the names, ages and experience of all programmers.
3. Display the names of those who have done the PGDCA course.
4. What is the highest number of copies sold by a package?
5. Display the names and date of birth of all programmers born in April.
6. Display the lowest course fee.
7. How many programmers have done the DCA course.
8. How much revenue has been earned through the sale of packages developed in C.
9. Display the details of software developed by Rakesh.
10. How many programmers studied at Pentafour.
11. Display the details of packages whose sales crossed the 5000 mark.
12. Find out the number of copies which should be sold in order to recover the
development cost of each package.
13. Display the details of packages for which the development cost has been
recovered.
14. What is the price of costliest software developed in VB?
15. How many packages were developed in Oracle ?
16. How many programmers studied at PRAGATHI?
17. How many programmers paid 10000 to 15000 for the course?
18. What is the average course fee?
19. Display the details of programmers knowing C.
20. How many programmers know either C or Pascal?
21. How many programmers don’t know C and C++?
22. How old is the oldest male programmer?
23. What is the average age of female programmers?
24. Calculate the experience in years for each programmer and display along with
their names in descending order.
25. Who are the programmers who celebrate their birthdays during the current
month?
26. How many female programmers are there?
27. What are the languages known by the male programmers?
28. What is the average salary?
29. How many people draw 5000 to 7500?
30. Display the details of those who don’t know C, C++ or Pascal.
31. Display the costliest package developed by each programmer.
32. Produce the following output for all the male programmers
Programmer
Mr. Arvind – has 15 years of experience
KEYS:
II . SCHEMA :
Table 1 : DEPT
Table 2 : EMP
MGR is the empno of the employee whom the employee reports to. DEPTNO is a foreign
key.
QUERIES
1. List all the employees who have at least one person reporting to them.
2. List the employee details if and only if more than 10 employees are present in
department no 10.
3. List the name of the employees with their immediate higher authority.
4. List all the employees who do not manage any one.
5. List the employee details whose salary is greater than the lowest salary of an
employee belonging to deptno 20.
6. List the details of the employee earning more than the highest paid manager.
7. List the highest salary paid for each job.
8. Find the most recently hired employee in each department.
9. In which year did most people join the company? Display the year and the number of
employees.
10. Which department has the highest annual remuneration bill?
11. Write a query to display a ‘*’ against the row of the most recently hired employee.
12. Write a correlated sub-query to list out the employees who earn more than the
average salary of their department.
13. Find the nth maximum salary.
14. Select the duplicate records (Records, which are inserted, that already exist) in the
EMP table.
15. Write a query to list the length of service of the employees (of the form n years and m
months).
KEYS:
Topics
• What is PL/SQL and what is it used for?
• Should one use PL/SQL or Java to code procedures and triggers?
• How can one see if somebody modified any code?
• How can one search PL/SQL code for a string/key value?
• How can one keep a history of PL/SQL code changes?
• How can I protect my PL/SQL source code?
• Can one print to the screen from PL/SQL?
• Can one read/write files from PL/SQL?
• Can one call DDL statements from PL/SQL?
• Can one use dynamic SQL statements from PL/SQL?
• What is the difference between %TYPE and %ROWTYPE?
• What is the result of comparing NULL with NULL?
• How does one get the value of a sequence into a PL/SQL variable?
• Can one execute an operating system command from PL/SQL?
• How does one loop through tables in PL/SQL?
• How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?
• I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?
• What is a mutating and constraining table?
• Can one pass an object/table as an argument to a remote procedure?
• Is it better to put code in triggers or procedures? What is the difference?
• Is there a PL/SQL Engine in SQL*Plus?
• Is there a limit on the size of a PL/SQL block?
• Where can one find more info about PL/SQL?
PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the
difference between these two language environments:
PL/SQL:
Java:
How can one search PL/SQL code for a string/ key value?
The following query is handy if you want to know where a certain table, field or expression is referenced in
your PL/SQL source code.
SELECT TYPE, NAME, LINE
FROM USER_SOURCE
WHERE UPPER(TEXT) LIKE '%&KEYWORD%';
• Back to top of file
This is done via a standalone utility that transforms the PL/SQL source code into portable binary object
code (somewhat larger than the original). This way you can distribute software without having to worry
about exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will still understand
and know how to execute such scripts. Just be careful, there is no "decode" command available.
DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the output
buffer will overflow. In that case, set the buffer size to a larger value, eg.: set serveroutput on size 200000
If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and then EXEC
NULL;. If you haven't cleared the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus
will display the entire contents of the buffer when it executes this dummy PL/SQL block.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/tmp', 'myfile', 'w');
UTL_FILE.PUTF(fileHandler, 'Look ma, I''m writing to a
file!!!\n');
UTL_FILE.FCLOSE(fileHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'ERROR: Invalid path for
file or path not in INIT.ORA.');
END;
/
• Back to top of file
-- Returning a cursor...
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at
these examples:
CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)',
DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
More complex DBMS_SQL example using bind variables:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE)
AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno
> :x', DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception
Raised: '||sqlcode||' '||sqlerrm);
END;
/
• Back to top of file
%ROWTYPE is used to declare a record with the same types as found in the specified database table, view
or cursor. Example:
DECLARE
v_EmpRecord emp%ROWTYPE;
%TYPE is used to declare a field with the same type as that of a specified table's column. Example:
DECLARE
v_EmpNo emp.empno%TYPE;
• Back to top of file
What is the result of comparing NULL with NULL?
NULL is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL is evaluated to
NULL. Look at this code example to convince yourself.
declare
a number := NULL;
b number := NULL;
begin
if a=b then
dbms_output.put_line('True, NULL = NULL');
elsif a<>b then
dbms_output.put_line('False, NULL <> NULL');
else
dbms_output.put_line('Undefined NULL is neither = nor <> to
NULL');
end if;
end;
• Back to top of file
How does one get the value of a sequence into a PL/SQL variable?
As you might know, one cannot use sequences directly from PL/SQL. Oracle (for some silly reason)
prohibits this:
i := sq_sequence.NEXTVAL;
However, one can use embedded SQL statements to obtain sequence values:
select sq_sequence.NEXTVAL into :i from dual;
In Oracle8 one can call external 3GL code in a dynamically linked library (DLL or shared object). One just
write a library in C/ C++ to do whatever is required. Defining this C/C++ function to PL/SQL makes it
executable. Look at this External Procedure example.
To fix this problem one can easily rewrite code like this:
NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI standard.
• Grant direct access on the tables to your user. Do not use roles!
• GRANT select ON scott.emp TO my_user;
Another way this error can occur is if the trigger has statements to change the primary, foreign or unique
key columns of the table off which it fires. If you must have triggers on tables that have referential
constraints, the workaround is to enforce the referential integrity through triggers as well.
• A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can
be accessed by the trigger) .
• A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the
result of a CASCADE delete.
• Etc.