Sei sulla pagina 1di 39

Be vegan!

Love animals they are innocent, dont use them selfishly to eat, Animals have also
their life, Let them enjoy their life, lets promise I will be vegan, I will contribute from my end to protect them, Remember they are innocent , helpless they are looking towards us. Its

humble request to all of you dearest friend..

DBMS
Q) What is Data? Data is unprocessed, unorganized and raw material. That needs to be processed. Q) What is information? Processed and organized data is called as information. Q) Explain evolve of Data Storage? Explain each of them? File System DBMS based on different models

o Hierarchical DBMS o Network DBMS o Relational DBMS o Object oriented DBMS Q) What is Database?
o A Database is set of logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose. o Database as a self describing collection of integrated records. o Database is a set of interrelated data. A record is physical or conceptual object. Each record has certain attribute called data. Since database contains structure of its own thats why it is self describing. A database contains both data and metadata. Metadata is information about data-structure within.

Database stores metadata in data dictionary. Database are of two types o OLTP(On line transaction processing) o OLAP(On line analytical processing)

Every organization maintains transactional database for storing day to day


transactional details, OLTP stores only current data but not historical data. Performance Reason Company maintains two databases i.e. OLTP and OLAP.

Q) What is DBMS? o It is collection of programs that enables user to create and maintain a database. In other words it is general purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications. o It is a specification means set of feature. An s/w which implement the feature of DBMS known as DBMS software. o DBMS is software that used to create, maintain and provide controlled access to user database. o DBMS is set of interrelated data and set of programs to access those data. o A DBMS is set of programs used to define, administer, and process database and their associated applications. o A DBMS is the tool you use to build that structure and operate on the data contained within the database. o DBMS software is interface between user and database. o DBMS software can also be called as DB server. o DBMS software is also called as Backend tools. o Oracle is backend. Any software provide faculty for creating and maintaining the database is called as backend tools.

DBMS s/w introduced in 1960s. Advantage of DBMSo Redundancy is controlled. o Unauthorized access is restricted. o Providing multiple user interfaces. o Enforcing integrity constraints. o Providing backup and recovery. Q) Explain what is Database System? The database and DBMS software together is called as Database system. Q) What is Data model? Explain different types of Data model?

o A collection of conceptual tools for describing data, data


relationships, data semantics and consistency constraints.

o Data model is a way of explaining the logical layout of data


and relationship of various parts to each other and the whole.
Q) What is Entity? It is a thing in the real world with an independent existence. Attribute is particular property which describes entity. Entity type is a collection of entities that have same attributes. Entity Set is a collection of all entities of particular entity type in the database. A Weak entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be weak entity set.
Relationship is an association among entities. Relationship Set is collection of similar type of relationship.

Q) What is functional dependency?


A functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuple t1 and t2 in r if t1[X]=t2[y] then they have t1[y]=t2[y]. This means the value of x component of a tuple uniquely determines the value of component of y. Q) When is functional dependency F said to be minimal? Every dependency in F has a single attribute for its right hand side. We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F. We cannot remove any dependency from F and still have set of dependency that is equivalent to F. Q) What is fully functional dependency?
It is based on concept of full functional dependency. A functional dependency X Y is fully functional dependency if removal of any attribute A from X means that the dependency does not hold any more.

Q) What is E-R model? o The entity-relationship (E-R) data model is based on a perception of a
real world that consists of a collection of basic objects, called entities, and of relationships among these objects.

o This data model is based on real world that consists of basic objects
called entities and of relationship among these objects. Entities are described in a database by a set of attributes.

o In an effective system data should be divided into Discrete into


Discrete Categories or Entities.

o An ER model is an illustration of various entities in a business and


relationships between them.

o ER-model separates the Information required & The Business from


the activities.

o It is build during the analysis phase of the System developing life


o o o o o o cycle. The overall logical structure (schema) of a database can be expressed graphically by an E-R diagram, which is built up from the following components: Rectangles, which represent entity sets Ellipses, which represent attributes Diamonds, which represent relationships among entity sets Lines, which link attributes to entity sets and entity sets to relationships

ER model benefitso It documents information for the organization in a clear, precise format. o Provides a clear picture of the scope of the information requirement. o Provides an easily understood pictorial map for the database design. o It offers an effective framework for integrating multiple applications.
Key components in ER modelo Entity- it is a thing of significance about which information need to be known. o An entity is a thing or object in the real world that is distinguishable from other objects. o Entities are described in a database by a set of attributes. o Attribute it is something that describes or qualifies an Entity. o Each Attribute may be mandatory or optional. o Relation- It is any Rule or situation that should be satisfied between the attribute and attribute of an entity or entities. Relational Database terminologyo Row or Tuple It represents all data required for a particular instance in an
entity. o Each row in an entity is uniquely identified by declaring it as primary key or UNQIUE.

o The order of the rows is not significant, while retrieving the data. o Column or Attribute- it represents one kind of data in a table vertically o o o o
collected. The column order is not significant when storing the data. Field it can be found at the intersection of a row and a column. A field can have only one value, or may not have a value at all. The absence of value in oracle is represented as NULL.

Relating multiple tables-

o Each table should contain data that describes exactly only on entity. o Data about different entities is stored in different tables. o RDBMS enables the data in one table to be related to another table by using the
foreign keys. o A foreign key is a column OR a set of columns that refer to a primary key in the same table or another table.

Q) What is relational model? Relational model is collection of tables to represent data and relationship among those data. Each table has multiple columns and each column has unique name. The relational model is at a lower level of abstraction than the E-R model. Database designs are often carried out in the E-R model, and then translated to the relational model.

Q) What is object oriented model?


The object-oriented model can be seen as extending the E-R model with notions of encapsulation, methods (functions), and object identity. The object-relational data model combines features of the object-oriented data model and relational data model.

This model is based on collection of objects. An object contains values


stored in instance variables within the object. An object also contains bodies of code that operate on the object. These bodies lf code are called methods. Objects that contain same types bodies of code are called methods. Objects that contain same types bodies of values and the same methods are grouped together into classes.

Instance Databases change over time as information is inserted and deleted. The
collection of Information stored in the database at a particular moment is called an instance of the database. Schema- The overall design of the database is called the database schema. Schema changes very infrequently, if at all. Database systems have several schemas, partitioned according to the levels of abstraction. The physical schema describes the database design at the physical level, while the logical schema describes the database design at the logical level. A database may also have several schemas at the view level, sometimes called sub-schemas, that describes different views of the database.

View -A view may be thought of as a virtual table, i.e. a table that does not
really exist but is derived from underlying base tables. In other words, there is no stored file that direct represents the view instead a definition of tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in database. Hence accounts for logical data, semantics and constraints.
View is nothing more than a SQL statement that is stored in the database with an associated name. Views allow the DBA to do the following: Structure data in a way that users or classes of users find natural or intuitive Restrict access to the data such that a user can see and (sometimes) modify exactly what they need and no more Simplify the DBAs job by building base data structures that the DBA can use to build other views in a natural progression.

A view is often called a virtual table because the view has the appearance of a table, but the data set is not physically stored in the database but rather pulled from the underlying tables on demand. The views data set doesnt exist anywhere until the moment that the view is used. When the view is executed,

the DBMS pulls the data and performs any operations or calculations required by the SQL statement, and then it presents that data to the user

Q) What is SQL? Explain types of SQL?


SQL is non procedural language, used to communicate with DBMS to retrieve or manipulate information from Database. Here just needs to tell what you want not where to get it and how to get it. SQL works on the concept of identification, ownership of database object and that of granting and revoking privileges from users. When table is first created, it is owned by the user who created it and enjoys the full privileges and anyone else then that have no authority unless granted. Oracle allows you to have 30 characters for both table and column name.

NULL VALUE
Null value means a value that is not available or not known. Null values are placed at the end in ascending order and at the beginning in descending order.

Projection
Projection is the operation where we select only a few columns out of the available columns.

Selection
It is possible to select only the required rows using WHERE clause of SELECT command. It implements selection operator of relational algebra.

SQL BUFFER
Whenever you enter an SQL command in SQL*Plus, it is stored in an area in the memory called as SQL Buffer.

Q) What is index?
Index is database object, that store information about the location of data (row) in table.

Q) What are Keys? Explain each of them?


A key is an attribute or set of attributes which can uniquely identify particular row.

Q) What is Primary key?

Column or combination of columns in a database table that uniquely identifies each row in the table is called primary key.

Q) What is Unique Key? Q) What is Foreign Key?


Foreign keys are columns that refer to primary keys in another table. Primary and foreign keys create relations between data in different tables.
In its simplest form, a foreign key is a referential constraint between two tables. A foreign key constraint validates the values of an INSERT or UPDATE against the values in another column, either in a different table or another column in the same table. Generally, though, a foreign key is a field (or fields) that points to the primary key of another table. A foreign key can also be described as a column in a table that does NOT uniquely identify rows in that table, but is used as a link to matching columns in other tables to indicate a relationship. A foreign key always defines a parent/child relationship. The "parent" is the column that is referenced in the foreign key and the "child" is the column or columns that contain the foreign key constraint.

Q) What is Candidate Key?


Candidate key is combination of column that can be uniquely identifies the each row of table.

Q) What is difference between Primary and unique key?


Primary key cant contain null values but unique key may contain null values. Oracle creates index automatically in case of unique and primary key.

Q) What is normalization?
o Process of evaluating and correcting table structure to minimize the data redundancies. o Worked through series of stages called normal form.

It is the process of analyzing the given relation schemas based on their


functional dependencies and primary key to achieve the properties minimizing redundancy, minimizing insertion, deletion and update anomalies.

A technique that reduces or eliminates the possibility that a database is


subject to modification anomalies.

A problem introduced into a database when a modification (insertion,


deletion, update) is made to one of database tables.

Q) What are different types of Normalization?


o o o o o 1 NF 2 NF 3 NF 4 NF 5 NF

In 1 NF table should have only relevant attribute to entity. There should not any repeated data and must have one primary key. In 2 NF table all non primary attribute should depend on Primary attribute. There should be justifiable link between the primary key and non primary attribute. If doesnt exist then we can have separate table. In 3 NF table all non primary should be directly dependent on primary key. There should not be transitive dependency among the attribute.

1 NF -The domain of attribute must include only atomic values. Define the data items required, because they become the columns in a table. Place related data items in a table.

Ensure that there are no repeating groups of data. Ensure that there is a primary key.

2 NF - A relation schema R is in 2 NF if is in 1 NF and every nonprime attribute A in R is fully functionality dependent on primary key.
Columns should be dependent on Primary key.

There must be link between columns and primary key.

3 NF- A relation schema R is in 3 NF if it is in 2nf and for every FD X A


either of the following is true. A is a prime attribute of R. In other words if every non prime attribute is non-transitively dependent on primary key.
A table is in third normal form when the following conditions are met: It is in second normal form. All nonprimary fields are dependent on the primary key. BCNF A relation schema R is in BCNF if it is in 3nf and satisfies an additional constraint that for every FDXS, X must by a candidate key.

Group functions or aggregate functions perform their operation on a group (a collection of rows). All the remaining functions are called as single-row functions as they return a result for each row.

What is Aggregate function?


Function which operates on group of rows received after query is called Aggregate function. Aggregate function can be used in select list just like regular columns with this provision o You cant nest aggregate function and cant mix aggregate function with regular column in same query. There are 5 types of aggregate function o Count()

o o o o

The First type of Count() list all the non value in particular supplied column. The Second type of Count() , counts and display the total numbers of rows retrieved by query. Third Count(*) includes null and non null rows and counts them and display. Max() Min() Avg() Sum()

Q) What are joins? Explain each of them in detail? Q) What is integrity constraint? Explain the type of Integrity constraint?
Constraints
Constraints are used to implement standard and business rules.

Standard rules
Standard constraints are the rules related to primary key and foreign key. Every table must have a primary key. Primary key must be unique and not null. Foreign key must derive its values from corresponding parent key. These rules are universal and are called as standard rules.

Business rules
These rules are related to a single application. For example, in a payroll application we may have to implement a rule that prevents any row of an employee if salary of the employee is less than 2000. Another example is current balance of a bank account Must be greater than or equal to 500. Once the constraints are created, Oracle server makes sure that the constraints are not violated whenever a row is inserted, deleted or updated. If constraint is not satisfied then the operation will fail. Constraints are normally defined at the time of creating table. But it is also possible to add constraints after the table is created using ALTER TABLE command. Constraints are stored in the Data Dictionary .

Constraints in database are used to define an integrity constraint, As a rule that restricts the values in database. As per oracle there are six types of constraints

o o o o o

NOT NULL CONSTRAINT UNIQUE CONSTRAINT PRIMARY KEY CONSTRAINT FOREIGN KEY CONSTRAINT(Referential integrity constraint) CHECK CONSTRAINT

Data Integrity is state in which all the data values stored in the data base are correct. Enforcing data integrity ensures the quality of the data in the data base.

Categories of Data Integrity

1>Entity Integrity 2>Domain Integrity 3>Referential Integrity 4>User Defined Integrity

1>Entity Integrity

It defines a Row as a unique entity for a particular table. Entity Integrity enforces the integrity of the Identifier columns, or the Primary key of table.

2> Domain Integrity Domain Integrity validates the entries for a given column. It can Enforced through.

o o o

Restricting type By format(CHECK constraint)) By Range of possible values using

Foreign key Default key word CHECK constraint Not Null constraint

Domains integrity major fact of concentration is on data that is being collected in that column.
3>Referential Integrity

It preserves the Defined relationship between tables when records are entered or deleted It ensures that key values are consistent Across tables When referential integrity is enforced , it prevents from o Adding records to a related table if there is no associated record in the primary table. o Changing values in a primary table that result in orphaned rerecords in related table o Deleting records from a primary table if there are matching related records.

4>User defined Integrity

It allows defining specific rules that do not fail into any one of the other Integrity categories. These are business rules which can be handled at runtime, usually designed using database triggers in PL/SQL. Can be any situation that looks abnormal to the current systems process.

Q) What are SQL functions? Q) What is single group function? Q) What is sub-query? And type of sub-query? Joins When data from more than one table in the database is required, a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is usually primary key and foreign key columns. To display data from two or more related tables, write a simple join condition in the where clause. o Use a join to query data from more than one table o A join is query that combines row from two or more table, view or materialized views. o A join is performed whenever when-ever multiple tables appear in the queries FRM clause.

o Join condition The applied condition is called join condition. o Oracle combines pairs of rows, each containing one row from each table, for which the join
condition evaluates to TRUE.

o The column in the join condition need not be part of select list. o The where clause of join query can also contain other conditions that refer to columns of only
one table.

o If a join involves over two tables then oracle joins the first two based on the condition and then
compares and then compares the result with next tbale and so on.

o Where table1.clm1=table2.clm2; o Self joins- it indicates joining table to itself.

o The same table appears twice in the from clasuse and is followed by table aliases. o The table aliases must qualify the clm names in the join condition. It is used on JoinWhen data from more than one table in the DB is required , a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is, usually primary and foreign key columns. To display data from two or more related tables, write a simple join condition in the where clause.

o Use a join to query data from more than one table. o A join is query that combines rows from two or more tables, views or
materialized views.

o A join is performed whenever multiple table appear in the queries


FROM clause.

Join condition The Applied condition is called a JOIN condition. o To execute a join o Oracle combines pairs of rows , each containing one row from each
table , for which the JOIN condition evaluates true.

o The column in the join condition need not be part of the select list. o The where clause of join query can also contain other conditions that
refer to columns of only one table.

o If a join involves over 2 tables then oracle joins the first two based on
the condition and then compares the result with the next table and so on.

o Where tb1.clm1=tb2.clm2; o When writing a select statement that joins tables , precede the clm
name with table name for clarity and to enhance database access.

Equi join- based on equality condition tables are joined. Only matching records are displayed. Joining tables must have at least one common column with same data type
and same values.(not clm same name)

Qualifying ambugous clm names- should be prefixed with Tablename

Non equi joins A non equi-join specifies the relationship between clms belonging to different tables by making use of the relational operations other than =. It is used to join table if value of one column a table falls the range of two column values of other table. It is used between operator, it called as between join. Select cl1,cl2 from tl1,tl2 where tl1.cl1 between tl2.cl2 . Self joins It indicates joining the table to itself. The same table appears twice in the from clause and is followed by table aliases. The table aliases must qualify the column names in the join condition. It is used on same table the table must have at least 2 clm with same. Data type Value To perfoem a self join, oracle combines and returns rows of the table that satisfy the join condition. Systex- select clm from t1 l,t 1 I where t1.l=t2.i Cartesian productA Cartesian product results in all conditions of rows displayed. This is done by either omitting the WHERE clause or specifying the CROSS JOIN clause. During Cartesian product oracle combines each row of one table with each row of the other. It tends to generate a large number of rows and the result is rarely useful. A Cartesian product is formed when: A join condition is omitted. A join condition is invalid. All rows in the first table are joined to all rows in the second table. To avoid a Cartesian product, always include a valid join condition in a where clause. Outer JoinUsed to retrieve all the rows from one table but matching rows from other table. An outer join extends the result of a simple or inner join. An outer join returns all rows that satisfy the join condition and also those rows from the other satisfy the join condition. It is use an operator (+), it is called join operator. (+) used with the table which missing the data.

It is use an operator (+), it called join operator. CROSS JOINS -CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it will produce rows which combine each row from the first table with each row from the second table. An 'inner join' is the most common join operation used in applications and can be regarded as the default join-type. Inner join creates a new result table by combining column values of two tables (A and B) based upon the join-predicate. The query compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate. When the joinpredicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row. The result of the join can be defined as the outcome of first taking the Cartesian product (or Cross join) of all records in the tables (combining every record in table A with every record in table B)then return all records which satisfy the join predicate.
An equi-join is a specific type of comparator-based join, that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join. The query shown above has already provided an example of an equi-join: SELECT * FROM employee JOIN department ON employee.DepartmentID = department.DepartmentID; We can write equi-join as below, SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID;

Natural join[edit]
A natural join is a type of equi-join where the join predicate arises implicitly by comparing all columns in both tables that have the same column-names in the joined tables. The resulting joined table contains only one column for each pair of equally named columns.

An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each recordeven if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table's rows are retained (left, right, or both).

Left outer join[edit]


The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B (for a given record in A), the join will still return a row in the result (for that record) but with NULL in each column from B. A left outer join returns all the values from an inner join plus all values in the left table that do not match to the right table.

Right outer join[edit]


A right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in B.

Full outer join[edit]


Conceptually, a full outer join combines the effect of applying both left and right outer joins. Where records in the FULL OUTER JOINed tables do not match, the result set will have NULL values for every column of the table that lacks a matching row. For those records that do match, a single row will be produced in the result set (containing fields populated from both tables).

Self-join[edit]
A self-join is joining a table to itself.

Equi inner join Select * from t1 inner join t2 on t1.id=t2.id; Non-EquiSelect * from t1 inner join t2 on t1.id>t2.id;

Full Outer joinSelect * from t1 full outer join t2 on t1.id=t2.id; Left Outer joinSelect * from t1 left outer join t2 on t1.id=t2.id; Right Outer joinSelect * from t1 right outer join t2 on t1.id=t2.id; Self joinSelect * from t1 t inner join t2 tt on t.id=tt.id;

View
A view is an object in Oracle database, used to provide access only to the required portion of the table by hiding the remaining part of the table. A view can simplify a query by storing complex query in the database. A view doesn't contain any data and retrieves the data from the base table whenever it is referred. As views are used just like tables they are called as virtual tables. It is also possible to manipulate base table through view. Manipulations like INSERT, DELETE and UPDATE can be performed by view provided it fulfills the conditions set by Oracle. A view is a window through which you access a portion of one or more tables. View itself doesn't contain any data but it refers to the data of a table on which it is based. A view is also called as virtual table as it can be used when a table can be used. View retrieves the data by executing the query and presents the data in the form of a table. Views are used to let users access only the portion of the data that they are supposed to access. ORDER BY CLAUSE CANT BE USED WITH QUERY TO CREATE VIEW

CREATE [OR REPLACE] [FORCE ] VIEW viewname [(column-name, column-name)] AS Query [with check option];

OR REPLACE Option Allows View to be created even if one already exists. This allows altering view without dropping, recreating and re-granting object privileges.

FORCE Option Allows view to be created even if the base table doesn't exist. However, the base table should exist before the view is used. Storage of view Oracle stores the query given at the time of creating view in data dictionary. Whenever the view is referred, Oracle executes the query and retrieves the data from the base tables. Whatever data is retrieved that is provided as the data of the view. Since all that Oracle stores regarding view is only the query, a view is also called as stored query. A view may be based on tables or other views or even snapshots (a replica of remote data). Views and dependence A view is dependent on base tables. Base tables may be either real tables or again views. Whether a view is valid or not depends on the availability of the base tables.

A View in Oracle and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query SELECT customerid, customername FROM customers WHERE countryid='US'; To create a view use the CREATE VIEW command as seen in this example

CREATE VIEW view_uscustomers AS SELECT customerid, customername FROM customers WHERE countryid='US'; This command creates a new view called view_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this: SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200; And Oracle will transform the query into this: SELECT * FROM (select customerid, customername from customers WHERE countryid='US') WHERE customerid BETWEEN 100 AND 200 Benefits of using Views Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called its less likely to require parsing. Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to.

isolation

SQL SQL Types Data Definition Language 1. Create 2. Alter 3. Rename 4. Truncate 5. Drop Data Manipulation Language 1. Insert 2. Update 3. Delete Data Retrieval Language 1. Selection Data Control Language 1. Grant 2.Revoke Transaction Control Language Commit Save point Rollback

Difference between Truncate & Delete & Drop Truncate it removes the all rows. But retains the table definition.

Data type Char This is used to store fixed character length. It stores maximum 2000 bytes. For one character one byte space is allocated, it stores ascii character data. Unused space it fills with blank pads. N Char This is used to store character length. It stores Unicode character data. Apart from that it behaves like Char data type. It allocates 2 byte for per character data. Varchar2- Text length may be variable. it also allocate one byte per character. This is used to store ASCII character data, Maximum 4000 bytes it can store. Unused space it releases. So memory saves. N Varchar2 () - This is used to store UNICODE character data, It allocates 2 bytes per character. Apart from this it as same as varchar2(). Number (P,S) This is used to store integer type, p stands for Precision and S stands for scale. Maximum precision it stores 38. Integer it uses 4 bytes to store integer values regardless of value. It has certain limit. Small Int Long

Date TimeStamp BLOB CLOB

What is Pseudo Column?


A pseudo column behaves like column but it is not actually stored in table. You can select from Pseudo column but you cant insert, update and delete them.
Information such as row numbers and row descriptions are automatically stored by Oracle and is directly accessible, ie. not through tables. This information is contained within pseudo columns. These pseudo columns can be retrieved in queries. These pseudo columns can be included in queries which select data from tables.

Pseudo columns are not actually stored in any database table. However these columns are available for inclusion within the output of any result table. Additionally, there are system functions which may also be referenced. Within this section we will consider how each of these may be helpful in certain circumstances. The pseudo columns and functions which we will discuss in this section are:
ROWID

ROWNUM

SYSDATE

USER

UID

SESSIONTIMEZON

Available Pseudo Columns


ROWNUM - row number. Order number in which a row value is retrieved. ROWID - physical row (memory or disk address) location, ie. unique row identification. SYSDATE - system or today's date. UID - user identification number indicating the current user. USER - name of currently logged in user.

Row ID
ROWID is a unique value assigned to each row created in a table. Once ROWID is assigned to a row it doesnt change during the lifetime of the row. Oracle access rows internally using ROWID.

Row Num. Each row retrieved for a query and included within the result table is assigned a row sequence number known as ROWNUM. The ROWNUM is assigned to a row after it is selected for inclusion into the result table, but before any sort due to an ORDER BY clause. For instance, in the example below each row from the MEMBERS table is included in the result and a sequential ROWNUM is assigned during the process. The ROWNUM can be viewed as part of the output by including the pseudo-column within the column list.

Row number. Order number in which a row value is retrieved.

Operator

ANY this operator returns true if any of the subquery (inner query) value is equal to outer query. ANY and SOME can be changed interchangbly. =ANY is equal IN <>ANY is equal to NOT IT < ANY or > ANY

From Where Select Group by Having Order by

PL/SQL
PL/SQL is oracles procedural extension to SQL language. It is block structured language. It is case insensitive language. Procedure refers to set of instruction computer should follow. In PL/SQL there are two types of block Anonymous block Named block o Procedures o Functions o Packages All blocks must contain at least one statement and must end with semi colon. LOOP IF o IF con>2 o Then DBMS_OUTPUT.PUT_LINE(then); o Else DBMS_OUTPUT.PUT_LINE(else);

o End IF; IF o IF con<3 o Then DBMS_OUTPUT.PUT_LINE(hai); o Else if con<2 o Then DBMS_OUTPUT.PUT_LINE(else); o Else DBMS_OUTPUT.PUT_LINE(e); o End if; CASE Case statement work as switch. It can be used in general way or in expression. o CASE o Where con>3 then DBMS_OUTPUT.PUT_LINE(case1); o Where con<3 then DBMS_OUTPUT.PUT_LINE(case2); o Else DBMS_OUTPUT.PUT_LINE(DEFAULT CASE); o END CASE LOOP o INFINITE LOOP LOOP Statements; End Loop; o FINITE LOOP (DO WHILE) Loop Statements EXIT WHEN condition; END loop; FOR o LOOP in forward direction LOOP FOR month in 1..6 DBMS_OUTPUT.PUT_LINE(month); END LOOP; o LOOP in reverse direction LOOP FOR month in REVERSE 1..6

DBMS_OUTPUT.PUT_LINE(month); END LOOP; WHILE o WHILE condition o LOOP o Statements o End Loop;

Data Type Scalar data type o Number o Integer o Varchar2() o Date o char Reference Ref cursor Ref Object type Composite Data item that can have internal component. Indexed by table(Associative table) Nested table V-Array (Collection) Records Table based records o % Type used for table column data type. o % Row-Type used for row. A variable that represents entire row of table. Programmer defined records

Cursor based records a variable that represent type of cursor. LOB BFILE BLOB CLOB NLOB

Scope of variable Variable can be accessed by the block in which they are defined or the inner nested block can use them but Outer block cant use the inner block variable. This concept may change when use Package. Comment Single line comment --Comment goes Multi line comment /* Comment goes here */ General Block Header section Declaration Section Executable section Exception section End NOTE Executable Section is only mandatory. General Program

Normal Anonymous block [Declaration Variable_ Name Data _ Type; ] Begin Statements; [Exception When ex name Then Statements;]

MODEs are 3

Procedure Create [Or replace] Procedure Pro_ name (parameter1 MODE data type (expression) . . ) AS [ Begin Statements; [Exception When ex_ name then Statements;] End Pro_ name; Variable_ Name Data _ Type; ]

1. IN caller supplied value permitted for read only. 2. Out permitted for write only. 3. IN Out Permitted for read and write both.

Function

IT Says to compiler what value u can expect

Create [Or replace] Function Fun_ name (parameter1 MODE data type (expression) . . ) RETURN DATA TYPE AS [ Begin Original Return Value Statements; RETURN EXPRESSION/VALUE [Exception When ex_ name then Statements; RETURN EXPRESSION/VALUE ] End; Variable_ Name Data _ Type; ]

Create [Or Replace] PACKAGE pkg_name

Package

AS Procedure 1; Procedure 2; . Function 1; Function 2.. End pkg_ Name ;

1. Package Specification 2. Package Body

Create [Or Replace] PACKAGE BODY pkg_name AS /* Private program */ Any other which is not in Package spec /*public program*/ Implementation of procedure1 Implementation of Function 1.. END pkg_name;

IN An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a value. You can pass a constant, literal, initialized variable, or expression as an IN parameter. You can also initialize it to a default value; however, in that case, it is omitted from the subprogram call. It is the default mode of parameter passing. Parameters are passed by reference. OUT An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable. You can change its value and reference the value after assigning it. The actual parameter must be variable and it is passed by value.

IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be assigned a value and its value can be read. The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a constant or an expression. Formal parameter must be assigned a value. Actual parameter is passed by value.

The AS keyword is used instead of the IS keyword for creating a standalone procedure.
A stored procedure is a PL/SQL block that is stored in the database with a name. It is invoked using the name. Each procedure is meant for a specific purpose. A stored procedure is stored in the database as an object. It is also called as database procedure as it is stored in the database. A procedure may take one or more parameters. If a procedure takes parameters then these parameters are to be supplied at the time of calling the procedure.

Procedures are used to perform only write only conditions. i.e. when caller is not expecting value from called block, then procedure should function. Procedure can be called in two ways: 1. Execute Procedure-name 2. Block Function are used mostly to perform read only condition. i.e. when caller is expecting value from called block, then function should be used. Package are used to organize the code and maintain them, and also used to create specification (API) for service user. Package is named container which can hold as many procedure and function as many you want. o Package specification shows what a package can do rather than how it will do. Ease to maintain and organize Modularity Easy to understand Performance Package specification - package name .pks Package body - package body. Pkb Procedure - procedure name.pro Function - function name. fun Anonymous block - note.sql SELECT INTO Declaration V1 Data _ Type; v2 Data_ type; Begin Select col1, col2 into v1, v2 from emp where [Exception When ex Then Statements;] End;

Cursor Oracle executes and stores the SQL command results in an area, that area is known as cursor. Cursor is the name for a structure in memory, called a private SQL area, which the
server allocates at runtime for each SQL statement. This memory area contains, among other things, a parsed version of the original SQL statement. If the host program uses any variables in the SQL statement, the cursor also contains the memory addresses of these variables.

/* Cursor using Cursor for loop*/ declare vname emp.ename%type; vsal emp.sal%type; --Cursor declartion cursor cu is select ename,sal from emp; begin /* automatically will open*/ /* rec is automatically filled and processed*/ for rec in cu Loop Dbms_Output.Put_line('vname'||rec.ename||'vsal'||rec.sal); end Loop; end; /

/* Cursor using loop*/ declare vname emp.ename%type; vsal emp.sal%type; --Cursor declartion cursor cu is select ename,sal from emp; begin /* Open cursor */ open cu; Loop fetch cu into vname, vsal; DBMS_Output.Put_Line(vname||vsal); exit when cu%notfound; end Loop; close cu;--closing the cursor end; / Cursor can be traversed in two ways 1. Cursor for loop 2. Simple Loop with exit condition. Cursor maintains 4 variable-

o o o o

Notfound Found RowCount isOpen

Trigger

Triggers are event driven procedures which gets executed at runtime is known as Trigger. In PL/SQL Triggers are procedures which gets executed in an event. Triggers are like stored procedure but only difference is stored procedure call explicitly and triggers are called implecitily. Types of triggers Statement level trigger A statement trigger is fired only once irrespective of rows affected by query. Statement triggers cant access the inserting values, update value. i.e. Statement triggers do not have access to NEW and OLD Statement trigger are by default trigger Row level trigger Row level trigger fired once for every DML affected row. Row level trigger can have access to new and old To use this we need to mention for each row in create trigger statement. After trigger Trigger will be fired when command gets executed. Before trigger Trigger will be fired before command gets executed.

Possible combination
Create or Replace Trigger trigger_ Name [ before|After ] [DML ( column )] on [ table name] [ For each row ] begin Statements; Where| when condition End;

Potrebbero piacerti anche