Sunteți pe pagina 1din 48

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 <filename> or @<filename> 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 14. 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. 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; 1200 Read more: http://www.ittestpapers.com/articles/question-and-answers-in-sql.html#ixzz22n94DsU5

I. SCHEMAS Table 1 : STUDIES PNAME (VARCHAR), SPLACE (VARCHAR), COURSE (VARCHAR), CCOST (NUMBER) Table 2 : SOFTWARE

PNAME (VARCHAR), TITLE (VARCHAR), DEVIN (VARCHAR), SCOST (NUMBER), DCOST (NUMBER), SOLD (NUMBER) Table 3 : PROGRAMMER PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1 (VARCHAR), PROF2 (VARCHAR), SAL (NUMBER) 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 dont 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 dont 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: 1. SELECT AVG(SCOST) FROM SOFTWARE WHERE DEVIN = 'ORACLE'; 2. SELECT PNAME,TRUNC(MONTHS_BETWEEN(SYSDATE,DOB)/12) "AGE", TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) "EXPERIENCE" FROM PROGRAMMER; 3. SELECT PNAME FROM STUDIES WHERE COURSE = 'PGDCA';

4. SELECT MAX(SOLD) FROM SOFTWARE; 5. SELECT PNAME, DOB FROM PROGRAMMER WHERE DOB LIKE '%APR%'; 6. SELECT MIN(CCOST) FROM STUDIES; 7. SELECT COUNT(*) FROM STUDIES WHERE COURSE = 'DCA'; 8. SELECT SUM(SCOST*SOLD-DCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'C'; 9. SELECT * FROM SOFTWARE WHERE PNAME = 'RAKESH'; 10. SELECT * FROM STUDIES WHERE SPLACE = 'PENTAFOUR'; 11. SELECT * FROM SOFTWARE WHERE SCOST*SOLD-DCOST > 5000; 12. SELECT CEIL(DCOST/SCOST) FROM SOFTWARE; 13. SELECT * FROM SOFTWARE WHERE SCOST*SOLD >= DCOST; 14. SELECT MAX(SCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'VB'; 15. SELECT COUNT(*) FROM SOFTWARE WHERE DEVIN = 'ORACLE'; 16. SELECT COUNT(*) FROM STUDIES WHERE SPLACE = 'PRAGATHI'; 17. SELECT COUNT(*) FROM STUDIES WHERE CCOST BETWEEN 10000 AND 15000; 18. SELECT AVG(CCOST) FROM STUDIES; 19. SELECT * FROM PROGRAMMER WHERE PROF1 = 'C' OR PROF2 = 'C'; 20. SELECT * FROM PROGRAMMER WHERE PROF1 IN ('C','PASCAL') OR PROF2 IN ('C','PASCAL'); 21. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++') AND PROF2 NOT IN ('C','C++'); 22. SELECT TRUNC(MAX(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'M'; 23. SELECT TRUNC(AVG(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'F'; 24. SELECT PNAME, TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) FROM PROGRAMMER ORDER BY PNAME DESC; 25. SELECT PNAME FROM PROGRAMMER WHERE TO_CHAR(DOB,'MON') = TO_CHAR(SYSDATE,'MON'); 26. SELECT COUNT(*) FROM PROGRAMMER WHERE SEX = 'F'; 27. SELECT DISTINCT(PROF1) FROM PROGRAMMER WHERE SEX = 'M'; 28. SELECT AVG(SAL) FROM PROGRAMMER; 29. SELECT COUNT(*) FROM PROGRAMMER WHERE SAL BETWEEN 5000 AND 7500; 30. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++','PASCAL') AND PROF2 NOT IN ('C','C++','PASCAL'); 31. SELECT PNAME,TITLE,SCOST FROM SOFTWARE WHERE SCOST IN (SELECT MAX(SCOST) FROM SOFTWARE GROUP BY PNAME); 32.SELECT 'Mr.' || PNAME || ' - has ' || TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) || ' years of experience' Programmer FROM PROGRAMMER WHERE SEX = 'M' UNION SELECT 'Ms.' || PNAME || ' - has ' || TRUNC (MONTHS_BETWEEN (SYSDATE,DOJ)/12) || ' years of experience' Programmer FROM PROGRAMMER WHERE SEX = 'F'; II . SCHEMA : Table 1 : DEPT DEPTNO (NOT NULL , NUMBER(2)), DNAME (VARCHAR2(14)),

LOC (VARCHAR2(13) Table 2 : EMP EMPNO (NOT NULL , NUMBER(4)), ENAME (VARCHAR2(10)), JOB (VARCHAR2(9)), MGR (NUMBER(4)), HIREDATE (DATE), SAL (NUMBER(7,2)), COMM (NUMBER(7,2)), DEPTNO (NUMBER(2)) 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: 1. SELECT DISTINCT(A.ENAME) FROM EMP A, EMP B WHERE A.EMPNO = B.MGR; or SELECT ENAME FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP); 2. SELECT * FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING COUNT(EMPNO)>10 AND DEPTNO=10); 3. SELECT A.ENAME "EMPLOYEE", B.ENAME "REPORTS TO" FROM EMP A, EMP B WHERE A.MGR=B.EMPNO; 4. SELECT * FROM EMP WHERE EMPNO IN ( SELECT EMPNO FROM EMP MINUS SELECT MGR FROM EMP); 5. SELECT * FROM EMP WHERE SAL > ( SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO HAVING DEPTNO=20); 6. SELECT * FROM EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP GROUP BY JOB HAVING JOB = 'MANAGER' );

7. SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB; 8. SELECT * FROM EMP WHERE (DEPTNO, HIREDATE) IN (SELECT DEPTNO, MAX(HIREDATE) FROM EMP GROUP BY DEPTNO); 9. SELECT TO_CHAR(HIREDATE,'YYYY') "YEAR", COUNT(EMPNO) "NO. OF EMPLOYEES" FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY') HAVING COUNT(EMPNO) = (SELECT MAX(COUNT(EMPNO)) FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY')); 10. SELECT DEPTNO, LPAD(SUM(12*(SAL+NVL(COMM,0))),15) "COMPENSATION" FROM EMP GROUP BY DEPTNO HAVING SUM( 12*(SAL+NVL(COMM,0))) = (SELECT MAX(SUM(12*(SAL+NVL(COMM,0)))) FROM EMP GROUP BY DEPTNO); 11. SELECT ENAME, HIREDATE, LPAD('*', "RECENTLY HIRED" FROM EMP WHERE HIREDATE = (SELECT MAX(HIREDATE) FROM EMP) UNION SELECT ENAME NAME, HIREDATE, LPAD(' ',15) "RECENTLY HIRED" FROM EMP WHERE HIREDATE != (SELECT MAX(HIREDATE) FROM EMP); 12. SELECT ENAME,SAL FROM EMP E WHERE SAL > (SELECT AVG(SAL) FROM EMP F WHERE E.DEPTNO = F.DEPTNO); 13. SELECT ENAME, SAL FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT(SAL)) FROM EMP B WHERE A.SAL<=B.SAL); 14. SELECT * FROM EMP A WHERE A.EMPNO IN (SELECT EMPNO FROM EMP GROUP BY EMPNO HAVING COUNT(EMPNO)>1) AND A.ROWID!=MIN (ROWID)); 15. SELECT ENAME "EMPLOYEE",TO_CHAR(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12))||' YEARS '|| TO_CHAR(TRUNC(MOD(MONTHS_BETWEEN (SYSDATE, HIREDATE),12)))||' MONTHS ' "LENGTH OF SERVICE" FROM EMP; Read more: http://www.ittestpapers.com/articles/test-your-sql-query-skills-withanswers.html#ixzz22n9L0Sb4

Explain an outer join?

An outer join includes rows from tables when there are no matching values in the tables.

What is a subselect? Is it different from a nested select? A subselect is a select which works in conjunction with another select. A nested select is a kind of subselect where the

inner select passes to the where criteria for the outer select.

What is the difference between group by and order by? Group by controls the presentation of the rows, order by controls the presentation of the columns for the results of the

SELECT statement.

What keyword does an SQL SELECT statement use for a string search? The LIKE keyword allows for string searches. The % sign is used as a wildcard.

What are some SQL aggregates and other built-in functions? The common aggregate, built-in functions are AVG, SUM, MIN, MAX, COUNT and DISTINCT.

How is the SUBSTR keyword used in SQL? SUBSTR is used for string manipulation with column name, first position and string length used as arguments. E.g.

SUBSTR (NAME, 1 3) refers to the first three characters in the column NAME.

Explain the EXPLAIN statement?

The explain statement provides information about the optimizer's choice of access path of the SQL.

What is referential integrity? Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every

foreign key value must have a corresponding primary key value.

What is a NULL value? What are the pros and cons of using NULLS? A NULL value takes up one byte of storage and indicates that a value is not present as opposed to a space or zero

value. It's the DB2 equivalent of TBD on an organizational chart and often correctly portrays a business situation.

Unfortunately, it requires extra coding for an application program to handle this situation.

What is a synonym? How is it used? A synonym is used to reference a table or view by another name. The other name can then be written in the

application code pointing to test tables in the development stage and to production entities when the code is migrated.

The synonym is linked to the AUTHID that created it.

What is an alias and how does it differ from a synonym? An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the location

qualifier of a table or view. The alias is not dropped when the table is dropped.

When can an insert of a new primary key value threaten referential integrity? Never. New primary key values are not a problem. However, the values of foreign key inserts must have

corresponding primary key values in their related tables. And updates of primary key values may require changes in

foreign key values to maintain referential integrity.

What is the difference between static and dynamic SQL? Static SQL is hard-coded in a program when the programmer knows the statements to be executed. For dynamic SQL

the program must dynamically allocate memory to receive the query results.

Compare a subselect to a join? Any subselect can be rewritten as a join, but not vice versa. Joins are usually more efficient as join rows can be

returned immediately, subselects require a temporary work area for inner selects results while processing the outer

select.

What is the difference between IN subselects and EXISTS subselect? If there is an index on the attributes tested an IN is more efficient since DB2 uses the index for the IN. (IN for index is

the mnemonic).

What is a Cartesian product? A Cartesian product results from a faulty query. It is a row in the results for every combination in the join tables.

What is a tuple?

A tuple is an instance of data within a relational database.

What is the difference between static and dynamic SQL? Static SQL is compiled and optimized prior to its execution; dynamic is compiled and optimized during execution.

Any SQL implementation covers data types in couple of main categories. Which of the following are those data

types ? (Check all that apply)

A). NUMERIC

B). CHARACTER

C). DATE AND TIME

D). BLOBS

E. BIT

A,B,C. Not all SQL implementations have a BLOB or a BIT data types.

We have a table with a CHARACTER data type field. We apply a ">" row comparison between this field and

another CHARACTER field in another table. What will be the results for records with field value of NULL?

(Check one that applies the best)

TRUE

B. FALSE

C. UNKNOWN

D. Error.

E. Those records will be ignored

C. NULL in a row when compared will give an UNKNOWN result.

Any database needs to go through a normalization process to make sure that data is represented only once. This

will eliminate problems with creating or destroying data in the database. The normalization process is done

usually in three steps which results in first, second and third normal forms. Which best describes the process to

obtain the third normal form? (Check one that applies the best)

Each table should have related columns.

Each separate table should have a primary key.

We have a table with multi-valued key. All columns that are dependent on only one or on some of the keys should be moved in a different table.

If a table has columns not dependent on the primary keys, they need to be moved in a separate table.

E. Primary key is always UNIQUE and NOT NULL.

D. All columns in a table should be dependent on the primary key. This will eliminate transitive dependencies in

which A depends on B, and B depends on C, but we're not sure how C depends on A.

SQL can be embedded in a host program that uses a relational database as a persistent data repository. Some of

the most important pre-defined structures for this mechanism are SQLDA ("SQL Descriptor Area") and

SQLCA ("SQL Communications Area") SQLCA contains two structures SQLCODE and SQLSTATE.

SQLSTATE is a standard set of error messages and warnings in which the first two characters defines the class

and the last three defines the subclass of the error. Which of the following SQLSTATE codes is interpreted as

"No data returned"?(Check one that applies the best)

A). 00xxx

B). 01xxx

C). 02xxx

D). 22xxx

E). 2Axxx

C. 00 - is successful completion, 01 - warnings, 22 - is data exception and 2A is syntax error. The SQLSTATE code

format returned for "No data returned" is "02xxx".

What are common SQL abend codes? (e.g. : 0,100 etc.,)

-818 time stamp mismatch

-180 wrong data moved into date field

What is meant by dynamic SQL?

Dynamic SQL are SQL statements that are prepared and executed within a program while the program is executing.

The SQL source is contained in host variables rather than being hard coded into the program. The SQL statement may

change from execution to execution.

What is meant by embedded SQL?

They are SQL statements that are embedded with in application program and are prepared during the program

preparation process before the program is executed. After it is prepared, the statement itself does not change(although

values of host variables specified within the statement might change).

Read more: http://www.ittestpapers.com/sql-interview-questions(25-50).html#ixzz22n9aXPYy

What is meant by entity integrity?

Entity integrity is when the primary key is in fact unique and not null. What will EXPLAIN do? EXPLAIN obtains information (which indexes are used, whether sorting is necessary, which level of locking is applied) about how SQL statements in the DBRM will be executed, inserting this information into the X.PLAN.TABLE where the X is the authorization ID of the owner of the plan. What is the foreign key? A foreign key is a column (or combination of columns) in a table whose values are required to match those of the primary key in some other table. What will GRANT option do? It will grant privileges to a list of one or more users. If the GRANT option is used in conjunction with the PUBLIC option, then all users will be granted privileges. Also you can grant privileges by objects and types. What does the term grant privileges mean? Grant privileges means giving access/authority to DB2 users. What is an image copy? It is an exact reproduction of all or part of a tablespace. DB2 provides utility programs to make full-image copies (to copy the entire tablespace) or incremental image copies to copy only those pages that have been modified since the last image copy. What is meant by an index? An index is a set of row identifiers (RIDs) or pointers that are logically ordered by the values of a column that has been specified as being an index. Indexes provide faster access to data and can enforce uniqueness on the row in a table. What is an index key? It is a column or set of columns in a table used to determine the order of index entries. What is a join? A join is a relational operation that allows retrieval of data from two or more tables based on matching columns values. What is meant by locking? Locking is a process that is used to ensure data integrity. It also prevents concurrent users from accessing inconsistent data. The data (row) is locked until a commit is executed to release the updated data.

What is meant by null? This is a special value that indicates the absence of data in a column. This value is indicated by a negative value, usually -1. What is an object? An object is anything that is managed by DB2 (that is databases, table spaces, tables, views, indexes or synonyms), but not the data itself. Describe referential integrity? Referential integrity refers to a feature in DB2 that is used to ensure consistency of the data in the database. Describe a primary key? A primary key is a key that is unique, non-null, and is part of the definition of a table. A table must have a primary key to be defined as a parent. How would you find out the total number of rows in a table? - GS Use SELECT COUNT(*) ... How do you eliminate duplicate values in SELECT? - GS Use SELECT DISTINCT ... How do you select a row using indexes? - GS Specify the indexed columns in the WHERE clause. What are aggregate functions? Bulit-in mathematical functions for use in SELECT clause. How do you find the maximum value in a column? - GS Use SELECT MAX(... Can you use MAX on a CHAR column? YES. My SQL statement SELECT AVG(SALARY) FROM EMP-TABLE yields inaccurate results. Why? Because SALARY is not declared to have Nulls and the employees for whom the salary is not known are also counted. How do you retrieve the first 5 characters of FIRSTNAME column of EMP table? SELECT SUBSTR(FIRSTNAME,1,5) FROM EMP; How do you concatenate the FIRSTNAME and LASTNAME from EMP table to give a complete name?

SELECT FIRSTNAME || ' ' || LASTNAME FROM EMP; What is the use of VALUE function? Avoid negative SQLCODEs by handling nulls and zeroes in computations. Substitute a numeric value for any nulls used in computation. What is UNION,UNION ALL? - GS UNION eliminates duplicates UNION ALL: retains duplicates Both these are used to combine the results of different SELECT statements.
Read more: http://www.ittestpapers.com/articles/sql-interview-questions-%285075%29.html#ixzz22nA5At51

Suppose I have five SQL SELECT statements connected by UNION/UNION ALL, how many times should I specify UNION to eliminate the duplicate rows? - GS Once. What is the restriction on using UNION in embedded SQL? It has to be in a CURSOR. In the WHERE clause what is BETWEEN and IN? - GS BETWEEN supplies a range of values while IN supplies a list of values. Is BETWEEN inclusive of the range values specified? - GS Yes. What is 'LIKE' used for in WHERE clause? What are the wildcard characters? - GS LIKE is used for partial string matches. '%' ( for a string of any character ) and '_' (for any single character ) are the two wild card characters. When do you use a LIKE statement? To do partial search e.g. to search employee by name, you need not specify the complete name; using LIKE, you can search for partial string matches. What is the meaning of underscore ( '_' ) in the LIKE statement? - GS Match for any single character. What do you accomplish by GROUP BY ... HAVING clause? - GS GROUP BY partitions the selected rows on the distinct values of the column on which you group by. HAVING selects GROUPs which match the criteria specified Consider the employee table with column PROJECT nullable. How can you get a list of employees who are not assigned to any project?

SELECT EMPNO FROM EMP WHERE PROJECT IS NULL; What is the result of this query if no rows are selected: SELECT SUM(SALARY) FROM EMP WHERE QUAL='MSC'; NULL Why SELECT * is not preferred in embedded SQL programs? For three reasons: If the table structure is changed (a field is added), the program will have to be modified Program might retrieve the columns which it might not use, leading on I/O over head. The chance of an index only scan is lost. What are correlated subqueries? - GS A subquery in which the inner ( nested ) query refers back to the table in the outer query. Correlated subqueries must be evaluated for each qualified row of the outer query that is referred to. What is a cursor? Why should it be used? - GS Cursor is a programming device that allows the SELECT to find a set of rows but return them one at a time. Cursor should be used because the host language can deal with only one row at a time. How would you retrieve rows from a DB2 table in embedded SQL? - GS Either by using the single row SELECT statements,or by using the CURSOR. Apart from cursor, what other ways are available to you to retrieve a row from a table in embedded SQL? - GS Single row SELECTs. How do you specify and use a cursor in a COBOL program? - GS Use DECLARE CURSOR statement either in working storage or in procedure division (before open cursor), to specify the SELECT statement. Then use OPEN, FETCH rows in a loop and finally CLOSE. What happens when you say OPEN CURSOR? If there is an ORDER BY clause, rows are fetched, sorted and made available for the FETCH statement. Other wise simply the cursor is placed on the first row. Is DECLARE CURSOR executable? No. Can you have more than one cursor open at any one time in a program ? GS Yes.

When you COMMIT, is the cursor closed? Yes.


Read more: http://www.ittestpapers.com/articles/sql-interview-questions-(7595).html#ixzz22nAJhGxs

SQL - Definitions (Notes)


Written By: Rajindar Reddy 6-6-2007 Categorized in: SQL/PLSQL/Oracle

Structured Query Language (SQL) provides the ability to create and define relational database objects. After these objects are defined, the language permits one to add data to these objects. Once data has been added, one can modify, retrieve, or delete that data. The language provides the capability of defining what type of authority one might have when accessing the data. Data Definition Language As the name implies, there is a group of SQL statements that allows one to define the relational structures that will manage the data placed in them. The CREATE statements brings Relational Database Management System (RDMS) objects into existence. The types of objects one can create are STOGROUP, Database, Table space, Table, Index, View, Synonym, and Alias. The definitions of these objects are as follows: STOGROUP: A storage group is a list of disk volume names to which one can assign a name. One defines the list of disk volumes and assigns the STOGROUP name with the Create STOGROUP statement. Database: A database is a logical structure in which tables and indexes are later created. The database is defined and associated with a STOGROUP with a Create Database statement. Tablespace: A tablespace is an area on disk that is allocated and formatted by the Create Table space statement. Table: A table is an organizational structure which is defined in a Create Table statement. In this statement, the data attributes are defined by column, giving each column its own unique name within the table. Index: A index is used in conjuction with the Primary Key parameter of the Create Table statement. It is made with the Create Index statement and provides the duplicate record-checking necessary for a unique key. View: A view is an alternative perspective of the data present in a database. It is made with the Create View statement and can represent a subset of the columns defined in a table. It can also represents a set of columns combined from more than one table. Synonym: The Create Synonym statement defines an unqualified name for a table or a view.

Alias: The Create Alias statement defines an alternate qualified name for a table or a view. After a table is created, additional columns may be added with an Alter Table statement. Any RDMS object that was made with a create statement can be removed with a drop statement. In order to define RDMS objects, one needs various levels of authority. The following is a list of authority levels that can be granted to a user ID to operate on a designated database. DBADM Database administrator authority DBCTRL Database control authority DBMAINT Database maintenance authority CREATETS Create Table space Authority CREATETAB Create Table authority DROP Drop authority on a database or subordinate objects Data Manipulation Language There are four SQL data manipulation statements(DML) available: Insert, Select, Update, and Delete. After tables are defined, they are ready to store data. Data is added to tables through the SQL Insert statement. Once data has been inserted into a table, it can be retrieved by the use of the Select statement. Data stored in a table can be modified by executing the SQL Update statement. Data can be deleted from a table by using the SQL Delete statement. The SQL statements perform RDMS operations that can affect only one row at a time if desired. The same statements can, if required, affect many or all of the rows in a table. It is possible to select one row and insert it into another with one statement. It is also just as easy to select all of the rows from one table and insert all of them into another with a single statement. The same scope of operation applied to the update and delete statements. The scope of operation is controlled by the use of the WHERE clause. The operation will affect only the rows that satisfy the search condition. When no search condition specified, the entire table is affected. There are additional language elements available that provide the ability to process the table data while it is being retrieved. In addition, there are a variety of functions that modify the value of the data that is returned in a query. There are column functions that act on all of the values of the selected rows for a specified column and return a single answer. There are also scalar functions that return a specific answer for each row that satisfies the search condition. As mentioned previously, SQL provides the ability to filter what data is retrieved in a select statement by including the WHERE clause. The WHERE clause specifies a variety of comparisons between two values. The values could be column values or the result of an operation involving more than one column or a constant. The comparison operation are the same as those used

in COBOL, with the exception of two additional operators. The first is the IN operator that compares a single value has a match in the specified list of values. The other is the LIKE operator, in which you can specify a value string that includes wildcard characters in such a manner that you can select rows of a table where column values are similar to the extent you require. SQL provides four arithmetic operations : addition, subtraction, multiplication, and division. An arithmetic expression may involve any combination of column name or numbers. The arithmetic expression may itself be used as a column name or in a Select, Insert, Update, or Delete statement. SQL provides the ability to sort the data retrieved from a table via the ORDER BY clause. In this clause, you can specify one or more sort column names as well as if each sort key is ascending or descending. SQL also provides the ability to perform set manipulation operations. Using SQL, one can SELECT the intersection of two or more sets of data by coding a JOIN. A JOIN is any SELECT statement that has more than one DBMS object listed in its FROM clause. One can combine different sets of data by using the UNION operator. Other set manipulations can be executed by combining different operators and search conditions.
Read more: http://www.ittestpapers.com/articles/sql---definitions-(notes).html#ixzz22nAYHHKm

What RDMS objects are required before you can create a table? Before you can create a table, you need an existing database and tablespace. In what RDMS object does one first list column names? One first uses the column name in the CREATE TABLE statement. What is the syntax for a CREATE TABLE statement? CREATE TABLE table name (column name list primary key (column name)) in database-name, tablespace-name. Can one add columns to a table after it has been defined? Yes, one can add column to a table after it has been defined by using the SQL ALTER TABLE statement. Where in a table are added columns located? The new columns are added to the end of the table. After a table is defined, can columns be removed? The only way to remove columns from an existing table involves a migration program that extracts only the desired columns of data, redefining the table without the unwanted columns, then populating the new table. One have to handle all the old tables dependents programmatically.

Which RDMS objects can you change with the SQL ALTER statements? The SQL ALTER statement can change a table index, a table, a tablespace, or a STOGROUP. What authority is required to create a table? In order to create tables, one needs CREATETAB privileges. What is minimum authority required for one to create a tablespace? In order to create tablespaces, one needs CREATETS privileges. When is it necessary to create a table index? It is necessary to create a table index whenever you want to enforce the uniqueness of the tables primary key. What is a synonym? A synonym is an unqualified alternative name for a table or view. What is a foreign key? A foreign key is the key defined in one table to reference the primary key of a reference table. This foreign key must have the same structure as the reference tables primary key. What is referential integrity? Referential integrity is the automatic enforcement of referential constraints that exist between a reference table and a referencing table. When referential integrity is enforced, the value of a foreign key exists as a primary key value in the reference table. In other words, when referential integrity is enforced, all of the foreign key values in, for example, the department code column in an employee table exist as primary key values in a department table. What are the column name qualifiers? A column name qualifier are used as a table designator to avoid ambiguity when the column names referenced exists in more than one table used in the SQL statement. Column name qualifiers are also used in correlated references. What is a correlation name? A correlation name is a special type of column designator that connects specific columns in the various levels of a multilevel SQL query. What is a results table? A result table is the product of a query against one or more tables or views (i.e., it is the place that holds the results of a query). What is a cursor? A cursor is a named control structure used to make a set of rows available to a program. DB2 is the relational database

system that runs in an MVS environment. It was developed by IBM and interfaces with SQL. With the use of SQL DB2, databases can be accessed by a wide range of host languages. SQL is the relational database " application language " that interfaces with DB2. Because of its capabilities, SQL and, in turn, DB2 have gained considerable acceptance. Thus, a working knowledge of DB2 increases one's marketability. What is the basic difference between a join and a union? A join selects columns from 2 or more tables. A union selects rows. What is normalization and what are the five normal forms? Normalization is a design procedure for representing data in tabular format. The five normal forms are progressive rules to represent the data with minimal redundancy. What are foreign keys? These are attributes of one table that have matching values in a primary key in another table, allowing for relationships between tables.

Describe the elements of the SELECT query syntax?

SELECT element FROM table WHERE conditional statement.


Explain the use of the WHERE clause?

WHERE is used with a relational statement to isolate the object element or row.
What techniques are used to retrieve data from more than one table in a single SQL statement?

Joins, unions and nested selects are used to retrieve data.


What is a view? Why use it?

A view is a virtual table made up of data from base tables and other views, but not stored separately.
Read more: http://www.ittestpapers.com/articles/sql-interview-questions.html#ixzz22nArtFPg

ORACLE QUESTIONS
What are the Back ground processes in Oracle and what are they? This is one of the most frequently asked question. There are basically 9 Processes but in a general system we need to mention the first five background processes. They do the house keeping activities for the Oracle and are common in any system. The various background processes in oracle are a) Data Base Writer (DBWR): Data Base Writer Writes Modified blocks from Database buffer cache to Data Files. This is required since the data is not written whenever a transaction is committed.

b)LogWriter (LGWR) : LogWriter writes the redo log entries to disk. Redo Log data is generated in redo log buffer of SGA. As transaction commits and log buffer fills, LGWR writes log entries into a online redo log file. c) System Monitor(SMON) : The System Monitor performs instance recovery at instance startup. This is useful for recovery from system failure d)Process Monitor(PMON) : The Process Monitor performs process recovery when user Process fails. Pmon Clears and Frees resources that process was using. e) CheckPoint(CKPT) : At Specified times, all modified database buffers in SGA are written to data files by DBWR at Checkpoints and Updating all data files and control files of database to indicate the most recent checkpoint f)Archieves(ARCH) : The Archiver copies online redo log files to archival storal when they are busy. g) Recoveror(RECO) : The Recoveror is used to resolve the distributed transaction in network h) Dispatcher (Dnnn) : The Dispatcher is useful in Multi Threaded Architecture i) Lckn : We can have upto 10 lock processes for inter instance locking in parallel sql. How many types of Sql Statements are there in Oracle? There are basically 6 types of sql statements. They are a) Data Definition Language (DDL): The DDL statements define and maintain objects and drop objects. b) Data Manipulation Language (DML): The DML statements manipulate database data. c) Transaction Control Statements : Manage change by DML d) Session Control : Used to control the properties of current session enabling and disabling roles and changing .e.g : Alter Statements, Set Role e) System Control Statements : Change Properties of Oracle Instance .e.g: Alter System f) Embedded Sql : Incorporate DDL, DML and T.C.S in Programming Language. e.g: Using the Sql Statements in languages such as 'C', Open, Fetch, execute and close What is a Transaction in Oracle? A transaction is a Logical unit of work that compromises one or more SQL Statements executed by a single User. According to ANSI, a transaction begins with first executable statement and ends when it is explicitly committed or rolled back. List some Key Words Used in Oracle. The Key words that are used in Oracle are a) Committing: A transaction is said to be committed when the transaction makes permanent changes resulting from the SQL statements. b) Rollback A transaction that retracts any of the changes resulting from SQL statements in Transaction. c) SavePoint : For long transactions that contain many SQL statements, intermediate markers or savepoints are declared. Savepoints can be used to divide a transaction into smaller points. d) Rolling Forward : Process of applying redo log during recovery is called rolling forward. e) Cursor : A cursor is a handle ( name or a pointer) for the memory associated with a specific statement. A cursor is basically an area allocated by Oracle for executing

the Sql Statement. Oracle uses an implicit cursor statement for Single row query and Uses Explicit cursor for a multi row query. f) System Global Area (SGA): The SGA is a shared memory region allocated by the Oracle that contains Data and control information for one Oracle Instance. It consists of Database Buffer Cache and Redo log Buffer. g) Program Global Area (PGA): The PGA is a memory buffer that contains data and control information for server process. g) Database Buffer Cache: Database Buffer of SGA stores the most recently used blocks of database data. The set of database buffers in an instance is called Database Buffer Cache. h) Redo log Buffer: Redo log Buffer of SGA stores all the redo log entries. i) Redo Log Files: Redo log files are set of files that protect altered database data in memory that has not been written to Data Files. They are basically used for backup when a database crashes. j) Process : A Process is a 'thread of control' or mechanism in Operating System that executes series of steps. What are Procedure, functions and Packages? Procedures and functions consist of set of PL/SQL statements that are grouped together as a unit to solve a specific problem or perform set of related tasks. Procedures do not Return values while Functions return one One Value Packages: Packages Provide a method of encapsulating and storing related procedures, functions, variables and other Package Content What are Database Triggers and Stored Procedures? Database Triggers : Database Triggers are Procedures that are automatically executed as a result of insert in, update to, or delete from table. Database triggers have the values old and new to denote the old value in the table before it is deleted and the new indicated the new value that will be used. DT are useful for implementing complex business rules which cannot be enforced using the integrity rules. We can have the trigger as Before trigger or After Trigger and at Statement or Row level. e.g: operations insert, update ,delete 3 before ,after 3*2 A total of 6 combinations At statement level (once for the trigger) or row level( for every execution ) 6 * 2 A total of 12. Thus a total of 12 combinations are there and the restriction of usage of 12 triggers has been lifted from Oracle 7.3 Onwards. Stored Procedures : Stored Procedures are Procedures that are stored in Compiled form in the database. The advantage of using the stored procedures is that many users can use the same procedure in compiled and ready to use format. How many Integrity Rules are there and what are they? There are Three Integrity Rules. They are as follows : a) Entity Integrity Rule : The Entity Integrity Rule enforces that the Primary key cannot be Null b) Foreign Key Integrity Rule : The FKIR denotes that the relationship between the foreign key and the primary key has to be enforced. When there is data in Child Tables the Master tables cannot be deleted. c) Business Integrity Rules : The Third Integrity rule is about the complex business processes which cannot be implemented by the above 2 rules.

What are the Various Master and Detail Relation ships? The various Master and Detail Relationship are a) NonIsolated : The Master cannot be deleted when a child is existing b) Isolated : The Master can be deleted when the child is existing c) Cascading : The child gets deleted when the Master is deleted. What are the Various Block Coordination Properties? The various Block Coordination Properties are a) Immediate Default Setting. The Detail records are shown when the Master Record are shown. b) Deferred with Auto Query Oracle Forms defer fetching the detail records until the operator navigates to the detail block. c) Deferred with No Auto Query The operator must navigate to the detail block and explicitly execute a query What are the Different Optimization Techniques? The Various Optimization techniques are a) Execute Plan : we can see the plan of the query and change it accordingly based on the indexes b) Optimizer_hint : set_item_property('DeptBlock',OPTIMIZER_HINT,'FIRST_ROWS'); Select /*+ First_Rows */ Deptno,Dname,Loc,Rowid from dept where (Deptno > 25) c) Optimize_Sql : By setting the Optimize_Sql = No, Oracle Forms assigns a single cursor for all SQL statements. This slow downs the processing because for evertime the SQL must be parsed whenever they are executed. f45run module = my_firstform userid = scott/tiger optimize_sql = No d) Optimize_Tp : By setting the Optimize_Tp= No, Oracle Forms assigns separate cursor only for each query SELECT statement. All other SQL statements reuse the cursor. f45run module = my_firstform userid = scott/tiger optimize_Tp = No How do u implement the If statement in the Select Statement? We can implement the if statement in the select statement by using the Decode statement. e.g select DECODE (EMP_CAT,'1','First','2','Second'Null); Here the Null is the else statement where null is done . How many types of Exceptions are there? There are 2 types of exceptions. They are a) System Exceptions e.g. When no_data_found, When too_many_rows b) User Defined Exceptions e.g. My_exception exception When My_exception then

What are the inline and the precompiler directives? The inline and precompiler directives detect the values directly How do you use the same lov for 2 columns? We can use the same lov for 2 columns by passing the return values in global values and using the global values in the code How many minimum groups are required for a matrix report? The minimum number of groups in matrix report are 4 What is the difference between static and dynamic lov? The static lov contains the predetermined values while the dynamic lov contains values that come at run time What are snap shots and views? Snapshots are mirror or replicas of tables. Views are built using the columns from one or more tables. The Single Table View can be updated but the view with multi table cannot be updated What are the OOPS concepts in Oracle? Oracle does implement the OOPS concepts. The best example is the Property Classes. We can categorize the properties by setting the visual attributes and then attach the property classes for the objects. OOPS supports the concepts of objects and classes and we can consider the property classes as classes and the items as objects Privileges and Grants Privileges are the right to execute a particular type of SQL statements. e.g : Right to Connect, Right to create, Right to resource Grants are given to the objects so that the object might be accessed accordingly. The grant has to be given by the owner of the object. What is the difference between candidate key, unique key and primary key? Candidate keys are the columns in the table that could be the primary keys and the primary key is the key that has been selected to identify the rows. Unique key is also useful for identifying the distinct rows in the table. What is concurrency? Concurrency is allowing simultaneous access of same data by different users. Locks useful for accessing the database are a) Exclusive The exclusive lock is useful for locking the row when an insert, update or delete is being done. This lock should not be applied when we do only select from the row. b) Share lock We can do the table as Share_Lock as many share_locks can be put on the same resource.

Table Space, Data Files, Parameter File, Control Files Table Space : The table space is useful for storing the data in the database. When a database is created two table spaces are created. a) System Table space : This data file stores all the tables related to the system and dba tables b) User Table space : This data file stores all the user related tables We should have separate table spaces for storing the tables and indexes so that the access is fast. Data Files : Every Oracle Data Base has one or more physical data files. They store the data for the database. Every datafile is associated with only one database. Once the Data file is created the size cannot change. To increase the size of the database to store more data we have to add data file. Parameter Files : Parameter file is needed to start an instance. A parameter file contains the list of instance configuration parameters e.g.: db_block_buffers = 500 db_name = ORA7 db_domain = u.s.acme lang Control Files : Control files record the physical structure of the data files and redo log files They contain the Db name, name and location of dbs, data files ,redo log files and time stamp. What is Row Chaining? The data of a row in a table may not be able to fit the same data block. Data for row is stored in a chain of data blocks . What are the Pct Free and Pct Used? Pct Free is used to denote the percentage of the free space that is to be left when creating a table. Similarly Pct Used is used to denote the percentage of the used space that is to be used when creating a table eg.: Pctfree 20, Pctused 40 Physical Storage of the Data The finest level of granularity of the data base are the data blocks. Data Block : One Data Block correspond to specific number of physical database space Extent : Extent is the number of specific number of contiguous data blocks. Segments : Set of Extents allocated for Extents. There are three types of Segments a) Data Segment : Non Clustered Table has data segment data of every table is stored in cluster data segment b) Index Segment : Each Index has index segment that stores data c) Roll Back Segment : Temporarily store 'undo' information
Read more: http://www.ittestpapers.com/articles/oracle-interview-questions---part1.html#ixzz22nBNEovq

Oracle Interview Questions- Part 2


Written By: Admin Admin

5-12-2009 Categorized in: SQL/PLSQL/Oracle

What is a 2 Phase Commit? Two Phase commit is used in distributed data base systems. This is useful to maintain the integrity of the database so that all the users see the same values. It contains DML statements or Remote Procedural calls that reference a remote object. There are basically 2 phases in a 2 phase commit. a) Prepare Phase : Global coordinator asks participants to prepare b) Commit Phase : Commit all participants to coordinator to Prepared, Read only or abort Reply What is the difference between deleting and truncating of tables? Deleting a table will not remove the rows from the table but entry is there in the database dictionary and it can be retrieved But truncating a table deletes it completely and it cannot be retrieved. What are mutating tables? When a table is in state of transition it is said to be mutating. eg : If a row has been deleted then the table is said to be mutating and no operations can be done on the table except select. What are Codd Rules? Codd Rules describe the ideal nature of a RDBMS. No RDBMS satisfies all the 12 codd rules and Oracle Satisfies 11 of the 12 rules and is the only Rdbms to satisfy the maximum number of rules. What is Normalisation? Normalisation is the process of organising the tables to remove the redundancy.There are mainly 5 Normalisation rules. a) 1 Normal Form : A table is said to be in 1st Normal Form when the attributes are atomic b) 2 Normal Form : A table is said to be in 2nd Normal Form when all the candidate keys are dependant on the primary key c) 3rd Normal Form : A table is said to be third Normal form when it is not dependant transitively What is the Difference between a post query and a pre query? A post query will fire for every row that is fetched but the pre query will fire only once. Deleting the Duplicate rows in the table? We can delete the duplicate rows in the table by using the Rowid

Can U disable database trigger? How? Yes. With respect to table ALTER TABLE TABLE [[ DISABLE all_trigger ]] What is pseudo columns ? Name them? A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns, but you cannot insert, update, or delete their values. This section describes these pseudocolumns: * CURRVAL * NEXTVAL * LEVEL * ROWID * ROWNUM How many columns can table have? The number of columns in a table can range from 1 to 254. Is space acquired in blocks or extents ? In extents . what is clustered index? In an indexed cluster, rows are stored together based on their cluster key values . Can not applied for HASH. what are the datatypes supported By oracle (INTERNAL)? Varchar2, Number,Char , MLSLABEL. What are attributes of cursor? %FOUND , %NOTFOUND , %ISOPEN,%ROWCOUNT Can you use select in FROM clause of SQL select ? Yes. What are the various types of Exceptions ? User defined and Predefined Exceptions. Can we define exceptions twice in same block ? No. What is the difference between a procedure and a function ? Functions return a single variable by value whereas procedures do not return any

variable by value. Rather they return multiple variables by passing variables by reference through their OUT parameter. Can you have two functions with the same name in a PL/SQL block ? Yes. Can you have two stored functions with the same name ? Yes. Can you call a stored function in the constraint of a table ? No What are the various types of parameter modes in a procedure ? IN, OUT AND INOUT. What is Over Loading and what are its restrictions ? OverLoading means an object performing different functions depending upon the no. of parameters or the data type of the parameters passed to it. Can functions be overloaded ? Yes. Can 2 functions have same name & input parameters but differ only by return datatype No.

What are the constructs of a procedure, function or a package ? The constructs of a procedure, function or a package are : variables and constants cursors exceptions

Why Create or Replace and not Drop and recreate procedures ? So that Grants are not dropped. Can you pass parameters in packages ? How ? Yes. You can pass parameters to procedures or functions in a package. What are the parts of a database trigger ? The parts of a trigger are: A triggering event or statement A trigger restriction A trigger action

What are the various types of database triggers ? There are 12 types of triggers, they are combination of : Insert, Delete and Update Triggers. Before and After Triggers. Row and Statement Triggers. (3*2*2=12) What is the advantage of a stored procedure over a database trigger ? We have control over the firing of a stored procedure but we have no control over the firing of a trigger. What is the maximum no. of statements that can be specified in a trigger statement?

One.
Can views be specified in a trigger statement ? No What are the values of :new and :old in Insert/Delete/Update Triggers ? INSERT : new = new value, old = NULL DELETE : new = NULL, old = old value UPDATE : new = new value, old = old value

What are cascading triggers? What is the maximum no of cascading triggers at a time? When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading. Max = 32. What are mutating triggers ? A trigger giving a SELECT on the table on which the trigger is written. What are constraining triggers ? A trigger giving an Insert/Updat e on a table having referential integrity constraint on the triggering table. Describe Oracle database's physical and logical structure ? Physical : Data files, Redo Log files, Control file. Logical : Tables, Views, Tablespaces, etc. Can you increase the size of a tablespace ? How ? Yes, by adding datafiles to it. Can you increase the size of datafiles ? How ? No (for Oracle 7.0) Yes (for Oracle 7.3 by using the Resize clause ----- Confirm !!). What is the use of Control files ? Contains pointers to locations of various data files, redo log files, etc.

What is the use of Data Dictionary ? Used by Oracle to store information about various physical and logical Oracle structures e.g. Tables, Tablespaces, datafiles, et What are the advantages of clusters ? Access time reduced for joins.

What are the disadvantages of clusters ? The time for Insert increases.

Can Long/Long RAW be clustered ? No. Can null keys be entered in cluster index, normal index ? Yes. Can Check constraint be used for self referential integrity ? How ? Yes. In the CHECK condition for a column of a table, we can reference some other column of the same table and thus enforce self referential integrity. What are the min. extents allocated to a rollback extent ? Two What are the states of a rollback segment ? What is the difference between partly available and needs recovery ? The various states of a rollback segment are : ONLINE, OFFLINE, PARTLY AVAILABLE, NEEDS RECOVERY and INVALID. What is the difference between unique key and primary key ? Unique key can be null; Primary key cannot be null. An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ? No. Can you define multiple savepoints ? Yes. Can you Rollback to any savepoint ? Yes. What is the maximum no. of columns a table can have ? 254. What is the significance of the & and && operators in PL SQL ? The & operator means that the PL SQL block requires user input for a variable. The && operator means that the value of this variable should be the same as inputted by the user previously for this same variable. If a transaction is very large, and the rollback segment is not able to hold the

rollback information, then will the transaction span across different rollback segments or will it terminate ? It will terminate (Please check ). Can you pass a parameter to a cursor ? Explicit cursors can take parameters, as the example below shows. A cursor parameter can appear in a query wherever a constant can appear. CURSOR c1 (median IN NUMBER) IS SELECT job, ename FROM emp WHERE sal > median; What are the various types of RollBack Segments ? Public Available to all instances Private Available to specific instance Can you use %RowCount as a parameter to a cursor ? Yes Is the query below allowed : Select sal, ename Into x From emp Where ename = 'KING' (Where x is a record of Number(4) and Char(15)) Yes Is the assignment given below allowed : ABC = PQR (Where ABC and PQR are records) Yes Is this for loop allowed : For x in &Start..&End Loop Yes How many rows will the following SQL return : Select * from emp Where rownum < 10; 9 rows
Read more: http://www.ittestpapers.com/articles/oracle-interview-questions--part2.html#ixzz22nBUAZz0

Oracle Interview Questions - Part 3


Written By: Admin Admin 5-12-2009 Categorized in: SQL/PLSQL/Oracle

How many rows will the following SQL return : Select * from emp Where rownum = 10; No rows Which symbol preceeds the path to the table in the remote database ? @

Are views automatically updated when base tables are updated ? Yes Can a trigger written for a view ? No If all the values from a cursor have been fetched and another fetch is issued, the output will be : error, last record or first record ? Last Record A table has the following data : [[5, Null, 10]]. What will the average function return ? 7.5 Is Sysdate a system variable or a system function? System Function Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference we get the next number 2. Suppose at this point we issue an rollback and again issue a nextval. What will the output be ? Definition of relational DataBase by Dr. Codd (IBM)? A Relational Database is a database where all data visible to the user is organized strictly as tables of data values and where all database operations work on these tables. What is Multi Threaded Server (MTA) ? In a Single Threaded Architecture (or a dedicated server configuration) the database manager creates a separate process for each database user. But in MTA the database manager can assign multiple users (multiple user processes) to a single dispatcher (server process), a controlling process that queues request for work thus reducing the databases memory requirement and resources. Which are initial RDBMS, Hierarchical & N/w database ? RDBMS - R system Hierarchical - IMS N/W - DBTG Difference between Oracle 6 and Oracle 7 ORACLE 7 ORACLE 6 Cost based optimizer ? Rule based optimizer Shared SQL Area ? SQL area allocated for each user Multi Threaded Server ? Single Threaded Server Hash Clusters ? Only B-Tree indexing Roll back Size Adjustment ? No provision Truncate command ? No provision Database Integrity Constraints ? Provision at Application Level Stored procedures, functions

packages & triggers ? No provision Resource profile limit. It prevents user from running away with system resources ? No provision Distributed Database ? Distributed Query Table replication & snapshots? No provision Client/Server Tech. ? No provision What is Functional Dependency Given a relation R, attribute Y of R is functionally dependent on attribute X of R if and only if each X-value has associated with it precisely one -Y value in R

What is Auditing ? The database has the ability to audit all actions that take place within it. a) Login attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL) or Least(1,NULL) NULL While designing in client/server what are the 2 imp. things to be considered ? Network Overhead (traffic), Speed and Load of client server What are the disadvantages of SQL ? Disadvantages of SQL are : ? Cannot drop a field ? Cannot rename a field ? Cannot manage memory ? Procedural Language option not provided ? Index on view or index on index not provided ? View updation problem When to create indexes ? To be created when table is queried for less than 2% or 4% to 25% of the table rows. How can you avoid indexes ? TO make index access path unavailable ? Use FULL hint to optimizer for full table scan ? Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes instead of another. ? Use an expression in the Where Clause of the SQL. What is the result of the following SQL : Select 1 from dual UNION

Select 'A' from dual; Error Can database trigger written on synonym of a table and if it can be then what would be the effect if original table is accessed. Yes, database trigger would fire. Can you alter synonym of view or view ? No Can you create index on view No. What is the difference between a view and a synonym ? Synonym is just a second name of table used for multiple link of database. View can be created with many tables, and with virtual columns and with conditions. But synonym can be on view. What is the difference between alias and synonym ? Alias is temporary and used with one query. Synonym is permanent and not used as alias. What is the effect of synonym and table name used in same Select statement ? Valid What's the length of SQL integer ? 32 bit length What is the difference between foreign key and reference key ? Foreign key is the key i.e. attribute which refers to another table primary key. Reference key is the primary key of table referred by another table. Can dual table be deleted, dropped or altered or updated or inserted ? Yes If content of dual is updated to some value computation takes place or not ? Yes If any other table same as dual is created would it act similar to dual? Yes For which relational operators in where clause, index is not used ? <> , like '% ...' is NOT functions, field +constant, field || ''

Assume that there are multiple databases running on one machine. How can you switch from one to another ? Changing the ORACLE_SID What are the advantages of Oracle ? Portability : Oracle is ported to more platforms than any of its competitors, running on more than 100 hardware platforms and 20 networking protocols. Market Presence : Oracle is by far the largest RDBMS vendor and spends more on R & D than most of its competitors earn in total revenue. This market clout means that you are unlikely to be left in the lurch by Oracle and there are always lots of third party interfaces available. Backup and Recovery : Oracle provides industrial strength support for on-line backup and recovery and good software fault tolerence to disk failure. You can also do pointin-time recovery. Performance : Speed of a 'tuned' Oracle Database and application is quite good, even with large databases. Oracle can manage > 100GB databases. Multiple database support : Oracle has a superior ability to manage multiple databases within the same transaction using a two-phase commit protocol. What is a forward declaration ? What is its use ? PL/SQL requires that you declare an identifier before using it. Therefore, you must declare a subprogram before calling it. This declaration at the start of a subprogram is called forward declaration. A forward declaration consists of a subprogram specification terminated by a semicolon. What are actual and formal parameters ? Actual Parameters : Subprograms pass information using parameters. The variables or expressions referenced in the parameter list of a subprogram call are actual parameters. For example, the following procedure call lists two actual parameters named emp_num and amount: Eg. raise_salary(emp_num, amount); Formal Parameters : The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters. For example, the following procedure declares two formal parameters named emp_id and increase: Eg. PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary REAL; What are the types of Notation ? Position, Named, Mixed and Restrictions. What all important parameters of the init.ora are supposed to be increased if you want to increase the SGA size ? In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 & 3500) shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 & 9MB) open_cursors was changed from 200 to 300 (std values are 200 & 300) db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of database creation}. The initial SGA was around 4MB when the server RAM was 32MB and The new SGA was around 13MB when the server RAM was increased to 128MB.

If I have an execute privilege on a procedure in another users schema, can I execute his procedure even though I do not have privileges on the tables within the procedure ? Yes What are various types of joins ? Equijoins, Non-equijoins, self join, outer join What is a package cursor ? A package cursor is a cursor which you declare in the package specification without an SQL statement. The SQL statement for the cursor is attached dynamically at runtime from calling procedures. If you insert a row in a table, then create another table and then say Rollback. In this case will the row be inserted ? Yes. Because Create table is a DDL which commits automatically as soon as it is executed. The DDL commits the transaction even if the create statement fails internally (eg table already exists error) and not syntactically. What are the various types of queries ? Normal Queries Sub Queries Co-related queries Nested queries Compound queries What is a transaction ? A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements. What is implicit cursor and how is it used by Oracle ? An implicit cursor is a cursor which is internally created by Oracle. It is created by Oracle for each individual SQL. Which of the following is not a schema object : Indexes, tables, public synonyms, triggers and packages ? Public synonyms What is PL/SQL? PL/SQL is Oracle's Procedural Language extension to SQL. The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools. Is there a PL/SQL Engine in SQL*Plus? No. Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine. Thus, all your PL/SQL are send directly to the database engine for execution. This makes it much

more efficient as SQL statements are not stripped off and send to the database individually. Is there a limit on the size of a PL/SQL block? Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is 100K. You can run the following select statement to query the size of an existing package or procedure. SQL> select * from dba_object_size where name = 'procedure_name' Can one read/write files from PL/SQL? Included in Oracle 7.3 is a UTL_FILE package that can read and write files. The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command. DECLARE fileHandler UTL_FILE.FILE_TYPE; BEGIN fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W'); UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1)); UTL_FILE.FCLOSE(fileHandler); END; How can I protect my PL/SQL source code? PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code. 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. The syntax is: wrap iname=myscript.sql oname=xxxx.yyy Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ? From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements. Eg: 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;

Read more: http://www.ittestpapers.com/articles/oracle-interview-questions---part3.html#ixzz22nBbxu00

FAQ / Interview questions in DBMS


Written By: Mahidhar Reddy 8-27-2009 Categorized in: SQL/PLSQL/Oracle 1. What is database? A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose. 2. What is DBMS? It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications. 3. What is a Database system? The database and DBMS software together is called as Database system. 4. Advantages of DBMS? Redundancy is controlled. Unauthorised access is restricted. Providing multiple user interfaces. Enforcing integrity constraints. Providing backup and recovery. 5. Disadvantage in File Processing System? Data redundancy & inconsistency. Difficult in accessing data. Data isolation. Data integrity. Concurrent access is not possible. Security Problems. 6. Describe the three levels of data abstraction? The are three levels of abstraction: Physical level: The lowest level of abstraction describes how data are stored. Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data. View level: The highest level of abstraction describes only part of entire database. 7. Define the "integrity rules" There are two Integrity rules.

Entity Integrity: States that Primary key cannot have NULL value Referential Integrity: States that Foreign Key can be either a NULL value or should be Primary Key value of other relation. 8. What is extension and intension? Extension It is the number of tuples present in a table at any instance. This is time dependent. Intension It is a constant value that gives the name, structure of table and the constraints laid on it. 9. What is System R? What are its two major subsystems? System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system. Its two subsystems are Research Storage System Relational Data System. 10. How is the data structure of System R different from the relational structure? Unlike Relational systems in System R Domains are not supported Enforcement of candidate key uniqueness is optional Enforcement of entity integrity is optional Referential integrity is not enforced 11. What is Data Independence? Data independence means that the application is independent of the storage structure and access strategy of data. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level. Two types of Data Independence: Physical Data Independence: Modification in physical level should not affect the logical level. Logical Data Independence: Modification in logical level should affect the view level. NOTE: Logical Data Independence is more difficult to achieve 12. What is a view? How it is related to data independence? A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence.

13. What is Data Model? A collection of conceptual tools for describing data, data relationships data semantics and constraints. 14. What is E-R model? This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes. 15. What is Object Oriented model? This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes. 16. What is an Entity? It is a 'thing' in the real world with an independent existence. 17. What is an Entity type? It is a collection (set) of entities that have same attributes. 18. What is an Entity set? It is a collection of all entities of particular entity type in the database. 19. What is an Extension of entity type? The collections of entities of a particular entity type are grouped together into an entity set. 20. What is Weak Entity set? An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set. 21. What is an attribute? It is a particular property, which describes the entity. 22. What is a Relation Schema and a Relation? A relation Schema denoted by R(A1, A2, , An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn). 23. What is degree of a Relation? It is the number of attribute of its relation schema.

24. What is Relationship? It is an association among two or more entities. 25. What is Relationship set? The collection (or set) of similar relationships. 26. What is Relationship type? Relationship type defines a set of associations or a relationship set among a given set of entity types. 27. What is degree of Relationship type? It is the number of entity type participating. 25. What is DDL (Data Definition Language)? A data base schema is specifies by a set of definitions expressed by a special language called DDL. 26. What is VDL (View Definition Language)? It specifies user views and their mappings to the conceptual schema. Read more: http://www.ittestpapers.com/articles/faq--interview-questions-indbms.html#ixzz22nBw5zjB

Database Questions
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. What are the different types of joins? Explain normalization with examples. What cursor type do you use to retrieve multiple recordsets? Diffrence between a "where" clause and a "having" clause What is the difference between "procedure" and "function"? How will you copy the structure of a table without copying the data? How to find out the database name from SQL*PLUS command prompt? Tadeoffs with having indexes Talk about "Exception Handling" in PL/SQL? What is the diference between "NULL in C" and "NULL in Oracle?" What is Pro*C? What is OCI? Give some examples of Analytical functions. What is the difference between "translate" and "replace"? What is DYNAMIC SQL method 4? How to remove duplicate records from a table? What is the use of ANALYZing the tables? How to run SQL script from a Unix Shell? What is a "transaction"? Why are they necessary? Explain Normalizationa dn Denormalization with examples.

20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33.

When do you get contraint violtaion? What are the types of constraints? How to convert RAW datatype into TEXT? Difference - Primary Key and Aggregate Key How functional dependency is related to database table design? What is a "trigger"? Why can a "group by" or "order by" clause be expensive to process? What are "HINTS"? What is "index covering" of a query? What is a VIEW? How to get script for a view? What are the Large object types suported by Oracle? What is SQL*Loader? Difference between "VARCHAR" and "VARCHAR2" datatypes. What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table. Difference between "ORACLE" and "MICROSOFT ACCESS" databases. How to create a database link ?

Read more: http://www.ittestpapers.com/articles/database-questions.html#ixzz22nCJOumK

S-ar putea să vă placă și