Sunday, 25 December 2016

Oracle PL/SQL Records

PL/SQL Records
A PL/SQL record is a collection of basic types of data and can be accessed as a single unit.

PL/SQL records are similar in structure to a row in a database table.

A record consists of components of any scalar, PL/SQL record, or PL/SQL table type.

It makes your life easier by transferring the entire row into a record, rather than transferring each column into a variable separately.

PL/SQL supports three kinds of records:
Important points on records

1. Individual fields are referenced via dot notation:

record_name.field_name

Example:

Emp_rec.first_name

2. Individual fields within a record can be read from or written to. They can appear on either the left or right side of the assignment operator:

BEGIN
policy_start_date:= new_emp_rec.hire_date + 30;
new_emp_rec.present:= FALSE;

3. An entire record can be assigned to another record of the same type.

However the assignment can fail, if you do not conform to these rules:
  • Both cursor-based records in a collective assignment must be based on the same cursor.
  • Both table-based records in a collective assignment must be based on the same table.
  • Both programmer-defined records in a collective assignment must be based on the same TYPE...RECORD statement.
4.Records cannot be compared, rather their field can be.

Difference between Views & Materialized views

Materialized views are disk based and update periodically base upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

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.

ACID Properties

A transaction consists of set of operations that perform a single logical unit of work in a database environment. It may be an an entire program, or part of it or a single SQL Command and it may involve any number of operations on the database. If the transaction is completely successfully, then the database moves from one consistent state to another.

Four properties of a transaction are:

Atomicity: A transaction is regarded as a single logical unit of work in the database rather than collection of separate operations.So, only when all the separate operations succeed does a transaction succeed and is committed to the database. On the other hand, if a single operation fails during the transaction, everything is considered to have failed and must be undone (rolled back) if it has already taken place. In the case of the order-entry system of the Northwind database, when you enter an order into the Orders and Order Details tables, data will be saved together in both tables, or it won’t be saved at all.

Atomicity is maintained in the presence of deadlocks, database software failures, application software failures, CPU failures, disk failures. Atomicity can be turned off at the system level or the session level.

Consistency: The transaction should leave the database in a consistent state — whether or not it completed successfully.In the case of Northwind, you can’t have rows in the Order Details table without a corresponding row in the Orders table, as this would leave the data in an inconsistent state.

Isolation: Every transaction has a well-defined boundary—that is, it is isolated from another transaction.Data modifications made by one transaction must be isolated from the data modifications made by all other transactions. A transaction sees data in the state it was in before another concurrent transaction modified it, or it sees the data after the second transaction has completed, but it doesn’t see an intermediate state.

Durability: Data modifications that occur within a successful transaction are kept permanently within the system regardless of what else occurs. A system crash or any other failure must not be allowed to lose the results of a transaction or the contents of the database.Transaction logs are maintained so that should a failure occur the database can be restored to its original state before the failure. As each transaction is completed, a row is entered in the database transaction log.

Example of ACID Properties:

Transaction to transfer $50 from account A to account B:

1. read(A)
2. A := A – 50
3. write(A)
4. read(B)
5. B := B + 50
6. write(B)

Consistency requirement – the sum of A and B is unchanged by the execution of the transaction.

Atomicity requirement — if the transaction fails after step 3 and before step 6, the system should ensure that its updates are not reflected in the database, else an inconsistency will result.

Durability requirement — once the user has been notified that the transaction has completed (i.e., the transfer of the $50 has taken place), the updates to the database by the transaction must persist despite failures.

Isolation requirement — if between steps 3 and 6, another transaction is allowed to access the partially updated database, it will see an inconsistent database (the sum A + B will be less than it should be). Isolation can be ensured trivially by running transactions serially, that is one after the other. However, executing multiple transactions concurrently has significant benefits.

References:
1. Service-Architecture
2. CWI
3. Beginning C# 2008 Databases: From Novice to Professional By Vidya Vrat Agarwal, James Huddleston, Ranga Raghuram, Syed Fahad Gilani, Jon Reid, Jacob Hammer Pedersen

Types of Tables in Oracle:

1.    Standard Tables
2.    Partitioned Tables
3.    Clustered Tables
4.    Index Organized Tables
5.    Global Temporary Tables.
6.    External Tables.

Keys in RDBMS

1. Primary Key
2. Composite Key
3. Candidate Key
4. Super Key
5. Foreign Key

Primary Key:
-      Primary key is the one which uniquely identifies the records in a table.
EMP ID
EMP NAME
SALARY
1
JOHN
5000
2
JACKSON
6000
3
JOHN
12000




-      Here “EMP ID” is the PRIMARY KEY.
Composite Key:
-      Composite Key is the collection of columns which uniquely identifies the records.
STUDENT ID
COURSE ID
STUDENT NAME
COURSE NAME
DATE OF COMPLETION
11AD12001
101
SAMRAT
COLD FUSION
15/01/2011
11AD12002
102
HARISH
JAVA
16/07/2011
11AD12001
102
SAMRAT
JAVA
16/07/2011
           
-      Here Using Student Id / Course Id, we can’t retrieve a record. Hence to get unique data, we need the combination of Student Id & Course Id.
-      Here (Student Id & Course Id) combined is the COMPOSITE KEY.
Candidate Key:
-      Candidate Key is the collection of columns which are eligible for PRIMARY KEY.
VEHICLE NO
VEHICLE NAME
ENGINE NO
PRICE
MODEL
AP09AZ1001
PULSAR
1234-234-567
65000
150CC
AP12BR0007
CBZ
1023-433-876
67000
LZ
AP22RZ9999
Royal Enfield
4444-444-444
150000
Thunderbird

-      Here Vehicle No, Engine No, are eligible for PRIMARY KEY.
-      Hence Vehicle No, Engine No are CANDIDATE KEY.
-      If Vehicle No is PRIMARY KEY, then Engine no is ALTERNATE KEY.
Super Key:
-      Different Set of attributes which uniquely identifies a record in a relation.

DEPT NO
DEPT NAME
LOCATION
101
CSE
HYDERABAD
102
ECE
HYDERABAD
103
IT
HYDERABAD

-     Here SUPER KEYS are :

DEPT NO + DEPT NAME + LOCATION = SUPER KEY 1
DEPT NO + DEPT NAME                       = SUPER KEY 2
DEPT NO + LOCATION             = SUPER KEY 3
DEPT NAME + LOCATION                     = SUPER KEY 4
DEPT NO                                              = SUPER KEY 5
DEPT NAME                                          = SUPER KEY 6

-     [ifferent Set of attributes which uniquely identifies a record in a relation..
-     s.
-     CANDIDATE KEY = MIN ( SUPER KEY ) { DEPT NO, DEPT NAME }
-     IF IIf DEPT NO is PRIMARY KEY, Then DEPT NAME is ALTERNATE KEY.

FOREIGN KEY:
-     It is used to establish the relationship between 2 relations (table).

EMP NO
EMP NAME
SALARY
DEPT NO
1
John
30000
101
2
Sam
25000
102
3
James
33000
101

DEPT NO
DEPT NAME
LOCATION
101
SALES
HYDERABAD
102
SUPPORT
HYDERABAD

-     Here Foreign Key is “DEPT NO”.
-     If the relationship is 1 to MANY, FOREIGN KEY must be added to many side tables.
-     If the relationship is 1 to 1, FOREIGN KEY can be added to any table.
-     If the relationship is Many to Many, FOREIGN KEY cannot be added to any of the tables.

-     Hence RDBMS doesn’t support MANY to MANY relationships.
-     In RDBMS, MANY to MANY can be split into one to many relations.

Supplier No
Supplier Name
101
John
102
Jackson

Customer No
Customer Name
301
James
302
Bill

Supplier No
Customer No
101
301
102
301
102
302
101
302

SQL Tutorial-- Basics

SQL refers to "Structured Query Language"
·         It is an Structured Query Language because it follows ANSI, ISO standards.
·         It is an editor which helps the user to communicate with the Oracle Server.
·         User communicates with the help of queries. A query is a request / question / command submitted to oracle server to perform operations over DB.
·         SQL is developed by IBM, olden days it was called as “Sequel”.
·         It is the language common for all RDBMS software’s like Oracle, SQL Server, MySQL.
·         Apart from SQL, we also have QBE and QUEL which are used to communicate with the RDBMS server.
-          QBE refers to Query by Example. Used in MS-ACCESS.
-          QUEL refers to Query Language.


Depending on the operations, SQL is categorized into following sub languages:

1.       DML     ( Data Manipulation Language )
2.      DDL      ( Data Definition Language )
3.       DRL      ( Data Retrieval Language )
4.      TCL       ( Transaction Control Language )
5.      DCL       ( Data Control Language )

Data Definition Language (DDL):

-          DDL is a set of instructions to perform operations over Data Definition.
-          Data Definition is also called as Metadata. (data about data)
-          Commands in DDL are:

(i)                 CREATE            
(ii)               ALTER
(iii)             DROP
(iv)              TRUNCATE
(v)                RENAME



 CREATE :
Syntax:

Create table <table_name>
(
                                <column_name>             <data_type> (size),
                                <column_name>             <data_type> (size),
                                <column_name>             <data_type> (size),
                                --
                                --
);            
               
Ex:
                Create table Employee
(
                EmpNo                 Number(4),
                EmpName          varchar2(20),
                Salary                   Number(7,2),
                Desg                     varchar2(20),
                DeptNo                Number(2)
);

Scenarios:

                                 1.       Create a table from the existing table ?

                                 CREATE TABLE EMP_TARGET
                                 AS
                                SELECT * FROM EMP;

                                It creates a new table with name EMP_TARGET. It will create the table along with 
                                the data.

                               2.      Copy the table definition but not the data ?

                               CREATE TABLE EMP_TARGET
                               AS
                               SELECT * FROM EMP WHERE 1=2;


ALTER :

-          It is used to modify data definition of a table.
-          Using alter command :

1.       Add columns
2.      Drop columns
3.       Rename a column
4.      Modify a column
a.       Increasing or decreasing size
b.      Changing data type
c.       Changing Null to Not Null
d.      Changing Not Null to Null

1.       Adding columns using Alter ?

Syntax:
                ALTER TABLE <table_ name>
                                ADD ( column_name datatype(size));

Ex:
Alter Table Employee
                Add ( DOB Date, Gender CHAR(1));

2.      Dropping a column using Alter ?

Syntax:
                ALTER TABLE <table_ name>
                                DROP ( column_name datatype(size));

Ex:
Alter Table Employee
                DROP ( DOB, GENDER);
               
3.       Rename a column using Alter ?

Syntax:
                ALTER TABLE <table_ name>
                                RENAME COLUMN <old_name>  to  <new_name>;

Ex:
Alter Table Employee
                RENAME  column  HireDate   to   DateOfJoin;


4.      Modifying a column using Alter ?

a)      Increasing or decreasing the column size.

Syntax:
                ALTER TABLE <table_ name>
                                MODIFY ( column_name datatype(size)…);

Ex:
Alter Table Employee
                                MODIFY ( ename    varchar2(20));

b)      Changing datatype.

Ex:
Alter Table Employee
                                MODIFY ( COMM    varchar2(20));

c)      Changing from NULL to NOT NULL.

Ex:
Alter Table Employee
                                MODIFY ( ename    NOT NULL);

d)      Changing from NOT NULL to NULL.

Ex:
Alter Table Employee
                                MODIFY ( ename    NULL);

DROP :

Syntax:
                DROP TABLE <tableName>
Ex:
                DROP TABLE EMP;

-          Prior to 10g, we don’t have the option of restoring.
-          From 10g, we can even restore the Dropped tables. This is possible with the concept of “Flashback”.
-          In 10g, when the table is dropped, it is moved to recyclebin in Oracle server.

-          To view  the contents of the Recyclebin, execute the following commands:

Select * from recyclebin;
OR
Show recyclebin;

-          To restore the tables from Recyclebin, execute the following commands:

FLASHBACK table EMP to before DROP;

                This restores the table back along with the data.

-          To delete the table permanently,  execute the following commands:

PURGE   TABLE   EMP;
               
                This deletes the table permanently. Hence FLASHBACK is not possible in this case.

-          To empty Recycle bin, execute the following commands:

DROP   TABLE    EMP   PURGE;
SQL stands for Structured Query Language. and it is generally referred to as SEQUEL. SQL is simple language to learn. SQL is a Nonprocedural language, as compared to the procedural or third generation languages (3GLs) such as COBOL and C. SQL was developed by IBM in the 1970s.
The American National Standards Institute (ANSI) published its first SQL standard in 1986 and a second widely adopted standard in 1989. ANSI released updates in 1992, known as SQL92 and SQL2, and again in 1999, termed both SQL99 and SQL3. Each time, ANSI added new features and incorporated new commands and capabilities into the language.
SQL is a simple, yet powerful, language used to create, access, and manipulate data and structure in the database.

SQL Statements categories: DDL - Data Definition Language.

DDL is used to define, alter, or drop database objects and their privileges. DDL statements will implicitly perform a commit.

DDL Statements:

CreateIt is used to create objects(tables, views) in the database.
AlterIt is used to alter the structure of the database objects.
Dropdelete database objects (It will invalidate the dependent objects ,it also drops indexes, triggers and referential integrity constraints ).
Truncateremove all records from a table, including all spaces allocated for the records are removed (It is fast as compared to Delete and does not generate undo information as Delete does. It performs an implicit commit as it is a DDL. It resets the high water mark.)
Grantassigning privileges

DML - Data Manipulation Language.

DML is used to access, create, modify or delete data in the structures of the database.

DML Statements:

SelectSelect data from the database
InsertIt is used to insert data into a table
UpdateIt is used to update existing data within a table
DeleteIt removes rows from the table.

DCL - Data Control Language

Following are the examples of Data control Statements.

DCL Statements:

CommitIt will end the current transaction making the changes permanent and visible to all users..
SavepointIt will identify a point(named SAVEPOINT) in a transaction to which you can later roll back
RollbackIt will undo all the changes made by the current transaction.
Set- TransactionIt is used to define the properties of a transaction