Você está na página 1de 15

SQL & PLSQL Questions: What is the use of Cascade Constraint?

Cascading is used for maintaining referential integrity rules, which says that foreign key attributes values should be either subset of primary key values or null. With cascading when parent is deleted child could be deleted/set null/set default according to cascade type. All this is for maintain integrity. 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. <br> WHERE clause can be used with DELETE and not with TRUNCATE. What is the use of Translate Function? Translate function replaces a sequence of characters in a string with another set of characters. However, it replaces a single character at a time. For example, it will replace the 1st character in the string_to_replace with the 1st character in the replacement_string . Then it will replace the 2nd character in the string_to_replace with the 2nd character in the replacement_string , and so on. The syntax for the translate function is: translate( string1, string_to_replace, replacement_string ) Eg: translate('1tech23', '123', '456); would return '4tech56' What is the Purpose of HAVING Clause? The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT statement to filter the records that a GROUP BY returns. The syntax for the HAVING clause is: SELECT column1, column2, ... column_n, aggregate_function (expression) FROM tables WHERE predicates GROUP BY column1, column2, ... column_n HAVING condition1 ... condition_n;

aggregate_function can be a function such as SUM , COUNT , MIN , or MAX . What is Materialized View in SQL? Materialized views are schema objects that can be used to summarize, precompute, replicate, and distribute data. E.g. to construct a data warehouse. A materialized view provides indirect access to table data by storing the results of a query in a separate schema object. Unlike an ordinary view, which does not take up any storage space or contain any data. The existence of a materialized view is transparent to SQL, but when used for query rewrites will improve the performance of SQL execution. Materialized views allow you to maintain copies of remote data on your local node. These copies are read-only. Primary Key Materialized View CREATE MATERIALIZED VIEW mv_emp_pk REFRESH FAST START WITH SYSDATE NEXT SYSDATE + 1/48 WITH PRIMARY KEY AS SELECT * FROM emp@remote_db; When you create a materialized view using the FAST option you will need to create a view log on the master tables(s). CREATE MATERIALIZED VIEW LOG ON emp; What is INLINE View in SQL? The inline view is a construct in Oracle SQL where you can place a query in the SQL FROM, clause, just as if the query was a table name. What is UNION in SQL? The UNION query allows you to combine the result sets of 2 or more "select" queries. It removes duplicate rows between the various "select" statements. Each SQL statement within the UNION query must have the same number of fields in the result sets with similar data types. The syntax for a UNION query is: select field1, field2, . field_n from tables UNION select field1, field2, . field_n from tables; What is UNION ALL in SQL?

The UNION ALL query allows you to combine the result sets of 2 or more "select" queries. It returns all rows (even if the row exists in more than one of the "select" statements). Each SQL statement within the UNION ALL query must have the same number of fields in the result sets with similar data types. The

syntax for a UNION ALL query is: select field1, field2, . field_n from tables UNION ALL select field1, field2, . field_n from tables; What is Global Temporary Table? Global temporary tables are distinct within SQL sessions. The basic syntax is: CREATE GLOBAL TEMPORARY TABLE table_name (...); What is EXISTS in SQL? The EXISTS condition is considered "to be met" if the subquery returns at least one row. The syntax for the EXISTS condition is: SELECT columns FROM tables WHERE EXISTS ( subquery ); What is the purpose of IN Function in SQL? The IN function helps reduce the need to use multiple OR conditions. The syntax for the IN function is: SELECT columns FROM tables WHERE column1 in (value1, value2, .... value_n); This SQL statement will return the records where column1 is value1, value2..., or value_n. The IN function can be used in any valid SQL statement - select, insert, update, or delete. What is the difference between IN and EXISTS in Subqueries? There's a difference when using rule-based optimization. You can determine the performance of a rulebased query by understanding which table is the driving table and how many rows each part returns. When you write a query using the IN clause, you're telling the rule-based optimizer that you want the inner query to drive the outer query (think: IN = inside to outside). E.g. select ename from emp e where mgr in (select empno from emp where ename = 'KING'); When you write EXISTS in a where clause, you're telling the optimizer that you want the outer query to be run first, using each value to fetch a value from the inner query (think: EXISTS = outside to inside). E.g. select ename from emp e where exists (select 0 from emp where e.mgr = empno and ename = 'KING'); What is the Purpose of Sequence in PLSQL? In Oracle, you can create an autonumber field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key. The syntax for a sequence is: CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value START WITH value INCREMENT BY value CACHE value; For example: CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20; While creating a sequence, what does MAXVALUE 999999999999999999999999999

cache and nocache options mean? With respect to a sequence, the cache option specifies how many sequence values will be stored in memory for faster access. What is Instr Function?

Instr function returns the position of the first occurrence of a string in another string. The syntax for the Instr function is: Instr ( [start], string_being_searched, string2, [compare] ) start is optional. It is the starting position for the search. If this parameter is omitted, the search will begin at position 1. string_being_searched is the string that will be searched. string2 is the string to search for. compare is optional. This is the type of comparison to perform. The valid choices are: VBA Constant

Value

Explanation

vbUseCompareOption

Uses option compare.

vbBinaryCompare

Binary comparison

vbTextCompare

Textual comparison

vbDatabaseCompare

Comparison based on your database.

Note: If string2 is not found within string_being_searched , the Instr function will return 0. If string_being_searched is zero-length, the Instr function will return 0. If string_being_searched is null, the Instr function will return null. If string2 is zero-length, the Instr function will return the value used in the start parameter. If the start parameter is omitted, the Instr

function will return 1. If start is greater than string2, the Instr function will return 0. Can you update the data in a view? A view is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the view. So, yes, you can update the data in a view providing you have the proper privileges to the underlying tables. Does the view exist if the table is dropped from the database? Yes, in Oracle, the view continues to exist even after one of the tables (that the view is based on) is dropped from the database. However, if you try to query the view after the table has been dropped, you will receive a message indicating that the view has errors. How will you update a View in SQL? You can update a VIEW without dropping it by using the following syntax: CREATE OR REPLACE VIEW view_name AS SELECT columns FROM table WHERE predicates;

What is a primary key? A primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a null value. A table can have only one primary key. Note: In Oracle, a primary key cannot contain more than 32 columns. What is a foreign key? A foreign key means that values in one table must also appear in another table. The referenced table is called the

parent table while the table with the foreign key is called the child table . The foreign key in the child table will generally reference a primary key in the parent table. A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement. What is a unique constraint? A unique constraint is a single field or combination of fields that uniquely defines a record. Some of the fields can contain null values as long as the combination of values is unique.

What is the difference between a unique constraint and Primary Key?

Primary Key

Unique Constraint

None of the fields that are part of the primary key can contain a null value.

Some of the fields that are part of the unique constraint can contain null values as long as the combination of values is unique.

Oracle does not permit you to create both a primary key and unique constraint with the same columns.

What is a check constraint? A check constraint allows you to specify a condition on each row in a table. Note:

A check constraint can NOT be defined on a VIEW .

The check constraint defined on a table must refer to only columns in that table. It can not refer to columns in other tables.

A check constraint can NOT include a SUBQUERY . A check constraint can be defined in either a CREATE TABLE statement or an ALTER TABLE statement. What is an Index? An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes. Create an Index The syntax for creating a index is: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, . column_n) [ COMPUTE STATISTICS ]; UNIQUE indicates that the combination of values in the indexed columns must be unique. Create a Function-Based Index

In Oracle, you are not restricted to creating indexes on only columns. You can create function-based indexes. The syntax for creating a function-based index is: CREATE [UNIQUE] INDEX index_name ON table_name (function1, function2, . function_n) [ COMPUTE STATISTICS ]; What types of index data structures can you have?

An index helps to faster search values in tables. The three most commonly used index-types are: B-Tree: builds a tree of possible values with a list of row IDs that have the leaf value. Needs a lot of space and is the default index type for most databases. Bitmap: string of bits for each possible value of the column. Each bit string has one bit for each row. Needs only few space and is very fast.(however, domain of value cannot be large, e.g. SEX(m,f); degree(BS,MS,PHD) Hash: A hashing algorithm is used to assign a set of characters to represent a text string such as a composite of keys or partial keys, and compresses the underlying data. Takes longer to build and is supported by relatively few databases. What is Synonym in PLSQL. A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects. The syntax for creating a synonym is: create [or replace] [public] synonym [schema .] synonym_name for [schema .] object_name [@ dblink]; The or replace phrase allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command. The public

phrase means that the synonym is a public synonym and is accessible to all users. Remember though that the user must first have the appropriate privileges to the object to use the synonym. The schema phrase is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema. The object_name phrase is the name of the object for which you are creating the synonym. It can be one of the following: table

package

view

materialized view

sequence

java class schema object

stored procedure

user defined object

function

synonym

Synonyms are used to: - Mask the real name and owner of a schema object - Provide global (public) access to a schema object - Provide location transparency for tables, views, or program units of a remote database. - Simplify SQL statements for database users The syntax for dropping a synonym is: drop [public] synonym [schema .] synonym_name [force]; Explain Cursors in PLSQL. A cursor is a mechanism by which you can assign a name to a "select statement" and manipulate the information within that SQL statement. We've categorized cursors into the following topics: Declare a Cursor OPEN Statement FETCH Statement CLOSE Statement Cursor Attributes (%FOUND, %NOTFOUND, etc) SELECT FOR UPDATE Statement WHERE CURRENT OF Statement Below is a function that uses this cursor . CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; END; Define Cursor Attributes in PLSQL. Attribute Explanation %ISOPEN Returns TRUE if the cursor is open, FALSE if the cursor is closed. %FOUND

- Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. - Returns NULL if cursor is open, but fetch has not been executed. - Returns TRUE if a successful fetch has been executed. - Returns FALSE if no row was returned. %NOTFOUND Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. - Return NULL if cursor is open, but fetch has not been executed. - Returns FALSE if a successful fetch has been executed. - Returns TRUE if no row was returned. %ROWCOUNT Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. - Returns the number of rows fetched. - The ROWCOUNT attribute doesn't give the real row count until you have iterated through the entire cursor. In other words, you shouldn't rely on this attribute to tell you how many rows are in a cursor after it is opened. In PSQL, I want to declare a cursor within cursor. The second cursor should use a value from the first cursor in the "where clause". How can I do this? In this example, we have a cursor called get_tables that retrieves the owner and table_name values. These values are then used in a second cursor called get_columns . create or replace procedure MULTIPLE_CURSORS_PROC is v_owner varchar2(40);

v_table_name varchar2(40); v_column_name varchar2(100); /* First cursor */ cursor get_tables is select distinct tbl.owner, tbl.table_name from all_tables tbl where tbl.owner = 'SYSTEM'; /* Second cursor */ cursor get_columns is select distinct col.column_name from all_tab_columns col where col.owner = v_owner and col.table_name = v_table_name; begin -Open first cursor open get_tables; loop fetch get_tables into v_owner, v_table_name; open get_columns; loop fetch get_columns into v_column_name; end loop; close get_columns; end loop; close get_tables; EXCEPTION WHEN OTHERS THEN raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM); end MULTIPLE_CURSORS_PROC; The trick to declaring a cursor within a cursor is that you need to continue to open and close

the second cursor each time a new record is retrieved from the first cursor. That way, the second cursor will use the new variable values from the first cursor. What is the difference between a "where" clause and a "having" clause?

"Where" is a kind of restiriction statement. You use where clause to restrict all the data from DB.Where clause is using before result retrieving. But Having clause is using after retrieving the data.Having clause is a kind of filtering command. What structure can you implement for the database to speed up table reads?

Follow the rules of DB tuning we have to: 1] properly use indexes ( different types of indexes) 2] properly locate different DB objects across different tablespaces, files and so on. 3] create a special space (tablespace) to locate some of the data with special datatype ( for example CLOB, LOB and )

Write Syntax to retrieve the Top N records from a query SELECT * FROM (your ordered query) alias_name WHERE rownum <= Rows_to_return ORDER BY rownum; Write Syntax to retrieve the Bottom N records from a query SELECT * FROM (your query ordered in reverse) alias_name WHERE rownum <= Rows_to_return ORDER BY rownum DESC; Write Syntax to retrieve the Middle N records from a query SELECT * FROM (select alias_name.*, rownum rnum from (-- your ordered query --) alias_name where rownum <= UPPER_BOUND ) WHERE rnum >= LOWER_BOUND; Write Syntax to retrieve the second lowest salary from a salary table SELECT salary_amount FROM (select salary2.*, rownum rnum from (select * from salary ORDER BY salary_amount) salary2 where rownum <= 2 ) WHERE rnum >= 2; How can I retrieve the second highest salary amount from a salary table?

To retrieve the second highest salary from a salary table, you could run the following query: (please note that the subquery is sorted in descending order) SELECT salary_amount FROM

(select salary2.*, rownum rnum from

(select * from salary ORDER BY salary_amount DESC) salary2

where rownum <= 2

WHERE rnum >= 2;

Você também pode gostar