PLSQL Questions 2

download PLSQL Questions 2

If you can't read please download the document

description

PLSQL Questions 2

Transcript of PLSQL Questions 2

Set-IV

PART-1

1. what is the diff between call by value and call by reference? Ans: call by value passes the value, call by reference passes the address of a variable. 2. do u know about method 4? Ans: - To build a dynamic sql statement. - The no.of select list items, the no.of place holders input host variables and the datatypes of the input host variables can be unknown at run time. 3. what are the parameters in procedure? Ans: in,out,inout. 4. can we modify the IN parameter ? Ans: No, 5. what is OUT parameter? Ans: out parameter is used to return values to the caller of a sub program. 6. suppose there are two tables with same structure, I want to display all the records in two tables using order by. Ans: : select * from (select city_name, city_code from city1 union all select city_name, city_code from city2) order by city_name; 7. how to restrict a program and table to run other users while I am running? Ans: using Lock and for update commands. 8. How much time does it takes to generate a report, if there are 1 lack records? Ans: : depending upon the complexity of the query. 9. write a plsql block to update a record with emp_name and emp_no, if that record is not there insert into the table. Ans:declare Erec emp%rowtype Begin Select ename, eno from emp; If(sql%rowcount>0) Update emp set ename=ram where sal=10000; Else Insert into emp (ename, eno) values(ram,10); End; 10. what is your role in your project? Ans: s/w developer. 11. How to handle core dump errors? Ans:- using gdb and dbx Type gdb at command line. Then press enter Type r 12. how you trace core dump errors without using tools?

Ans: signal handling. 13. can you create your own datatype in C? Ans: hint : enumerated data types. 14. Suppose in my database 1 lack records are there, I am generating report, after generating 10,000 records the program is aborted, if I again start the program from which record it generates the report? Ans: 10,001th record. 15. How to call a procedure in proc? Ans: exec sql execute Procedure_name (host variables) End-exec; 16. how to pass parameters to a pl/sql procedure in a proc program? Ans: :--- using host variables. Set-V 1) Can u rename a column in a table Ans: alter table emp rename column empno to empnumber; 2) I have 10 insert statements I want to roll back some statements How it is possible Ans: using save points. 3) What is correlated sub query ? write a correlated query Ans: Is evaluated once per row processed by the parent statement. Ex: select a.* from emp a where a.sal=a.sal)

3. /* Selecting Nth Minimum Salary from emp */ select ename,sal from emp a where &n = (select count(distinct(sal)) from emp b where 4. /* Selecting Salary and Rownum from Emp */ select sal,rownum from emp order by sal 5. /* Selecting Alternative Rows From A Table */ / select empno,ename,sal from(select empno,ename,sal , mod(rownum,2) a from emp ) b where b.a=0 6. /* Insert values from one table to another table */ insert into empdup select * from emp Note: AS and VALUES keywords are not used in this statement 7. /* Deleting duplicate rows from a table */ delete empdup a where rowid (select max(rowid) from empdup b where a.empno = b.empno) 8. /* To Print A Number In Words */ select to_char(to_date(1234,'JSP'),'JSP') from dual 9. /* To Find The No Of Columns In A table */ select count(*) from user_tab_columns where table_name = 'EMP' 10. /* To Get The SALs greater than 1000 in each DEPT */ select sal,count(sal),dname from emp a,dept b where a.deptno = b.deptno group by sal,dname having sal>1000 order by dname

b.sal 1000 group by a.deptno,dname,sal order by dname 12. select deptno, sum(decode(job,'CLERK',1,0)) "CLERK", sum(decode(job,'SALESMAN',1,0)) "'SALESMAN", sum(decode(job,'MANAGER',1,0)) "MANAGER", sum(decode(job,'ANALYST',1,0)) "ANALYST", count(decode(job,'CLERK',1,'SALESMAN',1, 'MANAGER',1,'ANALYST',1)) "TOTAL" from emp group by deptno CLERK 'SALESMAN MANAGER ANALYST ---------- ---------0 0 1 0 1 4 ---------1 1 1 ---------0 2 0 ---------1 4 6

Ans: DEPTNO TOTAL ------10 20 30

-----------------------------------------------------------------------------------------------------------PART - 2

Oracle Interview Questions and Answers : SQL1. To see current user name Sql> show user; 2. Change SQL prompt name SQL> set sqlprompt Manimara > Manimara > Manimara > 3. Switch to DOS prompt SQL> host 4. How do I eliminate the duplicate rows ? SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name); or SQL> delete duplicate_values_field_name dv from table name at where rowid

SQL> select rownum, ename from emp; Output: 1 Scott 2 Millor 3 Jiyo 4 Smith 6. Display the records between two range select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp; the output like, SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) --------- ----------------------------------------------------800 eight hundred

1600 one thousand six hundred 1250 one thousand two hundred fifty If you want to add some text like, Rs. Three Thousand only. SQL> select sal "Salary ", (' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) "Sal in Words" from emp / Salary Sal in Words ------- -----------------------------------------------------800 Rs. Eight Hundred only. 1600 Rs. One Thousand Six Hundred only. 1250 Rs. One Thousand Two Hundred Fifty only. 14. Display Odd/ Even number of records Odd number of records: select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp); 1 3 5 Even number of records: select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp) 2 4 6 15. Which date function returns, number value? months between 16. Any three PL/SQL Exceptions? Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others 17. What are PL/SQL Cursor Exceptions? Cursor_Already_Open, Invalid_Cursor 18. Other way to replace query result null value with a text SQL> Set NULL N/A to reset SQL> Set NULL 19. What are the more common pseudo-columns? SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM 20. What is the output of SIGN function? 1 for positive value, 0 for Zero, -1 for Negative value. 21. What is the maximum number of triggers, can apply to a single table? 12 triggers. . How would you determine the time zone under which a database was operating?21

select DBTIMEZONE from dual;

22. Explain the use of setting GLOBAL_NAMES equal to TRUESetting GLOBAL_NAMES dictates how you might connect to a database. This variable is either TRUE or FALSE and if it is set to TRUE it enforces database links to have the same name as the remote database to which they are linking. 23. What command would you use to encrypt a PL/SQL application? WRAP

24. Explain the difference between a FUNCTION, PROCEDURE and PACKAGE. A function and procedure are the same in that they are intended to be a collection of PL/SQL code that carries a single task. While a procedure does not have to return any values to the calling application, a function will return a single value. A package on the other hand is a collection of functions and procedures that are grouped together based on their commonality to a business function or application. 25. Explain the use of table functions. Table functions are designed to return a set of rows through PL/SQL logic but are intended to be used as a normal table or view in a SQL statement. They are also used to pipeline information in an ETL process. 26. Name three advisory statistics you can collect. Buffer Cache Advice, Segment Level Statistics, & Timed Statistics 27. Where in the Oracle directory tree structure are audit traces placed? In unix $ORACLE_HOME/rdbms/audit, in Windows the event viewer 28. Explain materialized views and how they are used. Materialized views are objects that are reduced sets of information that have been summarized, grouped, or aggregated from base tables. They are typically used in data warehouse or decision support systems. 29. When a user process fails, what background process cleans up after it? PMON 30. What background process refreshes materialized views? The Job Queue Processes. 31. How would you determine what sessions are connected and what resources they are waiting for? Use of V$SESSION and V$SESSION_WAIT 32. Describe what redo logs are. Redo logs are logical and physical structures that are designed to hold all the changes made to a database and are intended to aid in the recovery of a database. 33. How would you force a log switch? ALTER SYSTEM SWITCH LOGFILE; 34. Give two methods you could use to determine what DDL changes have been made. You could use Logminer or Streams 35. What does coalescing a tablespace do? Coalescing is only valid for dictionary-managed tablespaces and de-fragments space by combining neighboring free extents into large single extents. 36. What is the difference between a TEMPORARY tablespace and a PERMANENT tablespace? A temporary tablespace is used for temporary objects such as sort structures while permanent tablespaces are used to store those objects meant to be used as the true objects of the database. 37. Name a tablespace automatically created when you create a database. The SYSTEM tablespace.

38. When creating a user, what permissions must you grant to allow them to connect to the database? Grant the CONNECT to the user. 39. How do you add a data file to a tablespace? ALTER TABLESPACE ADD DATAFILE SIZE 40. How do you resize a data file? ALTER DATABASE DATAFILE RESIZE ; 41. What view would you use to look at the size of a data file? DBA_DATA_FILES 42. What view would you use to determine free space in a tablespace? DBA_FREE_SPACE 43. How would you determine who has added a row to a table? Turn on fine grain auditing for the table. 44. How can you rebuild an index? ALTER INDEX REBUILD; 45. Explain what partitioning is and what its benefit is. Partitioning is a method of taking large tables and indexes and splitting them into smaller, more manageable pieces. 46. You have just compiled a PL/SQL package but got errors, how would you view the errors? SHOW ERRORS 47. How can you gather statistics on a table? The ANALYZE command. 48. How can you enable a trace for a session? Use the DBMS_SESSION.SET_SQL_TRACE or Use ALTER SESSION SET SQL_TRACE = TRUE; 49. What is the difference between the SQL*Loader and IMPORT utilities? These two Oracle utilities are used for loading data into the database. The difference is that the import utility relies on the data being produced by another Oracle utility EXPORT while the SQL*Loader utility allows data to be loaded that has been produced by other utilities from different data sources just so long as it conforms to ASCII formatted or delimited files. 50. Name two files used for network connection to a database. TNSNAMES.ORA and SQLNET.ORA Technical - UNIX Every DBA should know something about the operating system that the database will be running on. The questions here are related to UNIX but you should equally be able to answer questions related to common Windows environments. 1. How do you list the files in an UNIX directory while also showing hidden files? ans: ls-ltr 2. How do you execute a UNIX command in the background? ans:Use the "&" 3. What UNIX command will control the default file permissions when files are created?

ans:Umask 4. Explain the read, write, and execute permissions on a UNIX directory. ans:Read allows you to see and list the directory contents. Write allows you to create, edit and delete files and subdirectories in the directory. Execute gives you the previous read/write permissions plus allows you to change into the directory and execute programs or shells from the directory. 5. the difference between a soft link and a hard link? A symbolic (soft) linked file and the targeted file can be located on the same or different file system while for a hard link they must be located on the same file system. 6. Give the command to display space usage on the UNIX file system. df -lk 7. Explain iostat, vmstat and netstat. Iostat reports on terminal, disk and tape I/O activity. Vmstat reports on virtual memory statistics for processes, disk, tape and CPU activity. Netstat reports on the contents of network data structures. 8. How would you change all occurrences of a value using VI? Use :%s///g 9. Give two UNIX kernel parameters that effect an Oracle install SHMMAX & SHMMNI 10. Briefly, how do you install Oracle software on UNIX. Basically, set up disks, kernel parameters, and run orainst. I hope that these interview questions were not too hard. Remember these are "core" DBA questions and not necessarily related to the Oracle options that you may encounter in some interviews. Take a close look at the requirements for any job and try to extract questions that interviewers may ask from manuals and real life experiences. For instance, if they are looking for a DBA to run their databases in RAC environments, you should try to determine what hardware and software they are using BEFORE you get to the interview. This would allow you to brush up on particular environments and not be caught off-guard. Good luck! -----------------------------------------------------------------------------------------------------------Set-III PART -3

1. What is the function, which do not use index? Ans. To_char(); 2. Is there any query to find whether the query using index? Ans: EXPLAIN PLAN SET STATEMENT_ID = 'raja1' FOR SELECT a.repid,a.repname,b.route_id,b.nonstop FROM nrep a,nroute_det b WHERE a.repid=123 AND a.repname='naren' AND b.route_id=105 AND b.nonstop='n';

3. Is there any function, which is like decode? Ans: Case function refer BOOK.PDF page no 336.

4. Write query for delete duplicate rows? Ans: DELETE FROM emp a WHERE ROWID (SELECT MAX(ROWID) FROM emp b WHERE a.empno = b.empno); 5. How list of values work? 6. What are the conditions where index should not be used? Ans: 1. When table have less no of columns. 2. When we want to retrieve almost all the rows from the table 3. The table is small. 4. The columns are not often used as a condition in query. 5. The table updated frequently. 7. What is the function, which do not use index? Ans. To_char(). 8. Is there any query to find whether the query using index? Ans. Explain plan set statement_id=xxxx for 9. Is there any function, which is like decode? Ans: Case function refers to CR page no 336. 10. Write query for delete duplicate rows? Ans. Delete from emp a where rowid (select max(rowid) from emp b where

a.empno=b.empno) 11. How list of values work? Ans. 12. What are the conditions where index should not be used? Ans. 1. When table have less no of columns. 2. When we want to retrieve almost all the rows from the table 3. The table is small. 4. The columns are not often used as a condition in query. 5. The table updated frequently. 13. If you have written a proc program and client has complaint about the program consuming more timeso then what u will do? Ans.using optimization techniques we have to reduce the cost of the queries those are used in our program. 14. What is difference between truncate and delete? Ans.1. Truncate is the DDL command. Delete is the DML command. 2. Truncate should not maintain the backup. Delete maintains the backup. 3. Using Truncate single row deletion is not possible. Using Delete single row deletion is possible. 4.Truncate implicitely commit. Delete explicitely commit. 5.Rollback is not possible in truncate. Rollback is possible in delete. 15. What is difference between view and synonym? Ans. 1. We can create view for more than one table. We cant create synonym for more than one table. 2. View can be accessed by all users. But private synonym can be accessed by the user who is created that synonym. 3. We can hide the date in the base table using views. We can not hide the data in the base table using Synonym. 16. What is index and what are all the different types of index? Ans. Index is a schema object that can be speed up the retrieval of rows by using a pointer. Indexes are created explicitly or automatically. There are 6 types of indexes. 1. Binary index(by default). 2. Bit map index. 3. Compressed index. 4. Function based index. 5. Reversed order key index. 6. Indexed organization table.(IOT). 17. What is different between stored procedure and trigger? Ans: trigger fires automatically, but we have to explicitly call the stored procedure.

18. What is a sequence? Ans: sequence is used to generate sequential integer values. 19. Why do you use lset, mset and null set? Ans: to mark the end of string null set is used, While initializing a variable junk chars will be assigned to the variable so replace junk chars by \0 we do memset When we are entering the data into database we have to lset the variables. 20. What is a dual? Ans: dual is a virtual table which consists of one dummy column & one row. 21. How do u handle exceptions in proc? Ans: SQLCA, ORACA,WHENEVER 22. What is procedure Tell me about in and inout? ANS: it is a sub program which performs a specific task,in is used to pass values to the sub program inout is used to pass values to subprogram and returns updated values to caller of subprogram. 23. What is a function? Ans: it is a sub program, which is used to return values. only in parameter is used in function. 24. What is a package? Why do u need a package? Ans. A Package is a schema object that groups logically related types,items and subprograms. Packages are having many advantages namely 1. Modularity. 2. Easier application design. 3. Information hiding. 4. Added functionality and better performance. set-IV 1. If you have written a proc program and client has complaint about the program consuming more timeso then what u will do? Ans.using optimization techniques we have to reduce the cost of the queries those are used in our program. 2. What is difference between truncate and delete? Ans.1. Truncate is the DDL command. Delete is the DML command. 2. Truncate should not maintain the backup. Delete maintains the backup. 3. Using Truncate single row deletion is not possible. Using Delete single row deletion is possible. 4.Truncate implicitely commit. Delete explicitely commit. 5.Rollback is not possible in truncate. Rollback is possible in delete. 3. What is difference between view and synonym? Ans. 1. We can create view for more than one table. We cant create synonym for more than one table. 2. View can be accessed by all users. But private synonym can be accessed by the user who is created that

in order

synonym. 3. We can hide the date in the base table using views. We can not hide the data in the base table using Synonym 4. What is index and what are all the different types of index? Ans. Index is a schema object that can be speed up the retrieval of rows by using pointer. Indexes are created explicitly or automatically. There are 6 types of indexes. 1.Binary index(by default). 2.Bit map index. 3.Compressed index. 4.Function based index. 5.Reversed order key index. 6.Indexed organization table.(IOT). 5. What is different between stored procedure and trigger? Ans: trigger fires automatically, but we have to explicitly call the stored procedure. 6. What is a sequence? Ans: sequence is used to generate sequential integer values. 7. Why do you use lset, mset and null set? Ans: to mark the end of string null set is used, While initializing a variable junk chars will be assigned to the variable so replace junk chars by \0 we do memset When we are entering the data into database we have to lset the variables. 8. What is a dual? Ans: dual is a virtual table which consists of one dummy column & one row. 9. How do u handle exceptions in proc? Ans: SQLCA, ORACA,WHENEVER 10. What is procedure Tell me about in and inout? ANS: it is a sub program which performs a specific task,in is used to pass values to the sub program inout is used to pass values to subprogram and returns updated values to caller of subprogram. 11. What is a function? Ans: it is a sub program which is used to return values. only in parameter is used in function. 12. What is a package? Why do u need a package? Ans. A Package is a schema object that groups logically related types,items and subprograms. Packages are having many advantages namely 1.Modularity. 2.Easier application design. 3.Information hiding. 4.Added functionality and better performance. 01) What is two phase commit? a

in order

Ans:) in a distributed database, Oracle must coordinate trAns:action control over a Network and maintain data consistency, even if a network or system failure occurs. A two-phase commit mechanism guarantees that all database servers participating in a distributed trAns:action either all commit or all roll back the statements in the trAns:action. A two-phase commit mechanism also protects implicit DML operations Performed by integrity constraints, remote procedure calls, and triggers. The Oracle two-phase commit mechanism is completely trAns:parent to users who issue distributed trAns:actions. 02) What is a soft link? Ans:) Symbolic link is a n indirect pointer to a file and its directory entries will give the name of the file it is linked. Symbolic links may span file systems and may refer to directories. 03) What is sticky byte? The sticky bit (file mode bit 01000) is used to indicate special treatment of certain files and directories. A directory for which the sticky bit is set restricts deletion of files it contains. A file in a sticky directory may only be removed or renamed by a user who has write permission on the directory, and either owns the file, owns the directory, or is the super-user. This is useful for directories such as /tmp, which must be publicly writable, but should deny users permission to arbitrarily delete or rename the files of others. 04) What is the difference between exists & IN clause? Ans. 1. EXIST is more faster. IN is not faster than EXIST. 2. EXIST returns Boolean value. IN returns a value. 05) What is 3-tier architecture in oracle? Ans. In 3 tier architecture we have 3 layers. 1.CLIENT layer. 2.MIDDLE layer. 3.SERVER layer. PART -4 -------------------------------------------------------------------------------------------------------------------------------

Questions and AnswersParallel/ 1. Difference between cursor for loop and for loop, which is faster? In for loops, the loop executes for a specified number of times whereas in a cursor for loop the results of a query are used to dynamically determine the number of times the loops is going to be executed. In a cursor for loop the opening, fetching and closing of cursors is performed implicitly, unlike normal cursors therefore it can be said that the cursor for loop is faster than normal for loop. 2. In proc and PL/SQL, which is faster? PL/SQL procedures are compiled and stored in the data dictionary. They are ready to execute. In case of Proc it has to compile every time. If you are calling a stored procedure it can be shared by N no of programs. It is not possible In case of Pro*c. If you call statements individually the application has to hit oracle for each individual Sql statement. Where as in pl/Sql all the block is transferred at a time and thus we can reduce network traffic. PL/SQL is more faster because PL/SQL directly uses the resources of Oracle

3. Which is best method to kill the process (unix or oracle)? It is better to kill the process in oracle only. Because if you kill using Unix if a query is already running in Sql engine, it will still run. Its better to kill a session rather than process. 4. Difference between c shell, bourn shell, k shell? Csh, the C shell, is a command interpreter with a syntax reminiscent of the C language. It provides a number of convenient features for interactive use that are not available with the Bourne shell, including filename completion, command aliasing, history substitution, job control, and a number of built-in commands. As with the Bourne shell, the C shell provides variable, command and filename substitution. Bourne shell is a subset of k-shell. 5. What is inode? All UNIX files have its description stored in a structure called 'inode'. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers to the data blocks of the file. If the file is large, inode has indirect pointer to a block of pointers to additional data blocks (this further aggregates for larger files). A block is typically 8k. Inode consists of the following fields: 1. File owner identifier 2. File type 3. File access permissions 4. File access times 5. Number of links 6. File size 6. How to search two patterns using grep pattern? grep -e pattern1 -e pattern2 search_list Eg: grep -e include -e scanf *.pc 7. Difference between ls and find? Find will display the full path of the file. But ls do not. We cannot find for a particular pattern recursively within subdirectories in case of ls 8. Difference between view and snapshot? View is a stored query. A snapshot is a replica of a target master table from a single point-in-time. Whereas in multi master replication tables are continuously being updated by other master sites, snapshots are updated by one or more master tables via individual batch updates, known as a refresh, from a single master site. View does not contain any data where as snapshot contain physical data. 9. Difference between function and procedure? A function must return a value A procedure may or may not return a value. 10. Why we cannot use DDL commands in procedure? a) DDL statements will do implicit commit. Its not possible to roll back if we use DDL statements. b) We cannot create a table within non-DDL statements. We call functions within SQL statements. So its not possible to use DDL statements. 11. Difference between global variable and static global variable? If we declare a global variable it can be shared by other c programs also. In case of static its not possible. If we have only one program then there is no difference.

12. How to access variable of nested procedure? It is not possible to define nested procedures. 13. If we have both user exception and system exception, which will be handled first? System exception will be handled first. Because the exception raised at runtime will first search for system exception only. 14. Difference between anonymous block and normal block? An anonymous block cannot be used else where except where it is defined. Where as its possible for named block. 15. Can we create snapshot for another schema? 16. How to access table from another database? Table_name.schema_name@databasename.-------------------------------------------------------------------------------------------------------------------------------

PART -5SQL 1. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables? Data Definition Language (DDL) 2. What operator performs pattern matching? LIKE operator 3. What operator tests column for the absence of data? IS NULL operator 4. Which command executes the contents of a specified file? START or @ 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 7. What are the wildcards used for pattern matching? _ for single character substitution and % for multi-character substitution 8. State true or false. EXISTS, SOME, ANY are operators in SQL. True 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 TRUNCATE TABLE EMP; DELETE FROM EMP; Will the outputs of the above two commands differ? Both will result in deleting all the rows in the table EMP. 14. 15. What is the difference between TRUNCATE and DELETE commands? TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE. 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. 17. What will be the output of the following query? SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL; TROUBLETHETROUBLE 18. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' ); Answer : NO Explanation : The query checks whether a given string is a numerical digit. 19. What does the following query do? SELECT SAL + NVL(COMM,0) FROM EMP; This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary. 20. Which date function is used to find the difference between two dates? MONTHS_BETWEEN 21. Why does the following command give a compilation error? DROP TABLE &TABLE_NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol. 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 25. What is the use of DESC in SQL? Answer : DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order. Explanation : The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order. 26. What is the use of CASCADE CONSTRAINTS? When this clause is used with the DROP command, a parent table can be dropped even when a child table exists. 27. Which function is used to find the largest integer less than or equal to a specific value? FLOOR 28. What is the output of the following query? SELECT TRUNC(1234.5678,-2) FROM DUAL; 120 -------------------------------------------------------------------------------------------------------------------------------

PART -6SQL SYNTAX DDL (DATA DEFINITION LANGUAGE): CREATE SYNTAX: Create table (column1 data type, column2 data type, ..) ALTER SYNTAX: Alter table < table name> add (column1 data type, column2 data type, .) Alter table < table name> modify (column name1 data type, column name2 data type, .) DROP SYNTAX: Drop table TRUNCATE SYNTAX: Truncate table DML (DATA MANIPULATION LANGUAGE): INSERT SYNTAX: Insert into values (value1, value2,.) Insert into (fields list) values (value1, value2,.)

UPDATE SYNTAX: Update set column = value Update set column = value where condition DELETE SYNTAX: Delete from Delete from where condition SELECT SYNTAX: Select filed list from Select filed list from where condition DCL (DATA CONTROL LANGUAGE): GRANT SYNTAX: Grant privileges on to Grant all on to REVOKE SYNTAX: Revoke privileges on from Revoke all on from TCL (TRANSACTION CONTROL LANGUAGE): COMMIT SYNTAX: Commit SAVE POINT SYNTAX: Save point ROLLBACK SYNTAX: Rollback FUNCTIONS: DATE: MONTHS_BETWEEN: Select months_between (date1, date2) from dual TRUNC: Select trunc (date, year/month/day) from dual ROUND: Select round (date, year/month/day) from dual ADD_MONTHS: Select add_months (date, value) from dual GREATEST: Select greatest (date1, date2) from dual CHARATER HANDLING FUNCTIONS: LTRIM: Select ltrim(string, pattern) from dual RTRIM: Select rtrim(string, pattern) from dual LPAD: Select lpad(string, total no of characters, pattern) from dual

RPAD: Select rpad(string, total no of characters, pattern) from dual LOWER: Select lower (string) from dual UPPER: Select upper (string) from dual INITCAP: Select Initcap (string) from dual CONCATENATION (||): Select string1 || string2 from dual SOUNDEX: Soundex (string) REPLACE: Replace (string, find string, replace string) TRANSLATE: Translate (string, find pattern, replace pattern) DECODE: Decode (column name, condition1, value1,.) LENGTH: Length (string) GREATEST: Greatest (string1, string2,.) NUMERIC FUNCTION: MOD: Select mod (value1,value2) from dual SQRT: Select sqrt (value) from dual TRUNC: Select trunc (m, n) from dual ABS: Select abs (value) from dual ROUND: Select round (m, n) from dual

CEIL: Select ceil (value) from dual FLOOR: Select floor (value) from dual POWER: Select power (m, n) from dual GROUPING FUNCTION: COUNT: Select count (column name) from Select count (*) from SUM: Select sum (column name) from where AVG: Select Avg (column name) from where MAX: Select max (column name) from where MIN: Select min (column name) from where GROUP BY CLAUSE: Select column name1, grouping function name (column name) from group by column name1 CONVERSION FUNCTION: TO_DATE: Select to_date (date, date format) from dual TO_CHAR: Select to_char (sysdate, date format) from dual TO_NUMBER: Select to_number (string format/100) from dual NVL: Select nvl (column name, value) from VSIZE: Select vsize (string) from dual SET OPERATORS:

UNION: Query1 union query2 INTERSECT: Query1 intersect query2 MINUS: Query1 minus query2 JOINS: SIMPLE JOIN: Select from ,< tablename2> where SELF JOIN: Select from ,< tablename1> where OUTER JOIN: (+) Select from ,< tablename2> where SUB QUERIES: Select from where = (Select from where ) CONSTRAINTS: NOT NULL: Create table (filed name1 datatype1, filed name2 datatype2 constraint constraint name not null, .) CHECK: Create table (filed name1 datatype1, filed name2 datatype2 constraint constraint name check, .) UNIQUE: Create table (filed name1 datatype1, filed name1 datatype1, constraint constraint name unique (column name), .) PRIMARY KEY: Create table (filed name1 datatype1, filed name1 datatype1, constraint constraint name primary key (column name), .) Create table (filed name1 datatype1, filed name2 datatype2 constraint constraint name primary key, .) DATA OBJECTS: SYNONYM: Create [public] synonym for SEQUENCES: Create sequence [increment by n ] [ start with n] [maxvalue n] [minvalue n] [cycle/nocycle]

[cache/nocache] VIEW: Create [or replace] view [column alias name..] as INDEX: Create index on (column name) PARTITIONING IN INDEX: Create index on (column name1, column name2) Partition by range (column name) Partition values less than (value1) tablespace Partition values less than (value2) tablespace

PART -7

1. what is the diff between call by value and call by reference? Ans: call by value passes the value of a variable ,call by reference passes the address of a variable. 2. do u know about method 4? 3. what are the parameters in procedure? Ans: in,out,inout. 4. can we modify the IN parameter ? 5. what is OUT parameter? Ans: out parameter is used to return values to the caller of a sub program. 6. suppose there are two tables with same structure, I want to display all the records in two tables using order by. Ans : select * from (select city_name, city_code from city1 union all select city_name,city_code from city2) order by city_name; 7. how to restrict a program and table to run other users while I am running? A 8. how much time does it takes to generate a report, if there are 1 lack records? Ans : depending upon the complexity of the query. 9. write a plsql block to update a record with emp_name and emp_no, if that record is not there insert into the table. Ans:declare Erec emp%rowtype Begin Select ename, eno from emp; If(sql%rowcount>0) THEN Update emp set ename=ram where sal=10000; Else Insert into emp (ename, eno) values(ram,10); End; 10.what is your role in your project? 11.how to handle core dump errors?

Ans:- using gdb and dbx Type gdb at command line. Then press enter Type r 12.how you trace core dump errors without using tools? Ans: signal handling. 13.can you create your own datatype in C? ans: hint : enumerated data types. 14.Suppose in my database 1 lack records are there, I am generating report, after generating 10,000 records the program is aborted, if I again start the program from which record it generates the report? Ans: 10,001th record. 15.How to call a procedure in proc? Ans: exec sql execute Procedure_name (host variables) End-exec; 16.how to pass parameters to a pl/sql procedure in a proc program? Ans :--- using host variables.

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

PART -8MBT Questions1. What is the 3rd Normal form A. each non key column must depend on nothing but the key. If a column depends on column that are not part of the key split those columns into new table. 2. Whats the difference between the table level constraints and row level constraints. A. The table level constraint is part of the table definition. An integrity constraint defined at table level can impose rules on any columns in the table whereas column level constraint being a part of the column definition can be imposed only on the column level on which it is defined. 3. How to store a resume in the data base. - in pdf format - in text form - at 4. Is index useful in all cases A. No 5. How to find if oracle is there in the resume stored in the data base? A. cat search. 6. Can null values be indexed? A. Yes 7. Can a view be indexed? A. No only create index for materialized view. 8. What is a cursor?

A. A cursor is handle or pointer to the context area. 9. Using the cursors how to increase the salary of employes by 15% whose salary is greater than 20,000. Declare Cursor c1 is select sal from emp where sal>20000; Sal1 emp.sal%type; Begin Open c1; loop Fetch c1 into sal1; Update emp set sal=sal+(sal1*20/100); Exit when c1%notfound; End loop; End; 10. Can you put more than one constraint to a column? A. Yes.

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

Pro*c Questions (Yalamanchili)1. How u declare a host variable? How it is use in pro*c and the difference between the indicator variable and host variable? Ans: we can declare host variable in the declare section . i.e. EXEC SQL BEGIN DECLARE SECTION; Host variable; EXEC SQL END DECLARE SECTION; Host variables are Key to communicate between your host program and Oracle. Indicator variables are variables that show status of the Host variable. 2. What is the difference between the EXEC SQL INCLUDE and #include statements? Ans: When you use EXEC SQL INCLUDE statement in your program then it includes header file at precompilation time and When you use #include statement then it includes header file at compile time. 3. What are the error handling mechanisms in pro*c? Ans: Whenever, SQLCA,oraca 4. What is a FETCH statement? How is it use?

PART -9

5. What is the ORACA?

6. What are the two components of sqlerrm? Ans: unsigned short sqlerrml, char sqlerrcmc[70]. 7. What does sqlwarn[3] depict? Ans: This flag is set if the number of columns in a query select list does not equal the number of host variables in the INTO clause of the SELECT or FETCH statement. The number of items returned is the lesser of the two. 8. What does sqlca.sqlerrd[2] depict? Ans: This component holds the number of rows processed by the most recently executed SQL statement. However, if the SQL statement failed, the value of sqlca.sqlerrd[2] is undefined.

9. What is PREPARE clause?

10. What is CURRENT OF clause? Ans: You use the CURRENT OF cursor_name clause in a DELETE or UPDATE statement to refer to the latest row FETCHed from the named cursor. The cursor must be open and positioned on a row. If no FETCH has been done or if the cursor is not open, theCURRENT OF clause results in an error and processes no rows. The FOR UPDATE OF clause is optional when you DECLARE a cursor that is referenced in the CURRENT OF clause of an UPDATE or DELETE statement. The CURRENT OF clause signals the precompiler to add a FOR UPDATE clause if necessary. When you DECLARE a cursor that is referenced in the CURRENT OF clause of an UPDATE or DELETE statement, you use the FOR UPDATE OF clause to acquire exclusive rowlocks. SELECT FOR UPDATE OF identifies the rows that will be updated or deleted, then locks each row in the active set. This is useful, for example, when you want to base an update on the existing values in a row. You must make sure the row is not changed by another user before your update. The FOR UPDATE OF clause is optional. For example, instead of coding EXEC SQL DECLARE emp_cursor CURSOR FOR SELECT ename, job, sal FROM emp WHERE deptno = 20 FOR UPDATE OF sal; you can drop the FOR UPDATE OF clause and simply code EXEC SQL DECLARE emp_cursor CURSOR FOR SELECT ename, job, sal FROM emp WHERE deptno = 20; The CURRENT OF clause signals the precompiler to add a FOR UPDATE clause if necessary. You use the CURRENT OF clause to refer to the latest row FETCHed from a cursor. Restrictions If you use the FOR UPDATE OF clause, you cannot reference multiple tables. An explicit FOR UPDATE OF or an implicit FOR UPDATE acquires exclusive row locks. All rows are locked at the OPEN, not as they are FETCHed. Row locks are released when you COMMIT or ROLLBACK (except when you ROLLBACK to a savepoint). Therefore, you cannot FETCH from a FOR UPDATE cursor after a commit. 11. If sqlca.sqlcode depicts 0 what does it indicate? Ans: Means that Oracle executed the statement without detecting an error or exception. 12.int a[25][25] is a valid host variable declaration. Justify?

13. What is the use of WHENEVER STOP?

14. What is the use of EXECUTE IMMEDIATE?

15. What does EXEC SQL COMMIT WORK RELEASE?

Some other Faqs on Pro*c About Host variable Host variables are Key to communticate between your host program and Oracle.

About Indicator variables

Indicator variables are variables which shows status of the Host variable. Every host variable is associated with optional Indicator variable. Indicator variable as 2 byte integer(short int) and it is immediately follow the host variable. Indicator value Meaning 0 Operation was Successful -1 Null was returned. -2 Output to a character host variable from a "long" type was truncated, but the original column length cannot be determined. >0 The Result of Select or Fetch into a character host variable was Truncated. About SQLCA(SQL Communication Area) The SQLCA contains the following runtime information about the outcome of SQL statements: Oracle error codes, warning flags, event information, rows-processed count diagnostics. struct sqlca { char sqlcaid[8]; long sqlabc; long sqlcode; struct { unsigned short sqlerrml; char sqlerrmc[70]; } sqlerrm; char sqlerrp[8]; long sqlerrd[6]; char sqlwarn[8]; char sqlext[8]; }; sqlcaid This string component is initialized to "SQLCA" to identify the SQL Communications Area. sqlcabc This integer component holds the length, in bytes, of the SQLCA structure. sqlcode This integer component holds the status code of the most recently executed SQL statement. The status code, which indicates the outcome of the SQL operation, can be any of the following numbers: 0 Means that Oracle executed the statement without detecting an error or exception. >0 Means that Oracle executed the statement but detected an exception. This occurs when Oracle cannot find a row that meets your WHERE-clause search condition or when a SELECT INTO or FETCH returns no rows. 10000Emp(empno,empname,salary,department) Ans: SELECT DEPTNO, COUNT (*) FROM EMP WHERE SAL>10000 GROUP BY DEPTNO

2. write a query to print the following format fromemptalble(eno,lastname,firstname,middlename) Format :- lastname,middlename firstname Conditions: if middle name is null or first name is null then there should not be blank what is the result of the statement? SELECT EMPNO,NAME,SAL FROM EMP WHERE ROWNUM > 2

3.

Ans: no rows selected

4. write a query to create the synonym for the employee tableemp(empno,empname,salary,department) Ans: CREATE PUBLIC SYNONYM SY_NAME FOR EMP;

5. write a query to create the view for the empdatails listed with the corresponding department name?Emp(empno,empname,salary,deptno) deptno(deptno,deptname) EMP B WHERE B.DNAME=SALES Ans: CREATE OR REPLACE VIEW V_NAME AS SELECT EMPNO,A.ENAME,B.DNAME FROM EMP A, AND B.DEPTNO=A.DEPTNO;

6. write the syntax for creating the sequence?Ans: CREATE SEQUENCE S_NAME INCEMENT BY integerval START WITH integerval MAXVALUE integerval MINVALUE integerval CYCLE/NOCYCLE CACHE integerval/NOCACHE ORDER/NOORDER

7. What is the difference the innerjoin and outterjoin? 8. What is the output of the following query?Select 12/12/04 from the dual 9. What is the use of commit & rollback? Ans: 10. There are tow tables named as emp1, emp2 with the same structure(empno,empname,salary,dept)? How can u copy the contents of emp1 and emp2? 11. There are two tables names as emp1,emp2 with the same structure(empno,empname,salary,dept) and how will u find the common records in emp1 and emp2? 12. How can u find the no of tables created in a user without using user_tab_columns and write the query for that? 13. What is the o/p of the following query? Select add_months(sysdate,-2) from dual; (note: sysdate is 06-may-2004) 14. What is the difference between the SQL and SQL * PLUS? 15. How can u find the constraint defined on a particular table and specify the query? 16. How to find the nth max salary of an employee table? 17. What is meant by self join? 18. Write the syntax for adding some columns named as designation, manager to an existing table(eno,ename,sal)? 19. How to create a primary key for an existing table? 20. What is the o/p of the following query? SELECT DECODE(ename,Raj,kumar,laxmi,lakshmi,sridhar) from emp; 21. What is the o/p of the following query??(note sysdate = 5-apr-2004) select next_day(sysdate,firday), last_day(sysdate) from dual; 22. What is the difference between the translate and decode statements? 23. Write a query to print the age of the employee along with employee details? Emp(eno,ename,salary,dateofbirth) 24. What is meant by database? 25. What is the difference between ROWID and ROWNUM?

PART 11Oracle SQL Test 1 Costal Tech. Sol

1. What is the Syntax for Creating a tableAns:Syntax: create table (column1 datatype, column2 datatype,..)

2. Create a table named as emp1which have the same structure as emp but it should not have the data?Anscreate table emp1 as select * from emp where 1=2

3. Employee table has 10 records with the name with the size 20. How can we alter the size of the namecolumn to 15. Note : All the name field values size is < 15 Ans: Here there is not possible to alter the column of table as decrees the size of the column data type. It is possible to increase the size of the column data type.

4. How to delete the duplicate rows in a table.Ans: delete from where rowid ( select max(rowid) from where .column = .column)

Eg1:

DELETE FROM EMP A WHERE ROWID (SELECT MAX(ROWID) FROM EMP B WHERE B.EMPNO=A.EMPNO); DELETE FROM EMP WHERE ROWID NOT IN (SELECT MAX(ROWID) FROM EMP GROUP BY EMPNO);

Eg2:

5. How a number can be printed in words? Specify the queryAns: select to_char(to_date(1234,jsp), jsp) from dual

6. How can u find the total no of columns of a tableAns: select count(*) from user_tab_columns where table_name=EMP Note: here the table_name must be the capital letters.

7. The following are the two different tables each one is having some recordsEmp(eno,ename,sal,dno) Dept(dno,dname) Write a query to print the employee details along with the department name? Ans: select e.eno,e.ename,d.dname from emp e, dept d where e.depno = d.depno

8. How can we print the alternative rows of a tableAns: select * from where mod((select count(*) from where alias_name.rowid=alias_name.rowid),2)=0 select * from comfort c where mod((select count(*) from comfort s where c.rowid