PL SQL
PL SQL
Other users can see the data changes made by the transaction.
The locks acquired by the transaction are released.
The work done by the transaction becomes permanent.
A ROLLBACK statement gets issued when the transaction ends, and the following is true.
50.Explain SPOOL
Spool command can print the output of sql statements in a file.
spool/tmp/sql_outtxt
spool off;
What are % TYPE and % ROWTYPE? What are the advantages of using these over datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.
The advantages are: I. need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.
Nested tables are similar to index by table but these can be stored in database columns but index by
tables cannot be stored in database columns.
A Nested table can be considered as a single-column table that can either be in memory, or as a column
in a database table. A nested table is quite similar to a VARRAY with the exception that the order of the
elements is not static. Elements can be deleted or added anywhere in the nested table where as a
VARRAY can only add or delete elements from the end of the array. Nested Table is known as a sparse
collection because a nested table can contain empty elements.
BEGIN
FOR i IN 1..10 LOOP
nt.EXTEND;
nt(i) := i;
END LOOP;
END;
We may create a type that is a nested table of objects of this type by:
The last line in the create table statement indicates that the nested table is not stored "in-line" with the
rest of the table
(Oracle maintains pointers between tables); you cannot refer to BeerTable in any query!
This query gives you a single value that looks like this:
BeerTableBrand(
BeerBrand(’sweet’,’ale’,’yellow’),
BeerBrand(’sour’,’lager’,’pale’))
NESTED TABLE
NESTED TABLE is an Oracle data type used to support columns containing multivalued attributes, in
this case, columns that can hold an entire sub-table.
Examples
Create a table with NESTED TABLE column:
CREATE OR REPLACE TYPE my_tab_t AS TABLE OF VARCHAR2(30);
/
CREATE TABLE nested_table (id NUMBER, col1 my_tab_t)
NESTED TABLE col1 STORE AS col1_tab;
A more complicated multi-column nested table where customers can have multiple addresses:
CREATE TYPE address_t AS OBJECT (
street VARCHAR2(30),
city VARCHAR2(20),
state CHAR(2),
zip CHAR(5) );
/
CREATE TYPE address_tab IS TABLE OF address_t;
/
CREATE TABLE customers (
custid NUMBER,
address address_tab )
NESTED TABLE address STORE AS customer_addresses;
The storage clause is not specified for the nested table column or attribute.
This makes sense but I can't work out the correct syntax to fix this I've tried
but this and every other variation I've tried result in ORA-00922: missing or invalid option
The reason of the error is that the C2 is not a nested table. The nested table is the B2 inside C2,
so you should try this:
Monitor
To see what nested tables were created, query the USER_NESTED_TABLES and
USER_NESTED_TABLE_COLS views.
How to update a table column with random values within a range in Oracle?
dbms_random() is what you are looking for:
UPDATE the_table
SET rand_amount = (amount * dbms_random.value(0, 100) ) /
4 down vote
100
WHERE amount IS NOT NULL
Candidate Key – A Candidate Key can be any column or a combination of columns that can
qualify as unique key in database. There can be multiple Candidate Keys in one table. Each
Candidate Key can qualify as Primary Key.
Primary Key – A Primary Key is a column or a combination of columns that uniquely identify a
record. Only one Candidate Key can be Primary Key.
Explain the uses of database trigger?
A PL/SQL program unit associated with a particular database table is called a database trigger. It is
used for :
Audit data modifications.
Log events transparently.
Enforce complex business rules.
Maintain replica tables
Derive column values
Implement Complex security authorizations
What are the benefits of PL/SQL packages?
Views evaluate the data in the tables underlying the view definition at the time the view is queried. It is a
logical view of your tables, with no data stored anywhere else. The upside of a view is that it will always
return the latest data to you. The downside of a view is that its performance depends on how good a select
statement the view is based on. If the select statement used by the view joins many tables, or uses joins
based on non-indexed columns, the view could perform poorly.
Materialized views are similar to regular views, in that they are a logical view of your data (based on a
select statement), however, the underlying query resultset has been saved to a table. The upside of this is
that when you query a materialized view, you are querying a table, which may also be indexed. In addition,
because all the joins have been resolved at materialized view refresh time, you pay the price of the join once
(or as often as you refresh your materialized view), rather than each time you select from the materialized
view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of
your materialized view in such a way that it instead reads from your materialized view. In situations where
you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this
can greatly speed up the response time of your end user application. The downside though is that the data
you get back from the materialized view is only as up to date as the last time the materialized view has been
refreshed.
Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a
change in data from one of the underlying tables. Materialized views can be incrementally updated by
combining them with materialized view logs, which act as change data capture sources on the underlying
tables.
Materialized views are most often used in data warehousing / business intelligence applications where
querying large fact tables with thousands of millions of rows would result in query response times that
resulted in an unusable application.
What is a schema?
Ans: The set of objects owned by user account is called the schema.
What is difference between CHAR and VARCHAR2? What is the maximum SIZE
allowed for each type?
Ans: CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad
blank spaces. For CHAR the maximum length is 255 and 2000 for VARCHAR2
What is a tablespace?
Ans: A database is divided into Logical Storage Unit called tablespaces. A
tablespace is used to grouped related logical structures together.
Explanation :
The distinct keyword is there to deal with duplicate salaries in the table. In order to find
the Nth highest salary, we are only considering unique salaries. Highest salary means no
salary is higher than it, Second highest means only one salary is higher than it, 3rd highest
means two salaries are higher than it, similarly Nth highest salary means N-1 salaries are
higher than it.
How will the fetch the last inserted record in any table ?
Ans: select column 1, column 2.... From where rowid = (select max(rowid) from
table);
A referential integrity constraint requires that for each row of a table, the value in
the foreign key matches a value in a parent key.
2. A TRUNCATE statement does not affect any structures associated with the table
being truncated (constraints and triggers) or authorizations (grants).
3. A TRUNCATE statement also specifies whether space currently allocated for the
table is returned to the containing tablespace after truncation.
1. Create a cursor
4. Defining outputs
TYPES OF HINTS :
FULL : The FULL hint explicitly chooses a full table scan for the specified table.
ROWID : The ROWID hint explicitly chooses a table scan by ROWID for the
specified table.
CLUSTER : The CLUSTER hint explicitly chooses a cluster scan to access the
specified table.
HASH : The HASH hint explicitly chooses a hash scan to access the specified table.
INDEX : The INDEX hint explicitly chooses an index scan for the specified table.
AND_EQUAL: The AND_EQUAL hint explicitly chooses an execution plan that uses
an access path that merges the scans on several single-column indexes. (You can
specify multiple indexes through this hint) INDEX_ASC: The INDEX_ASC hint
explicitly chooses an index scan for the specified table. If the statement uses an
index range scan, ORACLE scans the index entries in ascending order of their
indexed values.
INDEX_DESC: The INDEX_DESC hint explicitly chooses an index scan for the
specified table. If the statement uses an index range scan, ORACLE scans the
index entries in descending order of their indexed values.
ORDERED : The ORDERED hint causes ORACLE to join tables in the order in which
they appear in the FROM clause.
USE_NL : The USE_NL hint causes ORACLE to join each specified table to another
row source with a nested loops join using the specified table as the inner table.
USE_MERGE : The USE_MERGE hint causes ORACLE to join each specified table
with another row source with a sort-merge join.
Ans: No
Ans: JSP Query : The JSP Query is a standard query for number to words
conversion, used especially for converting amount in number into equivalent
amount in words. The query is as follows : Select to_char ( to_date ( ‘&no’, ‘J’ ),
‘JSP’ ) words from dual; For eg : Select to_char ( to_date ( '23949','j' ), 'JSP' )
"words" from dual; The value that can pass to &no cannot exceed 7 digits.
What is “Check Constraints” and “with check options” and “Default Specification”?
Ans: CHECK Integrity Constraints: A CHECK integrity constraint on a column or a
set of columns requires that a specified condition be true or unknown (ie. Not
false) for every row of the table. If a DML statement is issued so that the condition
of the CHECK constraint evaluates to false, the statement is rolled back. With
check Option: With Check option restricts inserts and updates performed through
the view to prevent them from creating rows that the view cannot itself select
.based on where clause of the create view statement. For eg: Create or replace
view Women As select name from Employee Where Sex= ‘Female’ With Check
Option; Default Specification It supplies a default value if column value is not
specified on INSERT It can contain literals (constants) and SQL functions, USER,
SYSDATE, sequence It cannot include references to any columns.
What are SQLCODE and SQLERRM and why are they important for PL/SQL
developers?
Ans: SQLCODE returns the value of the error number for the last error
encountered. The SQLERRM returns the actual error message for the last error
encountered. They can be used in exception handling to report, or, store in an
error log table, the error that occurred in the code. These are especially useful for
the WHEN OTHERS exception.
REF CURSOR
A REF Cursor is a datatype that holds a cursor value in the same way that a VARCHAR2 variable will
hold a string value.
A REF Cursor can be opened on the server and passed
Example[edit]
Create a function that opens a cursor and returns a reference to it:
Call the above function and fetch all rows from the cursor it returns:
set serveroutput on
DECLARE
c SYS_REFCURSOR;
v VARCHAR2(1);
BEGIN
c := f(); -- Get ref cursor from function
LOOP
FETCH c into v;
EXIT WHEN c%NOTFOUND;
dbms_output.put_line('Value from cursor: '||v);
END LOOP;
END;
/
the difference is that a ref cursor can be assigned to different result sets whereas a cursor is
always associated with the same result set.
The real purpose of ref cursors is to be able to share cursors and result sets between the client
and the Oracle server or between different subroutines. For example you might open a cursor in
an Oracle Forms client and then continue working with the cursor on the server or you might open
a cursor in a Java program and then continue working with it in an Oracle PL/SQL stored
procedure.
Ref cursors also come in two variants: strongly typed and weakly typed depending on how likely
you are (or want to) reuse a cursor variable. Weak ref cursor types can be associated with any
query whereas strong ref cursor types can only be associated with cursors of the same type.
select case when null = null then 'Yup' else 'Nope' end as Result;
This query will actually yield “Nope”, seeming to imply that null is not equal to
itself! The reason for this is that the proper way to compare a value to null in SQL
is with the is operator, not with =.
Accordingly, the correct version of the above query that yields the expected result
(i.e., “Yup”) would be as follows:
select case when null is null then 'Yup' else 'Nope' end as Result;
Given a table TBL with a field Nmbr that has rows with
thwing values:
1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1
write a query to add 2 where nmbr is 0 and add 3
when nmbr is 1
update TBL set Nmbr = case when Nmbr > 0 then Nmbr+3 else Nmbr+2 end;
Answer-
Subquery: – The inner query is executed only once. The inner query will get executed first and the
output of the inner query used by the outer query. The inner query is not dependent on outer
query.
Please check out the famous example below- ( 2nd Highest Salary )
• Missing Indexes
• Missing Statistics
• Red Flags
• How data is being retrieved (Which path , what all indexes are used)
SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > 200)
So, what exactly is happening when that first row is processed? Well, if you pay special attention to the
subquery you will notice that it’s basically searching for the count of salary entries in the Employee table that
are greater than 200. Basically, the subquery is trying to find how many salary entries are greater than 200.
Then, that count of salary entries is checked to see if it equals 1 in the outer query, and if so then everything
from that particular row in Emp1 will be returned.
Note that Emp1 and Emp2 are both aliases for the same table – Employee. Emp2 is only being used in the
subquery to compare all the salary values to the current salary value chosen in Emp1. This allows us to find
the number of salary entries (the count) that are greater than 200. And if this number is equal to N-1 (which
is 1 in our case) then we know that we have a winner – and that we have found our answer.
But, it’s clear that the subquery will return a 2 when Emp1.Salary is 200, because there are clearly 2 salaries
greater than 200 in the Employee table. And since 2 is not equal to 1, the salary of 200 will clearly not be
returned.
So, what happens next? Well, the SQL processor will move on to the next row which is 800, and the resulting
query looks like this:
SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > 800)
Since there are no salaries greater than 800, the query will move on to the last row and will of course find
the answer as 450. This is because 800 is greater than 450, and the count will be 1. More precisely, the
entire row with the desired salary would be returned, and this is what it would look like:
EmployeeID Salary
7 450
It’s also worth pointing out that the reason DISTINCT is used in the query above is because there may be
duplicate salary values in the table. In that scenario, we only want to count repeated salaries just once,
which is exactly why we use the DISTINCT operator.
Dynamic SQL
Dynamic SQL is a SQL statement that is constructed and executed at program execution time. In contrast to
this, static SQL statements are hard-coded in the program and executed "as-is" at run-time. Dynamic SQL
provides more flexibility, nevertheless, static SQL is faster and more secure than dynamic SQL.
NDS
Native Dynamic SQL is the easier way to write dynamic SQL. It uses the 'EXECUTE
IMMEDIATE' command to create and execute the SQL at run-time. But to use this way, the
datatype and number of variable that to be used at run time needs to be known before. It also
gives better performance and less complexity when compares to DBMS_SQL.
Syntax Explanation:
The above syntax shows EXECUTE IMMEDIATE command.
Clause INTO is optional and used only if the dynamic SQL contains a select
statement that fetches values. The variable type should match with the variable type of
the select statement.
Clause USING is optional and used only if the dynamic SQL contains any bind
variable.
Example1: In this example, we are going to fetch the data from emp table for emp_no '1001'
using NDS statement.
Code Explanation:
Code line 2-6: Declaring variables.
Code line 8: Framing the SQL at run-time. SQL contains the bind variable in where
condition ':empno'.
Code line 9: Executing the framed SQL text (which is done in code line 8) using the
NDS command 'EXECUTE IMMEDIATE'
The variables in 'INTO' clause (lv_emp_name, ln_emp_no, ln_salary, ln_manager) is
used to hold the fetched values from the SQL query (emp_name, emp_no, salary,
manager)
'USING' clause gives the values to the bind variable in the SQL query (:emp_no).
Code line 10-13: Displaying the fetched values.
Code Explanation:
Code line 1-9: Variable declaration.
Code line 10: Framing the SQL statement.
Code line 11: Opening the cursor using DBMS_SQL.OPEN_CURSOR. It will return
the cursor id which is opened.
Code line 12: After the cursor is opened, the SQL is parsed.
Code line 13: Bind variable '1001' is assigning to the cursor id instead ':empno'.
Code line 14-17: Defining the column name based on their relative position in the
SQL statement. In our case, the relative position is (1) emp_name, (2) emp_no (3)
salary (4) manager. So based on this position we are defining the target variable.
Code line 18: Executing the query using DBMS_SQL.EXECUTE. It returns the
number of records processed.
Code line 19-33: Fetching the records using a loop and displaying the same.
Code line 20: DBMS_SQL.FETCH_ROWS will fetch one record from the rows
processed. It can be called repeatedly to fetch all the rows. If it cannot fetch rows, it will
return 0, thus exiting the loop.
Summary
In this section, we have discussed dynamic SQL and the ways to execute DYNAMIC SQL.
We have also seen the different steps in executing the dynamic SQL in both the ways. We
have also seen the examples in which the same scenario is handled in both NDS and
DBMS_SQL ways to perform execution at run-time.
Use the built-in function VALUE, found in the built-in package DBMS_RANDOM, in conjunction
with ORDER BY and the built-in function ROWNUM:
1 select *
2 from (
3 select ename, job
4 from emp
6 order by dbms_random.value()
7 )
8 where rownum <= 5
Dual table is owned by the user SYS and can be accessed by all users. It contains one
columnDummy and one row with the value X. The Dual Table is useful when you want to
return a value only once. The value can be a constant, pseudocolumn or expression that is not
derived from a table with user data.
1.NVL: Converts a null value to an actual value. NVL (exp1, exp2) .If exp1 is null then
NVL function return value of exp2.
2.NVL2: If exp1 is not null, nvl2 returns exp2, if exp1 is null, nvl2 returns exp3. The
argument exp1 can have any data type. NVL2 (exp1, exp2, exp3)
3.NULLIF: Compares two expressions and returns null if they are equal or the first
expression if they are not equal. NULLIF (exp1, exp2)
4.COALESCE: Returns the first non-null expression in the expression list. COALESCE
(exp1, exp2… expn). The advantage of the COALESCE function over NVL function is
that the COALESCE function can take multiple alternative values.
5.Conditional Expressions: Provide the use of IF-THEN-ELSE logic within a SQL
statement. Example: CASE Expression and DECODE Function.
6.
What is a difference between “VERIFY” and “FEEDBACK” command?
VERIFY Command: Use VERIFY Command to confirm the changes in the SQL statement (Old
and New values). Defined with SET VERIFY ON/OFF.
A LONG column is not copied when a table is created using a sub query. A LONG column
cannot be included in a GROUP BY or an ORDER BY clause. Only one LONG column can be
used per table. No constraint can be defined on a LONG column.