Sunday, March 11, 2012
HOW PL/SQL GETS EXECUTED
the PL/SQL engine on the server where it is compiled. The named PL/SQL
block is compiled only at the time of its creation, or if it has been
changed. The compilation process includes syntax checking, binding,
and p-code generation.
Oracle guarantees a read-consistent view
of the data. Until that point, all data that has been inserted or updated
will be held in memory and only be available to the current user. The
rows that have been changed will be locked by the current user and will
not be available for updating to other users until the locks have been re-leased.
Wednesday, March 7, 2012
Wednesday, February 1, 2012
Nth Highest Salary in Oracle
First things first: The question is ambiguous!
Let’s say this is your data:
| Name | Salary |
| KING | 5000 |
| FORD | 3000 |
| SCOTT | 3000 |
| JONES | 2975 |
| BLAKE | 2850 |
| CLARK | 2850 |
| ALLEN | 1600 |
Who is second – FORD or SCOTT or both?
What will you say about JONES’s salary – is it the 3rd highest salary, or the 4th highest?
If you are looking for the set of people earning the Nth highest salary, with no gaps in case of ties, then JONES should be ranked 3rd, after KING [5000, 1st], followed by FORD and SCOTT [both 3000, 2nd].
If you are looking for exact ranks with gaps if there are ties, then JONES is the 4th highest paid employee, as there are 3 people earning more than him – KING, FORD and SCOTT. In this system of ranking, FORD and SCOTT are 2nd jointly and no employee is 3rd.
This is how your ranks will look, in the 2 cases:
|
Scenario 1: No gaps in case of ties Scenario 2: Gaps in case of ties
Once you have your question sorted out -
(a) Set of people earning the Nth highest salary, with continuous ranks if there are ties, OR
(b) Set of people earning the Nth highest salary, with skipped rank numbers if there are ties
Then you can proceed to writing the queries.
Scenario 1: DENSE_RANK () for Nth highest row, no gaps in case of ties
The analytic function dense_rank() will rank the rows with no gaps in ranking sequence if there are ties.
The ranks are calculated as: SQL> select ename
2 ,sal 3 ,dense_rank() over (order by sal desc) ranking 4 from emp; ENAME SAL RANKING ---------- ---------- ---------- KING 5000 1 FORD 3000 2 SCOTT 3000 2 JONES 2975 3 CLARK 2850 4 BLAKE 2850 4 ALLEN 1600 5
Wrap a filter around and pick out the Nth highest salary, say the 4th highest salary.
SQL> select *
2 from 3 ( 4 select ename 5 ,sal 6 ,dense_rank() over (order by sal desc) ranking 7 from emp 8 ) 9 where ranking = 4 -- Replace 4 with any value of N 10 / ENAME SAL RANKING ---------- ---------- ---------- BLAKE 2850 4 CLARK 2850 4
The 4th position has a tie between BLAKE and CLARK.
Scenario 2: RANK () for Nth highest row, gaps in case of ties
The analytic function rank() will rank the rows with gaps in ranking sequence if there are ties.
The ranks are calculated as:
SQL> select ename
2 ,sal 3 ,rank() over (order by sal desc) ranking 4 from emp; ENAME SAL RANKING ---------- ---------- ---------- KING 5000 1 FORD 3000 2 SCOTT 3000 2 JONES 2975 4 CLARK 2850 5 BLAKE 2850 5 ALLEN 1600 7 TURNER 1500 8
Wrap a filter around and pick out the Nth highest salary, say the 4th highest salary.
SQL> select *
2 from 3 ( 4 select ename 5 ,sal 6 ,rank() over (order by sal desc) ranking 7 from emp 8 ) 9 where ranking = 4 -- Replace 4 with any value of N 10 / ENAME SAL RANKING ---------- ---------- ---------- JONES 2975 4
A different answer from the previous query, as there is no rank 3 because of the tied 2nd place.
Closing Notes
The requirement to “find Nth highest row” is incomplete, until the following questions are also answered:
- Can the result match more than one value? If not, on what basis should the one record be chosen if there is a tie?
- How should the subsequent records be ranked in case of ties – contiguously or with gaps?
Depending on the answer for (2), DENSE_RANK (for contiguous) or RANK (for gaps) can be used. Depending on the answer for (1), extra filter criteria can be applied to the SQL.
There are other approaches for calculating the Nth highest row, too. The next is a non-analytic approach, which works the same way as the RANK query (gaps for ties).
SQL> select ename 2 , sal 3 from emp a 4 where 3 = ( select count(*) -- Replace 3 with any value of (N - 1) 5 from emp b 6 where b.sal > a.sal) 7 / ENAME SAL ---------- ---------- JONES 2975
However, tests have shown the analytics approach to be more efficient than the non-analytics one for Nth highest or Top-N type of queries.
sample SQL
SQL constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
MySQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)
add UNIQUE
ALTER TABLE Persons
ADD UNIQUE (P_Id)
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE Persons
DROP INDEX uc_PersonID
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID
.... to be continued
SQL syntax
SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).
The query and update commands form the DML part of SQL:
- SELECT - extracts data from a database
- UPDATE - updates data in a database
- DELETE - deletes data from a database
- INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also defines indexes (keys), specifies links between tables, and imposes constraints between tables. The most important DDL statements in SQL are:
- CREATE DATABASE - creates a new database
- ALTER DATABASE - modifies a database
- CREATE TABLE - creates a new table
- ALTER TABLE - modifies a table
- DROP TABLE - deletes a table
- CREATE INDEX - creates an index (search key)
- DROP INDEX - deletes an index
WHERE City LIKE '%tav%'
WHERE City NOT LIKE '%tav%'
SQL Alias Syntax for Tables
FROM table_name
AS alias_name
SQL Alias Syntax for Columns
FROM table_name
Different SQL JOINs
Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.
- JOIN: Return rows when there is at least one match in both tables
- LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
- RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
- FULL JOIN: Return rows when there is a match in one of the tables
----------
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
UNION
SELECT column_name(s) FROM table_name2
UNION ALL
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
create tables
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
CREATE a table from another table
AS (SELECT * FROM old_table);
CREATE TABLE suppliers
AS (SELECT *
FROM companies
WHERE id > 1000);
This would create a new table called suppliers that included all columns from the companies table.
CREATE TABLE suppliers
AS (SELECT companies.id, companies.address, categories.cat_type
FROM companies, categories
WHERE companies.id = categories.id
AND companies.id > 1000);
This would create a new table called suppliers based on columns from both the companies and categories tables.
create a table from another table without copying any values from the old table?CREATE TABLE new_table
AS (SELECT * FROM old_table WHERE 1=2);
find duplicated records
find 5th highest salary
Monday, January 30, 2012
Database management interview questions
1. What is a Cartesian product? What causes it?
Expected answer:
A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join. It is causes by specifying a table in the FROM clause without joining it to another table.
2. What is an advantage to using a stored procedure as opposed to passing an SQL query from an application.
Expected answer:
A stored procedure is pre-loaded in memory for faster execution. It allows the DBMS control of permissions for security purposes. It also eliminates the need to recompile components when minor changes occur to the database.
3. What is the difference of a LEFT JOIN and an INNER JOIN statement?
Expected answer:
A LEFT JOIN will take ALL values from the first declared table and matching values from the second declared table based on the column the join has been declared on. An INNER JOIN will take only matching values from both tables
4. When a query is sent to the database and an index is not being used, what type of execution is taking place?
Expected answer:
A table scan.
5. What are the pros and cons of using triggers?
Expected answer:
A trigger is one or more statements of SQL that are being executed in event of data modification in a table to which the trigger belongs.
Triggers enhance the security, efficiency, and standardization of databases.
Triggers can be beneficial when used:
– to check or modify values before they are actually updated or inserted in the database. This is useful if you need to transform data from the way the user sees it to some internal database format.
– to run other non-database operations coded in user-defined functions
– to update data in other tables. This is useful for maintaining relationships between data or in keeping audit trail information.
– to check against other data in the table or in other tables. This is useful to ensure data integrity when referential integrity constraints aren’t appropriate, or when table check constraints limit checking to the current table only.
6. What are the pros and cons of using stored procedures. When would you use them?
7. What are the pros and cons of using cursors? When would you use them?