Thursday 30 August 2012

SQL Interview Questions and Answers Part8

Q: What is the constructor?
A: The constructor creates an empty nested table as opposed to leaving it null.
Notice that without using the constructor, it is not possible to refer to the
nested table with the "THE" clause.
Q: What is the ‘THE’ sub-query?
A: To query a nested table you should use the "THE" clause. Also, the "THE"
sub-query is used to identify the nested table to INSERT INTO.
Q: How do you query a record using the ‘THE’ sub-query?
A: SQL > SELECT name
FROM
THE(SELECT kids FROM emp_family WHERE empno = 7788)
SQL> /
Q: What is a nested table?
A: It is a table within a table.
Q: How do you insert a record to a nested table?
A: SQL> INSERT INTO
THE(SELECT kids FROM emp_family
WHERE empno = 7900)
VALUES ('Sue','10-DEC-99');
Q: How do you update a record to nested table?
A: SQL > UPDATE emp_family
SET kids = employee_kids_table(
employee_kids('Sara','08-OCT-88'))
WHERE empno = 7788
SQL> /
Q: How do you add a unique index to a nested table?
A: SQL > CREATE UNIQUE INDEX i_nested_employee_kids_table
ON nested_employee_kids_table(nested_table_id,name)
SQL> /
Q: What is a data replica?
A: A duplicated data in a different location.
Q: What is the difference between a materialized view and a materialized view
log?
A: The Materialized view is a real duplicated data from a primary table but the
materialized view log is an on going logs generated due to the table changes
after the last refresh.
Q: What is an OID (Object ID)?
A: It is a unique ID assigned to an object by Oracle.
Q: How do you retrieve an object ID?
A: SQL > SELECT OWNER, TYPE_OID FROM DBA_TYPES
WHERE TYPE_NAME LIKE 'ADDRESS%';
Q: How do you use an object ID to create an object type?
A: SQL > CREATE OR REPLACE TYPE address_book_type_object
OID ‘XXXXXXXXXXXXXXXXXXXXX’
AS OBJECT (
id_address NUMBER(1),
address VARCHAR2 (20));
Q: What is the relationship between primary and foreign keys?
A: The relationships between two tables are normally established by defining
primary or foreign keys. A primary key has the immutable responsibility of
serving as a unique identifier in a table. A foreign key is a column that refers
to the primary key of another table. To join two tables, a “where clause” is used
to set up a table relationship between primary and foreign keys.
Q: What is a composite index?
A: A primary key can be composed of more than one column. We call it a
composite index.
Q: What is the result of 100 + NULL ?
A: NULL value.
Q: Write a query to concatenate the customers’ last name and first name
separated by comma.
A: SELECT last_name || ‘, ‘ || first_name
as “Full Name”
FROM customers
/
Q: Query the employees name and their department name using the “DECODE”
function. If the department number is 10 then print "accounting.” If the
department number is 20 then print "research," or if the department number is 30
then print "sales." Anything else prints others.
A: SELECT ename, DECODE (deptno, 10, 'Accounting',
20,
'Research',
30,
'Sales',
'Others') AS "Department"
FROM emp
/
Q: Query the department number and their total salaries that have more than 5
employees working in their department.
A: SELECT deptno, SUM(sal)
FROM emp
GROUP BY deptno
HAVING count(*) > 5
/
Q: query the customer names which have more than four orders.
A: SELECT name FROM customer c
WHERE exists (SELECT 'T' FROM ord
WHERE custid = c.custid
GROUP BY custid
HAVING count(*) > 4)
/
Q: Create an employee table that contains five columns:
Such as Employee Id, last name, First name, Phone number and Department number
with the following constraints.
The last name and first name should be not null.
Make a check constraint to check the department number is between 9 and 100.
Make a primary constraint on the employee ID column.
Make a foreign key on the department number column.
Use the "delete cascade" to delete all records if parent gets deleted.
Use the "phone number" as a unique key.
A: CREATE TABLE employee
(empid NUMBER(10),
lastname VARCHAR2(20) not null,
firstname VARCHAR2 (20) not null,
phone_no VARCHAR2 (15),
deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),
constraint pk_employee_01 PRIMARY KEY (empid),
constraint fk_dept_01 FOREIGN KEY (deptno)
references dept (deptno) ON DELETE CASCADE,
constraint uk_employee_01 UNQUE (phone_no))
Q: What is the difference between the delete statement and the truncate
statement?
A: On the DELETE statement the watermark will not change. But using the
TRUNCATE statement will change the watermark to the beginning of the table.
Q: Copy the “EMP” table to another table and name the new table "employee." In
the new employee table use the employee name, job, commission and department
number.
A: CREATE TABLE employee
AS SELECT ename, job, comm, deptno
FROM emp
/
Q: Reorganize the “employee_indx” index table.
A: ALTER INDEX employee_indx REBUILD
/
Q: What is the difference between public and private synonym?
A: You create synonym so that the users don’t need to type schema name to a
table when they query the table. The Public Synonym is available to all database
users but the Private Synonym is available only to the owner of synonym.
Q: Can you have multiple SQL statements in the afiedt.buf file?
A: No.
Q: How do you execute or run a SQL script?
A: SQL> @my_sql_script; or start my_sql_script;
Q: Write a query to list all the department names that their total paid
salaries are more than 1/3 of the total salary of the company.
A: SQL > WITH summary_totals AS
(SELECT dname,
SUM (sal) AS totals
FROM emp NATURAL JOIN dept
GROUP BY dname)
SELECT dname, totals
FROM summary_totals
WHERE totals > (SELECT SUM (totals)*1/3
FROM summary_totals)
ORDER BY totals DESC
SQL >/
Q: What is a Materialized View?
A: A materialized view (MVIEW) is a replica of a target master from a single
point in time. You use Materialized Views to create summaries in a data warehouse
environment or replicate a data in a distributed environment. In data warehouses,
you can use materialized views to pre-compute and store aggregated data such as
the sum of sales. In distributed environments, you can use materialized views to
replicate data from a master site to other distributed sites.
Q: What does the following SQL statement?
SQL > DELETE FROM dup_emp
WHERE ROWID IN (SELECT MAX (ROWID)
FROM dup_emp
GROUP BY empno
HAVING COUNT (empno) > 1)
SQL> /
A: Deletes duplicated records.
Q: What does the MAXVALUE parameter mean in the data partitioning?
A: It is the maximum possible value that can be store into a column.
Q: What does the following SQL statement?
SQL > INSERT INTO THE(SELECT kids FROM emp_family
WHERE empno = 7900)VALUES ('Sue','10-DEC-99')
SQL > /
A: Inserts a record to a nested object in a table.

SQL Interview Questions and Answers Part7

Q: Write the difference between ROWID and PRIMARY KEY in the Materialized View.
A: Fast refresh requires association between rows at snapshot and master sites.
Snapshots that use ROWIDs to refresh are called ROWID snapshots while those that
use primary keys are called primary key snapshots.
Q: What is the difference between a Materialized View and View?
A: A Materialized View is a physical duplicated data in a table, but a View is
just a logical presentation of a table.
Q: When or why do you use a Materialized View?
A: You use Materialized Views to create summaries in a data warehouse
environment or replicate a data in a distributed environment. In data warehouses,
you can use materialized views to pre-compute and store aggregated data such as
the sum of sales. In distributed environments, you can use materialized views to
replicate data from a master site to other distributed sites.
Q: What is a materialized view log?
A: A materialized view log is a holder that contains updated, inserted, or
deleted records’ information in the primary table.
Q: What are the PRIMARY KEY and ROWID in the Materialized View Log?
A: The Materialized View log that use ROWIDs to refresh are called ROWID view
log while those that use primary keys are called primary key view log.
Q: What does the USER_SNAPSHOT_LOGS view contain?
A: It shows if our log was created successfully and its name (MLOG$_EMP).
Q: Create a materialized view that contains the department number, number of
employees, and total salaries paid to employees by department.
A: SQL > CREATE MATERIALIZED VIEW mv_sal
BUILD IMMEDIATE
REFRESH ON DEMAND
AS SELECT deptno,
COUNT(1) AS no_of_emp, SUM (sal) AS salary
FROM emp
GROUP BY deptno
SQL> /
Q: Who can create a materialized view?
A: The one that was granted the CREATE MATERIALIZED VIEW privilege.
Q: What does the USER_MVIEWS view contain?
A: It contains all the Materialized Views’ information that were created by the
user.
Q: How do you refresh a materialized view?
A: SQL > EXECUTE dbms_snapshot.refresh('mv_sal','C');
Q: What parameter should be used to update the materialized view every month
automatically without human intervention?
A: The START WITH SYSDATE option will create an immediate data, and the
NEXT(SYSDATE+30) option will update the table every 30 days.
Q: What does the USER_JOBS view contain?
A: It contains all users’ jobs in the Oracle queue.
Q: How do you remove a job from the Oracle Job Queue?
A: SQL > EXECUTE dbms_job.remove(job_number);
Q: How do you drop a materialized view log and a materialized view?
A: SQL > DROP MATERIALIZED VIEW LOG ON emp;
To drop it:
SQL> DROP MATERIALIZED VIEW mv_sal;

Q: What does the BREAK ON clause in SQLPLUS?
A: It builds a break on a column.
Q: What do the REPHEADER and REPFOOTER commands in SQLPLUS?
A: They make a report header and footer.
Q: What does the following commands?
COLUMN sal HEADING 'Salary' FORMAT $99,999.99 --Creates heading format.
COLUMN ename HEADING 'Employee' FORMAT a20 – Creates heading format.
REPHEADER '' – Creates report heading.
BREAK ON dname SKIP 1 – Creates control bread on a column and skip 1 line after
the break.
COMPUTE SUM OF sal ON dname – Computes total salary within a department.
SPOOL c:\salary.out -- Activates spooling.
SPOOL OFF -- Deactivate spooling.
REPFOOTER '' – Creates report footer.
CLEAR BUFFER -- Clear the Oracle buffer.
CLEAR COLUMNS – Clears columns.
CLEAR COMPUTE -- Clears compute functions.
Q: What does the CLEAR command in SQLPLUS?
A: Note that all the values in REPHEADER , REPFOOTER , BUFFER, COLUMNS, COMPUTE
and etc are going to stay the same during your open session. In order to clean
them, you should use the CLEAR command for BUFFER, COLUMNS, and COMPUTE. And
input NULL to REPHEADER and REPFOOTER.
Q: What does the UNION statement in the SQL statement?
A: It will query all the records that match or not match with the base table.
Q: What does the INTERSET statement in the SQL statement?
A: It will query all the records that match with the base table. It is the same
as joining two tables.
Q: What does the MINUS statement in the SQL statement?
A: It will query all the records that are not matching against your base table.
Q: Why it is important to eliminate duplicate records?
A: To keep your database integrity.
Q: What does the following SQL statement?
SQL > DELETE FROM dup_emp
WHERE ROWID IN (SELECT MAX (ROWID)
FROM dup_emp
GROUP BY empno
HAVING COUNT (empno) > 1)
SQL> /
A: Deletes all the rows that have the same employee number except the first
one.
Q: What is a data partitioning in the Oracle database?
A: The data partitioning in the Oracle database is that the data will be
partitioned in multi-tablespaces for ease of maintenances.
Q: When should you use data partitioning?
A: When you have a huge data file and can be classified to some partitions.
Q: What is the advantage of using a data partitioning?
A: It is faster to access. It is easier to maintain.
Q: What is a partition key?
A: It is used to separate data and associates them to their own assigned
tablespace.
Q: What is a local index in the data partitioning?
A: A Local index is one that is partitioned exactly like the table to which it
belongs.
Q: What is a global index in the data partitioning?A: A Global index, unlike local indexes, you should explicitly partition range
boundaries using the “VALUE LESS THAN” methods.
Q: What are the differences between local and global indexes?
A: In the local index you don’t define explicitly partition range.
Q: How does the ‘VALUE LESS THAN’ method work in the data partitioning?
A: The VALUES LESS THAN clause indicates the partition key value must be less
then its assigned value in order to be illegible for any DML transaction on its
assigned tablespace.
Q: Why do you need multiple tablespaces?
A: Multiple tablespaces give us more flexibility to maintain a tablespace
without affecting any performance or downtime to others.
Q: Create a range-based partitioning table named p_emp. Make sure that the data
entry of the each department goes to its own provided tablespaces such as the
accounting department goes to the dept10ts tablespace, the data entry of the
research department goes to the dept20ts tablespace, etc.
A: SQL > CREATE TABLE p_emp (
empno NUMBER(4) PRIMARY KEY ,
ename VARCHAR2 (10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE ,
sale NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(2))
STORAGE (INITIAL 5K
NEXT 5K
PCTINCREASE 0)
PARTITION BY RANGE (deptno)
(PARTITION dept10
VALUES LESS THAN (20)
TABLESPACE dept10ts,
PARTITION dept20
VALUES LESS THAN (30)
TABLESPACE dept20ts,
PARTITION dept30
VALUES LESS THAN (40)
TABLESPACE dept30ts,
PARTITION deptxx
VALUES LESS THAN (MAXVALUE )
TABLESPACE deptxxts)
SQL > /
Q: What does the MAXVALUE parameter mean in the data partitioning?
A: It means as large as the column can hold.
Q: How do you analyze a partition table?
A: SQL > ANALYZE TABLE p_emp COMPUTE STATISTICS;
Q: What does the USER_TAB_PARTITIONS view contain?
A: A user can query its partitions table’s information that was created by the
user.
Q: Write a query to list the accounting employees from the partition table. Use
the partition option.
A: SQL > SELECT * FROM p_emp PARTITION (dept10);
Q: Write a query to list employee number 7900 from the sales department?
A: SQL > SELECT * FROM p_emp PARTITION (dept30)
WHERE empno = 7900
SQL> /
Q: How do you create a local partition index?
A: SQL > CREATE INDEX p_emp_ind ON p_emp (deptno) LOCAL;


Q: How do you analyze a partition table index?
A: SQL > ANALYZE INDEX p_emp_ind COMPUTE STATISTICS;
Q: What does the USER_IND_PARTITIONS view contain?
A: It contains information in regard to the user’s partition indexes.
Q: What does the ROLLUP operator?
A: The ROLLUP operator returns both ‘regular rows’ and ‘super-aggregate rows.’
Super-aggregate rows are rows that contain a sub-total value.
Q: What does the CUBE function?
A: The CUBE operator returns cross-tabulation values, thus produces totals in
all possible dimensions, and is used for warehousing aggregated data reports.
Q: What are the differences between the CUBE and ROLLUP functions?
A: See the output…
Q: What environments may use the CUBE and ROLLUP functions most?
A: Warehousing.
Q: Write a query to list an aggregation sum report for each job, in each year,
using the ROLLUP grouping option.
A: SQL > SELECT year, job, SUM (sal), COUNT(*)
FROM emp
GROUP BY ROLLUP (year, job)
SQL> /
Q: Write a query to list an aggregation sum report for each job, in each year,
using the CUBE grouping option.
A: SQL > SELECT year, job, SUM (sal), COUNT(*)
FROM emp
WHERE deptno = 20
GROUP BY CUBE (year, job)
SQL> /
Q: What is an object type?
A: The object type in the Oracle database is like the class eliminate in the
C++ developer tool or any object oriented tool.
Q: What is a collection object?
A: The collection object in the Oracle database is like a nested table and a
variable array in a table.
Q: Create an object type with two columns to hold the employee's child name and
date of birth and name it employee_kids .
A: SQL > CREATE TYPE employee_kids AS OBJECT (
NAME VARCHAR2 (30),
dob DATE
)
SQL> /
Q: Create a table type using employee_kids and name it employee_kids_table.
A: SQL > CREATE TYPE employee_kids_table
IS TABLE OF employee_kids;
Q: Create the emp_family table containing the kid’s column with a type of
employee_kids_table.
A: SQL > CREATE TABLE emp_family
(empno NUMBER,
kids employee_kids_table)
NESTED TABLE kids STORE AS nested_employee_kids_table
SQL> /
Q: How do you insert a record in the object type?
A: SQL > INSERT INTO emp_family VALUES
(7902,
employee_kids_table(employee_kids('David','08-AUG-01'),
employee_kids('Peter','10-JUN-88'),
employee_kids('Mark','30-OCT-92')
)
)
SQL > /

SQL Interview Questions and Answers Part6

Q: How do you save the inserted transaction?
A: COMMIT;
Q: Change the "last_name" column value from “Smith” to “Judd” where the
"employee id" is 100.
A: SQL > UPDATE employee
SET lastname = 'Judd'
WHERE empid = 100;
Q: Delete all the employee records from the "employee" table using the delete
command and the truncate command.
A: SQL > DELETE FROM employee;
OR
SQL > TRUNCATE TABLE employee;
Q: How do you undo a transaction?
A: ROLLBACK;
Q: What is the difference between the delete statement and the truncate
statement?
A: Notice that the TRUNCATE command is a DDL statement and all DDL statements
have commit inclusive. That is why the ROLLBACK action after truncation does not
work. Also, if you want to delete all records from a table, you should use the
TRUNCATE statement. It will change the table watermark. The table watermark is an
address that indicates a last location of a record in a table. On the DELETE
statement the watermark will not change. But using the TRUNCATE statement will
change the watermark to the beginning of the table.
Q: Copy the “EMP” table to another table and name the new table "employee." In
the new employee table use the employee name, job, commission and department
number.
A: SQL > CREATE TABLE employee
AS SELECT ename, job, comm, deptno
FROM emp;
Q: Add a salary column to the employee table.
A: SQL > ALTER TABLE employee
ADD (salary NUMBER(8,2));
Q: Modify the "ename" column size from varchar10 to varchar15.
A: SQL > ALTER TABLE employee
MODIFY (ename VARCHAR2(15));
Q: Rename the "employee" table to the "iself_employee" table.
A: SQL > RENAME employee TO iself_employee;
Q: Create a view to display the employee names of the “Accounting” department
only.
A: SQL > CREATE VIEW employee_name
AS SELECT ename
FROM iself_employee
WHERE deptno = 10;
Q: Why do you use the view?
A: You use view to present rows and columns of a table in the way you want.
You may use it for security reason. For example, you may eliminate some rows and
columns that are very sensitive information. These changes are transparent to a
user.
Q: How do you compile the view?
A: SQL > ALTER VIEW employee_name COMPILE;
Q: How do you delete the view?
A: SQL > DROP VIEW employee_name;
Q: Create an index on the employee table on the ename column only and name it
employee_indx.
A: SQL > CREATE INDEX employee_indx
ON employee (ename);
Q: Reorganize the “employee_indx” index table.
A: SQL > ALTER INDEX employee_ indx REBUILD;
Q: Drop the employee_ename index table.
A: SQL > DROP INDEX employee_indx;
Q: Create a user with username “newuser” and password "newpass." Its default
tablespace should be the "iself_data" tablespace.
A: SQL > CREATE USER newuser IDENTIFIED BY by newpass
DEFAULT TABLESPACE iself_data;
Q: Grant the resource and connect roles to newuser.
A: SQL > GRANT resource, connect TO newuser;
Q: Change the newuser password to "mypass".
A: SQL > ALTER USER newuser IDENTIFIED BY mypass;
Q: Can the above new user access to any other user tables?
A: No.
Q: What is a public synonym?
A: It is a synonym that public users can use. We create public synonym so that
the users don’t need to type schema name to a table when they query the table.
Creating a public synonym does not mean that oracle users can access to that
table or object. Still the owner of the object has to grant access to a user on
its table.
Q: What is the syntax to create a public synonym?
A: SQL > CREATE PUBLIC SYNONYM employees FOR iself.iself_employee;
Q: What is the difference between public and private synonym?
A: The private synonym is only for the user who owns or created the synonym,
but the public synonym can be used by every users.
Q: Create and drop a private synonym.
A: SQL > CREATE SYNONYM emp_table FOR iself.iself_employee;
To drop:
SQL > DROP SYNONYM emp_table;
Q: Revoke an object privilege on a table from a user.
A: SQL > REVOKE UPDATE, SELECT ON employee FROM newuser;
Q: What does the LIST or ‘L’ command line editor?
A: It lists the current SQL statement that was typed in the Oracle buffer.
Q: What does the INSERT or ‘I’ command line editor?
A: It inserts a command in the Oracle buffer after the current active line
that was indicated with an *.
Q: What does the DEL or ‘D’ command line editor?
A: It deletes the current active line in the Oracle Buffer.
Q: How do you change a string in the Oracle Buffer?
A: First, mark the line as a current active line and then type the‘del’
command.
Q: How do you save the SQL script in the Oracle Buffer?
A: SQL> save c:\myscript.sql
Q: How do you open the SQL Script into the Oracle Buffer?
A: SQL> get c:\myscript.sql
Q: How do you use the notepad editor?
A: Just type: the ed command to open the default editor.
Q: What is afiedt.buf?
A: The "afiedt.buf" file is a place that into which SQL *PLUS stores the most
recently executed SQL statement.
Q: How do you change your text editor in the SQLPLUS tool?
A: Issue the define_editor='your editor' statement from the SQL *PLUS prompt.
Q: What does the ed command in the SQLPLUS tool?
A: We use the "ed" command, to open your default word editor.
Q: Can you have multiple SQL statements in the afiedt.buf file?
A: No. You can only use one SQL statement at a time.
Q: How do you use the notepad editor as an independent tool in the SQLPLUS
utility?
A: Just open your notepad editor outside of your SQLPLUS.
Q: How do you execute or run a SQL script?
A: SQL> run c:\myscript.sql or start c:\myscript
Q: What is the SQL ANSI statement?
A: It is some standard roles that provided by American National Standards
Institute.
Q: What is the difference between the SQL ANSI statement and Original Oracle
statement?
A: The Original Oracle statements are not follow the role of American National
Standards Institute.
Q: Is the SET command a SQL statement?
A: No.
Q: How do you change your workstation’s page size or line size?
A: SQL > SET LINESIZE 100 PAGESIZE 55
Q: What does the JOIN syntax in the Oracle SQL (DML) statement?
A: It does innor join using the ON clause.
SQL > SELECT ename, dept.deptno, dname
FROM emp JOIN dept
ON emp.deptno = dept.deptno
AND dname <> 'SALES'
/
Q: What is the difference between the JOIN syntax and the NATURAL JOIN syntax?
A: In the NATURAL JOIN syntax, you don't need the ON clause if the column’s
names are the same.
Q: What does the USING clause in the Oracle SQL statement?
A: It joins two tables and in the USING clause the join column names must be
the same.
Q: What is the advantage of the NATURAL JOIN syntax?
A: It is less typing.
Q: What does the CROSS JOIN syntax in the Oracle SQL statement?
A: We can use the Oracle9i ANSI standard CROSS JOIN syntax with no WHERE
clause to create a Cartesian product .
Q: What does the IN clause in the Oracle SQL statement?
A: The IN clause in the Oracle SQL statement is an equivalent of the OR
condition in the SQL statement.
Q: What do the OUTER JOIN, RIGHT OUTER JOIN, LEFT OUTER JOIN, and FULL OUTER
JOIN syntax in the Oracle SQL statement?
A: We use the OUTER option when we want all records that have exact match plus
those records that have no match.
Q: How can you perform the FULL OUTER JOIN syntax using the Original Oracle
syntax?
A: Although it is possible but it is very difficult to perform the full outer
join using the original Oracle syntax.
Q: When do you use the WITH … AS clause in the SQL statement?
A: If we have a query which it needs to process the same sub-query several
times, we should consider using the WITH …AS clause in our statement.
Q: How does the WITH … AS clause help your performance?
A: The query will create a temporary table to query it over and over.
Q: Write a query to list all the department names that their total paid
salaries are more than 1/3 of the total salary of the company.
A: SQL > WITH summary_totals AS
(SELECT dname,
SUM (sal) AS totals
FROM emp NATURAL JOIN dept
GROUP BY dname)
SELECT dname, totals
FROM summary_totals
WHERE totals > (SELECT SUM(totals)*1/3
FROM summary_totals)
ORDER BY totals DESC
SQL >/
Q: What are the multiple columns in the SQL statement? Where or how do you use
them?
A: We use multiple columns to match the multiple columns returned from the
sub-query.
Q: Write a SQL statement to query the name of all employees who earn the
maximum salary in their department using the multiple columns syntax.
A: SQL > SELECT deptno, ename, job, sal
FROM emp
WHERE (deptno, sal) IN
(SELECT deptno, MAX (sal)
FROM emp
GROUP BY deptno)
/
Q: What is the inline view in the Oracle SQL statement?
A: If we have a sub-query in a FROM clause in the Oracle SQL statement, is
called an inline view.
Q: Write a SQL statement to query all of the employee names, jobs, and salaries
where their salary is more than 10% of the total company paid salary.
A: SQL > SELECT ename, job, sal
FROM (SELECT ename, job, sal
FROM emp
WHERE sal > (SELECT SUM (sal) * .1
FROM emp)
ORDER BY 3)
/
Q: What does the MERGE statement in the SQL statement?
A: We use the MERGE statement to merge one table into another table.
Q: Can you update, insert, or delete any records while you are using the MERGE
statement?
A: Yes.
Q: What is a Materialized View?
A: A materialized view (MVIEW) is a replica of a target master from a single
point in time.
Q: What are the Materialized View types?
A: Read-Only Materialized Views
Updatable Materialized Views
Sub-query Materialized Views
Row-id vs. Primary Key Materialized Views

SQL Interview Questions and Answers Part5

Q: What are the definitions of the following items?
COLUMN,
RECORD,
TABLE,
ITEM,
FIELD,
ELEMENT,
PRIMARY KEY,
FOREIGN KEY, and
DATATYPE.
A: A column is a smallest unit in a database that you need to deal with. A
record is a collection of columns and a table is a collection of records. The
terms: elements, columns, fields and items can be used interchangeably. A primary
key is a unique identifier in a table. A foreign key is a column in a table
(child) that references to a primary key column in another table (parent).
Relationships between two tables are normally established by defining primary or
foreign keys. A datatype is a format that an input data will be stored in a
column.
Q: What is the relationship between primary and foreign keys?
A: Relationships between two tables are normally established by defining
primary or foreign keys. It will establish a child and parent relationships. A
foreign key is a column in a table (child) that references to a primary key
column in another table (parent).
Q: Describe the Entity Relationship diagram and Logical Data Model.
A: "Entity Relationship Diagram" or "Logical Data Model" is used to establish
relationships between entities.
Q: What is a composite index?
A: If an index key or a primary key were composed of more than one column. We
call it a composite index.
Q: What are the responsibilities of an Oracle DBA and Oracle Developer?
A: The integrity, security, connectivity, performance, and tuning of a database
will be maintained by DBAs. One of the responsibilities of a DBA is to plan a
contingency for disaster and ensure recovery of the database. On the other hand
developers use front-end and back-end tools along with management tools to
perform their tasks. They develop applications to manipulate a database’s data.
Their application will query, insert, delete and update a record or records. They
use front-end tools such as "form builder," "report builder," and "graphics
builder." They use back-end tools such as "schema builder," "procedure builder,"
and "query builder." They use project builder tools to manage and deliver their
applications to their clients.
Q: What is a Database?
A: A collection of all tables under a single or many different schemas can be
stored and maintained in a database. A database, in effect, is a collection of
objects such as tables, indexes, stored procedures, etc.
Q: Query the employee names and their salaries from the employee table.
A: SQL > SELECT ename, sal FROM emp;
Q: Do the above query and use an “as” clause for the “salary” column aliases orcolumn headings.
A: SQL > SELECT ename, sal AS salary FROM emp;
Q: Repeat the previous query and have “Full Name” for the ename’s column
heading and “Salary” for the “sal” column heading.
A: SQL > SELECT ename “Full Name”, sal "Salary"
FROM emp;
Q: What is the result of 100 + NULL ?
A: NULL.
Q: Query the employee names with their commissions.
A: SQL > SELECT ename, comm commission FROM emp;
Q: Use the (NVL ) the null value function to assign zero to any null value in
the commission column for the previous query.
A: SQL > SELECT ename, NVL(comm,0) commission
FROM emp;
Q: Concatenate the customers’ last name and first name separated by comma.
A: SQL > SELECT last_name || ', ' || first_name AS "full name"
FROM customers;
Q: Query the employees name sorted by ascending order.
A: SQL > SELECT ename
FROM emp
ORDER BY ename ASC;
Q: Query the employees name sorted by descending order.
A: SQL > SELECT ename FROM emp
ORDER BY ename DESC;
Q: Query the employee information whose employee number is 7788.
A: SQL > SELECT *
FROM emp
WHERE empno = 7788;
Q: Query the employees name whose names start with the letter “M.”
A: SQL > SELECT ename
FROM emp
WHERE ename LIKE 'M%';
Q: Query the employees name whose names end with the letter “R.”
A: SQL > SELECT ename
FROM emp
WHERE ename LIKE '%R';
Q: Query the employees name whose salaries between 2000 and 3000 dollars.
A: SQL > SELECT ename
FROM emp
WHERE sal BETWEEN 2000 AND 3000;
Q: Query the employees name and their department name using the “DECODE”
function. If the department number is 10 then print "accounting.” If the
department number is 20 then print "research," or if the department number is 30
then print "sales." Anything else prints others.
A: SQL > SELECT ename, DECODE (deptno, 10, 'Accounting',
20,
'Research',
30,
'Sales',
'Others') AS "Department"
FROM emp;
Q: What is an ambiguous column?
A: An ambiguous column is a column that is not defined clearly. Having two
tables with the same column name, you should reference them such that there is noambiguity on their ownerships.
Q: How can you resolve an ambiguous column problem?
A: The column name should be identified by alias to make it clear that to what
table that column is belong.
Q: What is a Cartesian product?
A: A “Cartesian” product is caused by joining “N” number of tables while you
have less than “N-1” joins condition in the query.
Q: How can you avoid a Cartesian product ?
A: To avoid it, just when joining “N” number of tables you should have more or
equal “N-1” joins condition in the query.
Q: What is an inner join or equi-join?
A: Joining two or more tables together using the WHERE clause with the equal
sign (=) in a query. This type of query will retrieve records that have exact
match and will be called inner join or equi-join.
Q: What is an outer join?
A: Joining two or more tables using OUTER join, not only you retrieve all
matching records but also you retrieve the records that do not match.
Q: What is a self join?
A: When a table refers to itself in the WHERE clause, we call that join is a
self-join.
Q: Query all the employee names and their department including all the
departments with no employees.
A: SQL > SELECT ename, dname
FROM emp e, dept d
WHERE e.deptno (+) = d.deptno;
Q: Query the managers’ name with their employees sorted by the manager name.
A: SQL > SELECT mgr.ename “Manager Name”, e.ename “Employee Name”
FROM emp mgr, emp e
WHERE mgr.empno = e.mgr
ORDER BY mgr.ename;
Q: Query the department number and their total, average, min, and max salaries
for each department.
A: SQL > SELECT deptno, SUM(sal), AVG(sal), MIN(sal), MAX(sal)
FROM emp
GROUP BY deptno;
Q: Query the department no and their total salaries that have more than 5
employees working in their department.
A: SQL > SELECT deptno, SUM(sal)
FROM emp
GROUP BY deptno
HAVING count(*) > 5;
Q: Query the employees name that work for the Research or Sales department (the
department number 20 or 30).
A: SQL > SELECT ename, deptno
FROM emp
WHERE deptno IN (20, 30);
Q: Query the employees name that work in the "accounting" department. Assuming
the department number is unknown.
A: SQL > SELECT ename
FROM emp
WHERE deptno IN
(SELECT deptno
FROM dept
WHERE dname = "ACCOUNTING");
Q: Query the employees name and use the runtime variable to substitute the
department number? Then run it for following department no 10, 20, and 30.
A: SQL > SELECT ename
FROM emp
WHERE deptno = &deptno;
SQL > /
Q: Query the customer names which have more than four orders.
A: SQL > SELECT name
FROM customer c
WHERE exists
(SELECT 'T'
FROM ord
WHERE custid = c.custid
GROUP BY custid
HAVING count(*) > 4);
Q: Create an employee table that contains five columns:
Such as Employee Id, last name, First name, Phone number and Department number
with the following constraints.
The last name and first name should be not null.
Make a check constraint to check the department number is between 9 and 100.
Make a primary constraint on the employee ID column.
Make a foreign key on the department number column.
Use the "delete cascade" to delete all records if parent gets deleted.
Use the "phone number" as a unique key.
A: SQL > CREATE TABLE employee
(empid NUMBER(10),
lastname VARCHAR2(20) not null,
firstname VARCHAR2 (20) not null,
phone_no VARCHAR2 (15),
deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),
constraint pk_employee_01 PRIMARY KEY (empid),
constraint fk_dept_01 FOREIGN KEY (deptno)
references dept (deptno) ON DELETE CASCADE,
constraint uk_employee_01 UNQUE (phone_no));
Q: Create a composite index on the employee table that contains two index
columns (last name and first name).
A: SQL > CREATE INDEX employee_lname_fname_ind_01
ON employee (lastname, firstname);
Q: Query the tables that you as a user own.
A: SQL > SELECT table_name
FROM user_tables
ORDER BY table_name;
Q: Query the index tables that belong to the employee table and owns by the
iself user.
A: SQL > SELECT index_name, uniqueness
FROM user_indexes
WHERE table_name = 'EMPLOYEE';
Q: Change the size of the "column_name" to 30 characters logically (for display
only).
A: SQL > COLUMN column_name FORMAT a30
Q: Query the indexes columns of the employee table.
A: SQL > SELECT index_name, column_name, column_position
FROM user_ind_columns
WHERE table_name = 'EMPLOYEE';
Q: Insert a record into the "employee" table using column names.
A: SQL > INSERT INTO employee
(empid, lastname, deptno, firstname, phone_no)
VALUES (100, 'smith', 10,'joe', ‘7038212211');
Q: Insert a record using the column position format.
A: SQL> INSERT INTO employeeVALUES (200, 'KING', 'Allen', 5464327532, 10);

SQL Interview Questions and Answers Partt4

                                                     
                                                                    
                                                                    
                                            
1) backup database incremental level 0, what are the files will be part of the backupset?
  Datafiles and control files.
  

2) What does crosscheck command does?
Updates the catalog whether the piece does exist or not.

3) steps to clone a db using Rman? also suppose source and target directory structures are different? how would you proceed further
  
 a) take a full backup of the database
 b) move the backups to the dev server (Make sure you move to the same file-system as in Source database)
 c) create the auxiliary instance by specifying the required parameter values.
 d) Then run the below duplicate command by connecting to target as well as auxiliary database:
           rman nocatalog target monitor@TFSSG_SGDC01APUX001-TFSPROD1 auxiliary/
           run{
           set until time "TO_DATE('11/06/09 06:05','MM/DD/YY HH24:MI')";
           duplicate target database to tfsprod1 nofilenamecheck; }

    If there are different directory structure, then use DB_FILE_NAME_CONVERT and LOG_FILE_NAME_CONVERT accordingly........
          
 

4) Improving the performance of an Rman backup

  a) Use multiple channels
  b) use block change tracking feature
  c) enable the backups during non bussiness hours

5) What is the purpose of VIP

   VIp (Virtual IP address) which gets switched over to another node during the failure of active node. The concept of VIP comes in the clustered servers (Eg : VCS)
   The advantage is user gets connected to the passive node with less down time.

6) 10 Db's on a RAC server, want to find what db's are running. What commands do u use

  $CRS_HOME/bin/srvctl status database -d <name>

7) Steps to set up a data guard

   a) Take a backup of the database
   b) backup of the control file and pfile too
   c) Move the backups to the DR server.
   d) configure the following parameters db_file_name_convert, log_file_name_convert, standby_file_management, standby_archive_dest, fal_server and fal_client
   e) Startup nomount and alter database mount standby database
   f) Enabled managed recovery -----> alter database recover managed standby database cancel;
   g) To ensure that the DR is in managed recovery fire this command ----> select process,sequence#,status,blocks,block# from v$managed_standby;
   i) To ensure the DR is in sync with the primary fire the below query
   
    Get the current log sequence of the primary and at the standby site execute this command select max(sequence#),thread# from v$log_history group by thread#; 


8) U want to refersh a dev database with a production db, due to file-system naming mismatch between prod and dev, how would you move the backup pieces and
    recover the db?

   1 method:

   a) Take the backup of the database.  
   b) Move the backup pieces to the develeopment server by creating soft links, so that the location between the prod and develeopment server looks similar
   c) startup the db in nomount stage
   d) duplicate the database as specified in question 3

  2 method

   a) Take the backup of the database
   b) move the backup pieces to some location on the development server
   c) startup the db in nomount stage
   d) At the Rman prompt create the control file -------> restore controlfile from 'location of the piece containing the control file';
   e) bring the db to mount state -------> alter database mount;
   f) Again at the Rman prompt catalog the backup pieces in the control file -------> catalog start with 'location of the backup pieces';
   g) after cataloging fire ----> restore database and recover database.... use the below command

      rman > run { restore database ; recover database ; }

11) Apps team require a tablespace to be created OF a non standard block size, hoe would you configure

Define a parameneter db_nk_block_size used to store the blocks of non default size in the buffer cache..... after configuring this parameter create a tablespace of the specified block size.....


13) If a data file is added at the primary site, how the change will be reflected at the DR site

If the standby_file_management parameter is set to AUTO then the datafile gets created automatically at the DR site else we need to create manually....

14) Index is being rebuilt at the primary site with no logging option, whatz the effect at the DR site.

Cause a logical corruption at the DR site.... hence we need to rebuild the DR database.......

15) How do you identify and resolve gap sequences at the DR site

Use v$archive_gap and v$archived_log and v$log_history to see the archive gap..... if the archive logs are missing at the primary site then try to restore the archive logs so that the DR will catch up with those archive logs.......

16) What is FAL_SERVER and FAL_CLIENT parameter. What is the advantage of setting the same parameter at the primary site

FAL_SERVER ---> specifies the location of the primary server
FAL_CLIENT ----> specifies the location of the DR site...... basically these parameters are configures to resolve the gaps automatically......

The adavantage of setting this parameter at the primary site is for the ease of siwtchover and switch back....... nothing more.......

17) Difference between Datapump and conventional export/import

    a) Run the export in parallel.... can also increase the parallel threads on the fly....
    b) stop the export and imporrt at will and then restart the job.
    c) The staus of the expdp/impdp is transparent to the user...... just attach the job and we will get to know the status of the job
    d) Filter of the objects is much user friendly..
    e) server side utility.
    f) Over the db link we can import the data without actually creating the export dump ----> network_link is the parameter that is used
    g) without actaully performing the export we can get to know the size of the dump....

18) How do you identify whether the DB is primary or a standby database?

select controlffile_type from v$database;

If primary then it is a primary database
If standby then it is a standby database

19) Standby database is lagging by 100 logs, how do you fix to get the DR in sync with the primary

check if we can restore the archivelogs at the primary site...... unfortunately if the archivelogs are not in the backup, then we need to apply the incremental backups to the standby database to get the DR in sync with the primary.....

Applying the incremental backup's is a new feature of 10g.... the main advantage of this feature is we can get the DR in sync pretty fast rather than rebuilding the entire database which is a time consuming task....

20) What is Ora-01555

Snapshot too old....... meaning -----> when the read consistent data is being over written by another active session, then is such situations the user who is getting a read consistent data will be prompted with the error message ----> ORA-01555

Remedy----- > increase the undo tablespace as well as undo_retention parameter


21) How do you remove the shared memory segment from the operating system

ipcs -rm

22) What is FRA feature

Flash recovery area used to store the Rman backup's as well as falsh back logs so that we can flash back the database to a particular time....

PArameters configured to enable FRA is --> db_recovery_file_dest and  db_recovery_file_dest_size and db_recovery_retention_period......

23) What is Flash back database

Flash back database is a kinda rolling back the database using Flash back logs...... New feature in 10G

24) How do you check the max sequence# applied at the DR site

    a) select max(sequence#),thread# from v$log_history group by thread#;
    b) check the alert log file

25) Parameters configured at the Primary/DR site in a Dataguard Environment

PRIMARY SITE ----> log_archive_dest_2, db_unique_name
DR SITE -----> FAl-SERVER, FAL_CLIENT, STANDBY_FILE_MANAGEMENT, STANDBY_ARCHIVE_DEST, DB_FILE_NAME_CONVERT, LOG_FILE_NAME_CONVERT

26) How do you check the load on a server

use the below OS commands
   top ----> In Linux
   /usr/ucb/ps aux | more ----> In Sun OS
   prstat  ---- > In Sun OS


  
27) Archive dest is configured in the FRA, how do u clear the same when the destination is full

  a) increase the FRA size at first instance to avoid outage of the database...
  b) If the archivelogs are backed up and also if the same has been applied in the DR (If configured), then remove the old archivelogs using RMAN

 Rman ;> delete archivelog all completed before (sysdate -1);

28) What is TAF

Transparent application fail over.... where the session gets failed over to the available instance in case of RAC

29) U wanna do some maintanence on a RAC cluster database... what are the steps to bring down the CRS resources

  $CRS_HOME/bin/srvctl crs_stat -t to see the services that are currently running.....

    a) $CRS_HOME/bin/srvctl stop database -d <db_name>
    b) $CRS_HOME/bin/srvctl stop service - d <db_name>
    c) $CRS_HOME/bin/srvctl stop asm -n <node_name>  (To get the node names in cluster fire this command $CRS_HOME/bin/srvctl olsnodes)
    d) $CRS_HOME/bin/srvctl stop nodeapps -n <node_name>
    e) As root user stop the CRS stack -----> crsctl stop crs

30) FRA is 100%, how wuld u fix the issue

Increse the db_recovery_file_dest_Size parameter

31) At the OS level how wuld u find the CPU usage

   To see the CPU idleness ------>   sar 10 10

32) How would u check whether the standby database is in managed recovery mode

select process,sequence#,status,blocks,block# from v$managed_stqandby;

33) Datafile is corupted, how to fix it

Try to recover the corrupted block throo block media recovery..... at the worst case try to restore the datafile and recover it.....

34) Steps to upgrade a DB from 9i to 10G

35) what is a nodeapps

Sunday 26 August 2012

ETL Testing life cycle

ETL testing require manual testing steps and testers who understand the basic of an ETL Tool, Database,SQL, basic UNIX commands etc., following are the various phases typically followed in ETL Testing.

Requirement Understanding:-

- Review BRD, Technical specification document and data mapping document.
- Attend Technical Specification Walk throughs
- Work with business analyst and understand the structure, usage of source data.
- Identify all the issues and work with business analyst to clarify the data related issues mapping issues data transformation logic's etc., and make sure that there are no gaps.

Test Plan:-

- Test Estimation
- Preparation of test cases with all the test scenarios possible.
- Review the test cases with Business Analust.

Test Data Creation:-

- Understand the structure of source data.
- Make sure that all the tables are updated with referential data if the source or target data is in one or more tables.
- Ensure that the test data is created in all the associated tables ofter thoroughly understandling the data model.

Test case Execution and Test Results Reporting :-

- Run the ETL application jobs.
- Check the target data and structure and make sure that the data is complete and valid for test.
- Write simple to complex SQL Queries to check the expected results when the data sources is in multiple tables.
- Check the ETL tool logs for the abnormal termination error causes.
- Work closely with the developers and business analyst for all the testing related issues.
- document the test metrics with number of test cases, no of defects, source of each defect etc., for each test cycle


SQL Interview Questions and Answers Part3


SELECT COUNT(column_name)
FROM user_tab_columns
WHERE table_name = 'MYTABLE';


dbms_output.enable(4000);  /*allows the output buffer to be increased to the specified number of bytes */


DECLARE
BEGIN
dbms_output.enable(4000);
FOR i IN 1..400
LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
/


Set the following to some other character. By default it is &.

set define '~'

44.  How do you remove Trailing blanks in a spooled file :
Change the Environment Options Like this :
set trimspool on
set trimout on


Sample :1
CREATE OR REPLACE PROCEDURE CNT(P_TABLE_NAME IN VARCHAR2)
AS
SqlString VARCHAR2(200);
tot number;
BEGIN
SqlString:='SELECT COUNT(*) FROM '||  P_TABLE_NAME;
EXECUTE IMMEDIATE SqlString INTO tot;
DBMS_OUTPUT.PUT_LINE('Total No.Of Records In ' || P_TABLE_NAME || ' ARE=' || tot);
END;

Sample :2
DECLARE
            sql_stmt VARCHAR2(200);
            plsql_block VARCHAR2(500);
            emp_id NUMBER(4) := 7566;
            salary NUMBER(7,2);
            dept_id NUMBER(2) := 50;
            dept_name VARCHAR2(14) := ’PERSONNEL’;
            location VARCHAR2(13) := ’DALLAS’;
            emp_rec emp%ROWTYPE;
BEGIN
            EXECUTE IMMEDIATE 'CREATE TABLE bonus (id NUMBER, amt NUMBER)';

            sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';
            EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;

            sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
            EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;

            plsql_block := 'BEGIN emp_pkg.raise_salary(:id, :amt); END;';
            EXECUTE IMMEDIATE plsql_block USING 7788, 500;

            sql_stmt := 'UPDATE emp SET sal = 2000 WHERE empno = :1
            RETURNING sal INTO :2';
            EXECUTE IMMEDIATE sql_stmt USING emp_id RETURNING INTO salary;

            EXECUTE IMMEDIATE 'DELETE FROM dept WHERE deptno = :num'
            USING dept_id;

            EXECUTE IMMEDIATE ’ALTER SESSION SET SQL_TRACE TRUE’;
END;

Sample 3
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
              v_cursor integer;
              v_dname  char(20);
              v_rows   integer;
            BEGIN
              v_cursor := DBMS_SQL.OPEN_CURSOR;
              DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x', DBMS_SQL.V7);
              DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
              DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
              v_rows := DBMS_SQL.EXECUTE(v_cursor);
              LOOP
                IF DBMS_SQL.FETCH_ROWS(v_cursor) = 0 THEN
                   EXIT;
                END IF;
                DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
                DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
              END LOOP;
              DBMS_SQL.CLOSE_CURSOR(v_cursor);
            EXCEPTION
              WHEN OTHERS THEN
                   DBMS_SQL.CLOSE_CURSOR(v_cursor);
                   raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||sqlerrm);
END;


Difference 1:
            Oracle : select name from table1 where name like 'k%';
            Access: select name from table1 where name like 'k*';
Difference 2:
            Access: SELECT  TOP 2 name FROM Table1;
            Oracle : will not work there is no such TOP key word.


SELECT organization_id,name
FROM hr_all_organization_units
WHERE organization_id in
(
SELECT ORGANIZATION_ID_CHILD FROM  PER_ORG_STRUCTURE_ELEMENTS
CONNECT BY PRIOR
ORGANIZATION_ID_CHILD = ORGANIZATION_ID_PARENT
START WITH
ORGANIZATION_ID_CHILD = (SELECT organization_id
FROM hr_all_organization_units
WHERE name =  'EBG Corporate Group'));


CREATE OR REPLACE PROCEDURE read_data
AS
c_path             varchar2(100) := '/usr/tmp';
c_file_name     varchar2(20)  := 'EKGSEP01.CSV';
v_file_id           utl_file.file_type;
v_buffer           varchar2(1022) := This is a sample text’;
BEGIN
v_file_id := UTL_FILE.FOPEN(c_path,c_file_name,'w');
UTL_FILE.PUT_LINE(v_file_id, v_buffer);
UTL_FILE.FCLOSE(v_file_id);

v_file_id := UTL_FILE.FOPEN(c_path,c_file_name,'r');
UTL_FILE.GET_LINE(v_file_id, v_buffer);
DBMS_OUTPUT.PUT_LINE(v_buffer);
UTL_FILE.FCLOSE(v_file_id);
END;
/


SELECT DBMS_RANDOM.VALUE (1,2) FROM DUAL;


SELECT
       FLOOR((date1-date2)*24*60*60)/3600)
       || ' HOURS ' ||
       FLOOR((((date1-date2)*24*60*60) -
       FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60)
       || ' MINUTES ' ||
       ROUND((((date1-date2)*24*60*60) -
       FLOOR(((date1-date2)*24*60*60)/3600)*3600 -
       (FLOOR((((date1-date2)*24*60*60) -
       FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60)*60)))
       || ' SECS ' time_difference
FROM   my_table;


I have this string in a column named location

LOT 8 CONC3 RR

Using instr and substr, I want to take whatever value follows LOT and put
it into a different column and whatever value follows CONC and put it into
a different column


select substr('LOT 8 CONC3 RR',4,instr('LOT 8 CONC3 RR','CONC')-4) from
dual;

select substr('LOT 8 CONC3 RR',-(length('LOT 8 CONC3 RR')-(instr('LOT 8
CONC3 RR','CONC')+3)))
from dual


select text from all_source where name = 'X'
order by line;
select text from user_source where name = 'X'
select text from user_source where type = 'procedure' and
name='procedure_name';
select name,text from dba_source where name='ur_procedure'
and owner='scott';


select  to_number('-999,999.99', 's999,999.99')  from dual;               -999,999.99
select  to_number('+0,123.45', 's999,999,999.99')  from dual;           123.45
select  to_number('+999,999.99', 's999,999.99')  from dual;  999,999.99


select column_name from user_tab_columns where TABLE_NAME = 'EMP'
select column_name from all_tab_columns where TABLE_NAME = 'EMP'
select column_name from dba_tab_columns where TABLE_NAME = 'EMP'
select column_name from cols where TABLE_NAME = 'EMP'

I have a table have
a,b,c field,

a,b should be unique, and leave max(c) row in.
How can I delete other rows?

delete from 'table'
where (a,b,c)  not in (select a,b,max(c) from 'table' group by a,b);

56. CLOB to Char                              

1)  This function helps if your clob column value not exceed 4000 bytes
(varchar2 limit).if clob column's data exceeds 4000 limit, you have to
follow different approach.

 create or replace function lob_to_char(clob_col clob) return varchar2 IS
 buffer  varchar2(4000);
 amt                 BINARY_INTEGER := 4000;
 pos                  INTEGER := 1;
 l   clob;
 bfils    bfile;
 l_var   varchar2(4000):='';
 begin
  LOOP
              if dbms_lob.getlength(clob_col)<=4000 THEN
                            dbms_lob.read (clob_col, amt, pos, buffer);
                           l_var := l_var||buffer;
                           pos:=pos+amt;
              ELSE
                 l_var:= 'Cannot convert to varchar2..Exceeding varchar2 field
limit';
/
                   exit;
     END IF;
  END LOOP;
 return l_var;
 EXCEPTION
             WHEN NO_DATA_FOUND THEN
   return l_var;
 END;


2) CREATE GLOBAL TEMPORARY TABLE temp_tab(id number,varchar_col
varchar2(4000));

SQL> var r refcursor
SQL> exec lobpkg.lob_to_char(:r);
SQL> print r

create or replace package lobpkg is
type ref1 is ref cursor;
n number:=0;
PROCEDURE lob_to_char(rvar IN OUT lobpkg.ref1) ;
end;
/

create or replace package body lobpkg is

PROCEDURE lob_to_char(rvar IN OUT lobpkg.ref1) IS
buffer               varchar2(4000);
amt             BINARY_INTEGER := 4000;
pos              INTEGER := 1;
l                       clob;
r lobpkg.ref1;
bfils                 bfile;
l_var                varchar2(4000):='';
CURSOR C1 IS SELECT * FROM clob_tab;
-- change clob_tab to your_table_name
begin
n:=n+1;
FOR crec IN c1 LOOP
amt:=4000;
pos:=1;
BEGIN
            LOOP

--change crec.clob_col to crec.your_column_name

                                    dbms_lob.read (crec.clob_col, amt, pos, buffer);

--change next line if you create temporary table with different name

                                    insert into temp_tab values (n,buffer);

                                    pos:=pos+amt;
 
                       
            END LOOP;
EXCEPTION
            WHEN NO_DATA_FOUND THEN
                        NULL;
END;
END LOOP;
--change next line if you create temporary table with different name
open rvar for select vchar from temp_tab where id=n;
                       
END;
END;

57. Change Settings

Open file oracle_home\plus32\glogin.sql and
add this
set linesize 100
set pagewidth 20
and save the file
and exit from sql and reload then it will set it.


 declare
  -- we need one here to get a single quote into the variable
 v_str varchar2 (20) := 'O''reilly''s';
 begin
   DBMS_OUTPUT.PUT_LINE ( 'original single quoted v_str= ' || v_str );
   v_str := replace(v_str, '''', '''''');
   DBMS_OUTPUT.PUT_LINE ( 'after double quoted v_str= ' || v_str );
 end;
SQL> /
original single quoted v_str= O'reilly's
after double quoted v_str= O''reilly''s


CREATE OR REPLACE FUNCTION to_hms (i_days IN number)
   RETURN varchar2
IS
BEGIN
   RETURN TO_CHAR (TRUNC (i_days)) &#124&#124 ' days ' &#124&#124
                         TO_CHAR (TRUNC (SYSDATE) + MOD (i_days, 1), 'HH24:MI:SS');
END to_hms;

select to_hms(to_date('17-Jan-2002 13:20:20', 'dd-Mon-yyyy hh24:mi:ss') -
       to_date('11-Jan-2002 11:05:05', 'dd-Mon-yyyy hh24:mi:ss')) from
dual;

The table in both the schemas should have exactly the same structure. The data in
it could be same or different

a-b and b-a

select *   from a.a minus  select *  from b.a  and  select *   from b.a minus select *   from a.a


select * from user_jobs;
exec dbms_job.remove(job_no);

62. Switching Columns
Update tblname
Set  column1 = column2,
      Column2 = column1;

I have the number e.g. 63,9823874012983 and I want to round it to 63,98 and at the same time change the , to a .

select round(replace('63,9823874012983',',','.'),2) from dual;

64. First date of the year
select trunc(sysdate, 'y') from dual;

01-jan-2002

last year this month through a select statement
select add_months(sysdate, -12) from dual;
05-APR-01

65. Create Sequence
create sequence sh increment by 1 start with 0;

66. Cursors
cursor is someting like pointers in C language.
u fetch the data using cursor.( wiz...store it somewhere temporarily). u
can do any manipulation to the data that is fetched by the cursor. like
trim, padd, concat or validate. all this are done in temporary areas called
as context area or the cursor area. u can insert this data again in some
other table or do anything u want!!...like setting up some flags etc.
U can display the contents of cursor using the dbms_output only. U can
create an anonymous plsql block or a stored procedure. the major advantage
of cursors is that you can fetch more thatn one row and u can loop through
the resultset and do the manupulations in a secure manner.

set serveroutput on;
declare
cursor c1 is select * from emp;
begin
for var in c1 loop
exit when c1%notfound;
dbms_output.put_line('the employee' &#124&#124 var.ename &#124&#124'draws a
salary of '&#124&#124 var.sal);
end loop;
end;


select next_day(sysdate-7,'SUNDAY'), next_day(sysdate,'SATURDAY') from dual;

NEXT_DAY( NEXT_DAY(
--------- ---------
07-APR-02 13-APR-02