Download - drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

Transcript
Page 1: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

WHAT IS A REALATIONAL DATABASE MANAGEMENT SYSTEM (RDBMS)

A Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by Dr. Edgar F. Codd. Strictly speaking it should also satisfy codd’s 12 rules, but in practice there is no DBMS that satisfies all these rules. In fact, most successful DBMS that are considered to be relational violate the relational model in several important ways, including the structured Query language (SQL). However, most database practitioners and researchers use the term in a loose way such that most databases that support SQL are included.

Relational Database Management system (RDBMS) stores data in the form of related tabled. RDBMS are powerful because they require few assumptions about how data is related or how it will be extracted from the database. As a result, the same database can be viewed in many different ways.

An important feature of relational systems is that a single database can be spread across several tables. This differs from flat file database, in which each database is self- contained in a single table.

The first released RDBMS that was a relatively faithful implementation of the relational model was the Multics Relational Data store first sold in 1978. Others have been Berkeley Ingres, QUEL and IBM BS12.

Today, popular commercial RDBMS for large databases include Oracle Microsoft SQL server, sybase SQL server, and IBM’s DB2. The most commonly used free RDBMS are MySQL, postgreSQL.

Dr. E. F. Codd’s Rules for RDBMS

Dr. E. F. Codd is an IBM researcher who first developed the relational data model in 1970. In 1985, Dr. Codd published a list of 12 rules that define ideal relational database and has provided a guideline for the design of all relational database systems.

Page 1 of 63

Page 2: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Dr. Codd has used the term guideline because till date no commercial relational database system fully conforms to all 12 rules. For a few years, scorecards were kept that rated each commercial product’s conformity to Codd’s rules. Today, the rules are not talked about as much but remain a goal for relational database design.

Rule 1: The Information Rule: All data should be presented in table form. Means CLIENT_MASTER table represent following:

TABLE: CLIENT_MASTER COMMAND:CREATE TABLE CLIENT_MASTER ( CLIENTNO VARCHAR2(6) PRIMARY KEY, NAME VARCHAR2(20) NOT NULL, ADDRESS1 VARCHAR2(30), ADDRESS2 VARCHAR2(30), CITY VARCHAR2(15), PINCODE NUMBER(8), STATE VARCHAR2(15), BALDUE NUMBER(10,2) );STRUCTURE: Name Null? Type

---------------------------- -------- ---- CLIENTNO NOT NULL VARCHAR2(6) NAME NOT NULL VARCHAR2(20)

ADDRESS1 VARCHAR2(30) ADDRESS2 VARCHAR2(30) CITY VARCHAR2(15) PINCODE NUMBER(8) STATE VARCHAR2(15) BALDUE NUMBER(10,2)

Rule 2: Guaranteed Access Rules: All data should be accessible without ambiguity. This can be accomplished through a combination of the table name,

Primary Key, and column name. EXAMPLE:

Page 2 of 63

Page 3: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Emp_info Emp_Salary_infoEmpId Name EmpId Salary

91 John 91 2000092 Thomas 92 40000

OR Each and every data is guaranteed to be logically accessible by

resorting to a combination of table name, primary key value and column name.

Rule 3: Systematic Treatment of Null Values: A field should be allowed to remain empty. This involves the support of a null value, which is distinct from an

empty string or number with a value of zero. Of course, this can’t apply to primary key. In addition, most database

implementations support the concept of a not- null field constraint that prevents null values in a specific table column.

EXAMPLE:Emp Id Name Phone NoMobile No09BCA01 John 2326864 972514275209BCA02 Thomas 2555631 -

NULL Values are supported in the fully relational DBMS for representing missing information in a systematic way independent of data type.

NULL values are distinct from empty character string or a string of blank character and distinct from 0 or any other number.

Rule 4: Dynamic On-Line Catalog based on the Relational Model: A relational database must provide access to its structure through the

same tools that are used to access the data. EXAMPLE:

This is usually accomplished by storing the structure definition within special system tables.Rule 5: Comprehensive Data Sublanguage Rule: The Relational database must support at least one clearly defined

language that includes functionality for data definition, data manipulation, data integrity and database transaction control.

1.Data Definition2.View Definition3.Data Manipulation4.Integrate Constraints5.Authorization

Page 3 of 63

Page 4: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

6.Transaction Control All commercial relational database use forms of standard SQL (i.e.

Structure Query Language) as their supported comprehensive language.

Rule 6: View Updating Rule: Data can be presented in different logical combination called views. Each view should support the same full range of data manipulation that

has direct access to a table available. In practice, providing update and delete access to logical view is

difficult and not fully supported by any current database. EXAMPLE: All views those are theoretically updatable by the system. This rule is not really implemented yet any available.

Rule 7: High –Level Insert, Update, and Delete: Data can be retrieved from a relation database in sets constructed of

data from multiple rows and/or multiple tables. This rule states that insert, update, and delete operations should be

supported for any retrievable set rather than just for a single row in a single table.

EXAMPLE: Suppose if we need to change ID then it will reflect everywhere automatic. Rule 8: Physical Data independence: The user is isolated from the physical method of storing and retrieving

information from the database. Changes can be made to the underlying architecture (hardware, disk

storage methods) without affecting how the user accesses it. EXAMPLE:

The user is isolated (Separated) from the physical method of storing and retrieving information from the database in which affecting directly in database.

Rule 9: Logical Data Independence: How data is viewed should not be changed when the logical structure

(table’s structure) of the database changes. This rule is particularly difficult to satisfy. Most databases rely on strong ties between the data viewed and the

actual structure of the underlying tables. EXAMPLE:

In this rule we want to retrieve any ID, when we retrieve Data without ID that time we can not satisfy this rule.

Page 4 of 63

Page 5: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Rule 10: Integrity Independence: The database language (like SQL) should support constraints on user

input that maintain database integrity. This rule is not fully implemented by most major vendors. At a minimum, all databases do preserve two constraints through SQL. No component of a primary key can have a null value. If a foreign key is defined in one table, any value in it must exist as a

primary key in another table. All databases do preserved to constrain through SQL.

1. Primary Key can not have NULL.2. Foreign Key is define in one table any value in it must exists as a

primary key in another table.3. Integrity constraints specific to a particular relation database must

be definable in the relational data sub-language & storable in a catalog not in the application program.

Rule 11: Distribution independence: A user should be totally unaware of whether or not the database is

distributed (whether parts of database exist in multiple locations) make this rule difficult to implement.

A variety of reasons make this rule difficult to implement. EXAMPLE:

This rule difficult to implement due to variety of reasons. Rule 12: Non subversion Rule: There should be no way to modify the database structure other than

through the multiple row database language (like SQL). Most databases today support administrative tools that allow some

direct manipulation of the data structure. EXAMPLE:

If a relational system supports a low level (Single record at a time) language that low level language can not be used to sub word or by pass the integrity rules or constraints expressed in the higher level (multiple record at a time) relational language.

What is table ? The data in RDBMS is stored in database objects called tables. The table is a collection of related data entries and it consists of columns and rows. Remember, a table is the most common and simplest form of data storage in a relational

Page 5 of 63

Page 6: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

database. Following is the example of a CUSTOMERS table:

+----+----------+-----+-----------+----------+| ID | NAME | AGE | ADDRESS | SALARY |+----+----------+-----+-----------+----------+| 1 | Ramesh | 32 | Ahmedabad | 2000.00 || 2 | Khilan | 25 | Delhi | 1500.00 || 3 | kaushik | 23 | Kota | 2000.00 || 4 | Chaitali | 25 | Mumbai | 6500.00 || 5 | Hardik | 27 | Bhopal | 8500.00 || 6 | Komal | 22 | MP | 4500.00 || 7 | Muffy | 24 | Indore | 10000.00 |+----+----------+-----+-----------+----------+

What is field? Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY. A field is a column in a table that is designed to maintain specific information about every record in the table.

What is record, or row? A record, also called a row of data, is each individual entry that exists in a table. For example there are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the CUSTOMERS table:

+----+----------+-----+-----------+----------+| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |+----+----------+-----+-----------+----------+

A record is a horizontal entity in a table.What is column?

A column is a vertical entity in a table that contains all information associated with a specific field in a table. For example, a column in the CUSTOMERS table is ADDRESS which represents location description and would consist of the following:

+-----------+

Page 6 of 63

Page 7: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

| ADDRESS |+-----------+| Ahmedabad || Delhi || Kota || Mumbai || Bhopal || MP || Indore |+----+------+

What is NULL value? A NULL value in a table is a value in a field that appears to be blank which means A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation.

Introduction To Structure Query Language(SQL)Structure Query Language (SQL) is language that provides an interface to relational database systems. SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an ISO and ANSI standard. SQL is often pronounced SEQUEL and SEQUEL means Structure English QUEry Language.

Features of SQL 1. SQL can be used by a range of users, including those with

little or no programming experience.2. It is a non procedural language.3. It reduces the amount of time required for creating and

maintaining systems.4. It is an English-like language.5.

Rules for SQL1. SQL starts with a verb(i.e. a SQL action word).

EXAMPLE: SELECT statements. This verb may have additional adjectives. EXAMPLE: FROM

2. Each verb is followed by number of clauses. EXAMPLE: FROM, WHERE, HAVING

Page 7 of 63

Page 8: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

3. A space separates clause. EXAMPLE: DROP TABLE EMP;

4. A Comma (,) separates parameters without a clause.5. A ‘;’ is used to end SQL statements.6. Statements may be split across lines but keywords may

not.7. Lexical units such as identifiers, operator names, literals

are separated by one or more spaces or other delimiters that will not be confused with the lexical unit.

8. Reserved words cannot be used as identifiers unless enclosed with double quotes. Reserved words are: AS, BY, CREATE, SELECT, VARCHAR, BETWEEN etc.

9. Identifiers can contain up to 30 characters and must start with an alphabetic character.

10. Character and date literals must be enclosed within single quotes.

11. Numeric literals can be represented by simple values such as 0.32,-34,01991, and so on, scientific notation as 2E5 meaning 2x10 to power of 5=200,000.

12. Comments may be enclosed between /* and */ symbols and may be multi line. Single line comments may be prefixed with a – symbol.

SQL Delimiters

Delimiters are symbol or compound symbols, which have a special meaning within SQL and PL/SQL statements.

+ Addition “ Quote identifier- Subtraction : Host Variable* Multiplication ** Exponential/ Division <> !=

^=Relational

=> < Relational <= >= Relational() Expression or list := Assignment; Terminator => Association% Attribute indicator || Concatenation, Item separator << Label. Component selector >> Label@ Remote access -- Comment

Page 8 of 63

Page 9: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

indicator‘ Character string

delimiter/* */ Comment (Multi-

line)

Components of SQL1. DDL(Data Definition Language) :

It is a set of SQL commands used to create, modify and delete database structures but not data.

These commands are normally not used by a general user, who should be accessing the database via an application.

They are normally used by the DBA to a limited extent, a database designer or application developer.

DDL must have the CREATE object privilege and a Tablespace area in which to create objects.

2. DML(Data Manipulation Language) : It is the area of SQL that allows changing data within

the database. 3. DCL(Data Control Language) :

It is the component of SQL statement that control access to data and to the database. Occasionally DCL statements are grouped with DML statements.

4. DQL(Data Query Language) : It is the component of SQL statement that allows

getting data from the database and imposing ordering upon it. In includes the SELECT statement. This command is the heart of SQL. It allows getting the data out of the database perform operations with it. When a SELECT is fired against a table or tables the result is compiled into a further temporary table, which is displayed or perhaps received by the program i.e. a front-end.

Examples of DDL, DML and DCL commands

DDL: Data Definition Language statementsExamples:

CREATE To create objects in the database ALTER Alters the structure of the database

Page 9 of 63

Page 10: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

DROP Delete objects from the database TRUNCATE Remove all records from a table, including

all spaces allocated for the records are removed

COMMENT Add comments to the data dictionary GRANT Gives user’s access privileges to database REVOKE Withdraw access privileges given with the

GRANT Command

DML: Data Manipulation Language statementsExamples:

INSERT Insert data into a table UPDATE Updates existing data within a table DELETE DELETE Deletes all records from a table, the

space for the records remain CALL Call a PL/SQL or JAVA subprogram EXPLAINPLAN Explain access path to data LOCK TABLE Control concurrency

DCL: Data Control Language statementsExamples:

COMMIT Save work done SAVEPOINT Identify a point in a transaction to which

you can later roll back ROLLBACK Restore database to original since the last

COMMIT SET TRANSACTION Change transaction options like

what rollback segment to use GRANT / REVOKE EGrant or take back permissions to

or from the oracle users.DQL: Data Query Language statementsExamples:

SELECT Retrieve data from the a database

TABLESPACE IN ORACLE

Logical Structure of a DatabaseAn Oracle database comprises of a number of physical files called data files. These files are logically grouped together into oracle(logical) structure called a Tablespace.

Page 10 of 63

Page 11: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

TablespaceUser data in an Oracle database is logically stored in tablespace and physically stored in data files, which are bound to the corresponding tablespace.

Tablespace are a mechanism or a means by which logical objects such as tables, indexes and views are mapped to a specific data file. Tablespaces are also used to group different types of (logical) database objects together.

SQL Constraints:Constraints are the rules enforced on data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database.

There are two types of constraints:1).Input output constraints.

o Primary key constrainto Foreign key constraintso Unique key constraints

2).Business rule constraints.o Not null constraintso Check constraintso Default constraints

Constraints could be column level or table level. Column level constraints are applied only to one column where as table level constraints are applied to the whole table.

Page 11 of 63

Constraint

Input output

Business rule

Page 12: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Following are commonly used constraints available in SQL:

1. NOT NULL Constraint : Ensures that a column cannot have NULL value. By default, a column can hold NULL values. If you do not

want a column to have a NULL value then you need to define such constraint on this column specifying that NULL is now not allowed for that column.

A NULL is not the same as no data, rather, it represents unknown data.

EXAMPLE:

For example, the following SQL creates a new table called CUSTOMERS and adds five columns, three of which, ID and NAME and AGE, specify not to accept NULLs:

CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));

If CUSTOMERS table has already been created, then to add a NOT NULL constraint to SALARY column in Oracle, you would write a statement similar to the following:

ALTER TABLE CUSTOMERS MODIFY SALARY DECIMAL (18, 2) NOT NULL;

2. DEFAULT Constraint : Provides a default value for a column when none is

specified. The DEFAULT constraint provides a default value to a

column when the INSERT INTO statement does not provide a specific value.

EXAMPLE:For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here SALARY column is set to 5000.00 by default, so in case INSERT INTPO statement does not provide a value for this column then by default this column would be set to 5000.00.

CREATE TABLE CUSTOMERS(

Page 12 of 63

Page 13: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2) DEFAULT 5000.00, PRIMARY KEY (ID));

If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY column, you would write a statement similar to the following:

ALTER TABLE CUSTOMERS MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;

Drop Default Constraint:To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE CUSTOMERS ALTER COLUMN SALARY DROP DEFAULT;

3. UNIQUE Constraint : Ensures that all values in a column are different. The UNIQUE Constraint prevents two records from having

identical values in a particular column. In the CUSTOMERS table, for example, you might want to prevent two or more people from having identical age.

EXAMPLE:For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here AGE column is set to UNIQUE, so that you can not have two records with same age:

CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL UNIQUE, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));

Page 13 of 63

Page 14: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE column, you would write a statement similar to the following:

ALTER TABLE CUSTOMERS MODIFY AGE INT NOT NULL UNIQUE;

You can also use following SYNTAX, which supports naming the constraint and multiple columns as well:

ALTER TABLE CUSTOMERS ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);

DROP a UNIQUE Constraint:To drop a UNIQUE constraint, use the following SQL:

ALTER TABLE CUSTOMERS DROP CONSTRAINT myUniqueConstraint;

If you are using MySQL then you can use following SYNTAX:

ALTER TABLE CUSTOMERS DROP INDEX myUniqueConstraint;

4. PRIMARY Key :

Uniquely identified each rows/records in a database table. A primary key is a field in a table which uniquely identifies

the each rows/records in a database table. Primary keys must contain unique values. A primary key

column cannot have NULL values. A table can have only one primary key which may consist

of single or multiple fields. When multiple fields are used as a primary key, they are

called a composite key. If a table has a primary key defined on any field(s) then

you can not have two records having the same value of that field(s).

Note: You would use these concepts while creating database tables.

Create Primary Key:

Page 14 of 63

Page 15: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Here is the SYNTAX to define ID attribute as a primary key in a CUSTOMERS table.

CREATE TABLE CUSTOMERS( ID INT NOT NULL, PRIMARY KEY (ID));

To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already exists, use the following SQL SYNTAX:

ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).For defining a PRIMARY KEY constraint on multiple columns, use the following SQL SYNTAX:

CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID, NAME));

To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table already exists, use the following SQL SYNTAX:

ALTER TABLE CUSTOMERS ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);

Delete Primary Key:You can clear the primary key constraints from the table, Use SYNTAX:

ALTER TABLE CUSTOMERS DROP PRIMARY

Page 15 of 63

Page 16: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

KEY ; 5. FOREIGN Key :

Uniquely identified a rows/records in any another database table.

A foreign key is a key used to link two tables together. This is sometimes called a referencing key.

Primary key field from one table and insert it into the other table where it becomes a foreign key ie. Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.

The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table.

If a table has a primary key defined on any field(s) then you can not have two records having the same value of that field(s).

EXAMPLE:Consider the structure of the two tables as follows: CUSTOMERS table:

CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));

ORDERS table:

CREATE TABLE ORDERS ( ID INT NOT NULL, DATE DATETIME, CISTOMER_ID INT references CUSTOMERS(ID), AMOUNT double, PRIMARY KEY (ID)

Page 16 of 63

Page 17: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

);If ORDERS table has already been created, and the foreign key has not yet been, use the SYNTAX for specifying a foreign key by altering a table.

ALTER TABLE ORDERS ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);

DROP a FOREIGN KEY Constraint:To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE ORDERS DROP FOREIGN KEY;

6. CHECK Constraint : The CHECK constraint ensures that all values in a column

satisfy certain conditions. The CHECK Constraint enables a condition to check the

value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn’t entered into the table.

EXAMPLE:For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here we add a CHECK with AGE column, so that you can not have any CUSTOMER below 18 years:

CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL CHECK (AGE >= 18), ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));

If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you would write a statement similar to the following:

ALTER TABLE CUSTOMERS

Page 17 of 63

Page 18: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );

You can also use following SYNTAX, which supports naming the constraint and multiple columns as well:

ALTER TABLE CUSTOMERS ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);

DROP a CHECK Constraint:To drop a CHECK constraint, use the following SQL.

ALTER TABLE CUSTOMERS DROP CONSTRAINT myCheckConstraint;

INDEX : Use to create and retrieve data from the database very

quickly. The INDEX is used to create and retrieve data from

the database very quickly. Index can be created by using single or group of columns in a table. When index is created it is assigned a ROWID for each rows before it sort out the data.

EXAMPLE:For example, the following SQL creates a new table called CUSTOMERS and adds five columns:

CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, SALARY DECIMAL (18, 2), PRIMARY KEY (ID));

Now you can create index on single or multiple columns using the folloiwng SYNTAX:

CREATE INDEX index_name ON table_name ( column1, column2.....);

Page 18 of 63

Page 19: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

To create an INDEX on AGE column, to optimize the search on customers for a particular age, following is the SQL SYNTAX:

CREATE INDEX idx_age ON CUSTOMERS ( AGE );

DROP a INDEX Constraint:To drop a INDEX constraint, use the following SQL:

ALTER TABLE CUSTOMERS DROP INDEX idx_age;

SQL is followed by unique set of rules and guidelines called SYNTAX. This tutorial gives you a quick start with SQL by listing all the basic SQL SYNTAX:

All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;).

Important point to be noted is that SQL is case insensitive which means SELECT and select have same meaning in SQL statements but MySQL make difference in table names. So if you are working with MySQL then you need to give table names as they exist in the database.

SQL SELECT Statement:

SELECT column1, column2....columnNFROM table_name;

SQL DISTINCT Clause:SELECT DISTINCT column1, column2....columnNFROM table_name;

SQL WHERE Clause:SELECT column1, column2....columnNFROM table_name

Page 19 of 63

Page 20: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

WHERE CONDITION;

SQL AND/OR Clause:SELECT column1, column2....columnNFROM table_nameWHERE CONDITION-1 {AND|OR} CONDITION-2;

SQL IN Clause:SELECT column1, column2....columnNFROM table_nameWHERE column_name IN (val-1, val-2,...val-N);

SQL BETWEEN Clause:SELECT column1, column2....columnNFROM table_nameWHERE column_name BETWEEN val-1 AND val-2;

SQL Like Clause:SELECT column1, column2....columnNFROM table_nameWHERE column_name LIKE { PATTERN };

SQL ORDER BY Clause:SELECT column1, column2....columnNFROM table_nameWHERE CONDITIONORDER BY column_name {ASC|DESC};

SQL GROUP BY Clause:SELECT SUM(column_name)

Page 20 of 63

Page 21: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

FROM table_nameWHERE CONDITIONGROUP BY column_name;

SQL COUNT Clause:SELECT COUNT(column_name)FROM table_nameWHERE CONDITION;

SQL HAVING Clause:SELECT SUM(column_name)FROM table_nameWHERE CONDITIONGROUP BY column_nameHAVING (arithematic function condition);

SQL DROP TABLE Statement:DROP TABLE table_name;

SQL CREATE INDEX Statement :CREATE UNIQUE INDEX index_nameON table_name ( column1, column2,...columnN);

SQL DROP INDEX Statement:ALTER TABLE table_nameDROP INDEX index_name;

SQL DESC Statement: DESC table_name;

Page 21 of 63

Page 22: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

SQL TRUNCATE TABLE Statement:TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement:ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};

SQL ALTER TABLE Statement (Rename) :ALTER TABLE table_name RENAME TO new_table_name;

SQL INSERT INTO Statement:INSERT INTO table_name( column1, column2....columnN)VALUES ( value1, value2....valueN);

SQL UPDATE Statement:UPDATE table_nameSET column1 = value1, column2 = value2....columnN=valueN[ WHERE CONDITION ];

SQL DELETE Statement:DELETE FROM table_nameWHERE {CONDITION};

SQL CREATE DATABASE Statement:CREATE DATABASE database_name;

SQL DROP DATABASE Statement:DROP DATABASE

Page 22 of 63

Page 23: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

database_name;

SQL COMMIT Statement:COMMIT;

SQL ROLLBACK Statement:ROLLBACK;

SQL LoaderSQL LOADER utility is used to load data from other data source into Oracle. For example, if you have a table in FOXPRO, ACCESS or SYBASE or any other third party database, you can use SQL Loader to load the data into Oracle Tables. SQL Loader will only read the data from Flat files. So If you want to load the data from FoxPro or any other database, you have to first convert that data into Delimited Format flat file or Fixed length format flat file, and then use SQL loader to load the data into Oracle.

Following is procedure to load the data from Third Party Database into Oracle using SQL Loader.

1. Convert the Data into Flat file using third party database command.

2. Create the Table Structure in Oracle Database using appropriate data types

3. Write a Control File, describing how to interpret the flat file and options to load the data.

4. Execute SQL Loader utility specifying the control file in the command line argument

SQL*Loader  (sqlldr ) is the utility to use for high performance data loads.  The data can be loaded from any text file and inserted into the database. 

Page 23 of 63

Page 24: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Figure 4.2 depicts the SQL*Loader architecture.   SQL*Loader reads a data file and a description of the data which is defined in the control file.  Using this information and any additional specified parameters (either on the command line or in the PARFILE), SQL*Loader loads the data into the database.   During processing, SQL*Loader writes messages to the log file, bad rows to the bad file, and discarded rows to the discard file.

  Figure 4.2 – SQL*Loader Architecture 

The Control File

The SQL*Loader control file contains information that describes how the data will be loaded.  It contains the table name, column datatypes, field delimiters, etc.   It simply provides the guts for all SQL*Loader processing.  Manually creating control files is an error-prone process.   The following SQL script (controlfile.sql) can be used to generate an accurate control file for a given table.  The script accepts a table name and a date format (to be used for date columns), and generates a valid control file to use with SQL*Loader for that table.    

Page 24 of 63

Page 25: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

 controlfile.sql set echo off ver off feed off pages 0accept tname prompt 'Enter Name of Table: 'accept dformat prompt 'Enter Format to Use for Date Columns: ' spool &tname..ctl select 'LOAD DATA'|| chr (10) ||       'INFILE ''' || lower (table_name) || '.dat''' || chr (10) ||       'INTO TABLE '|| table_name || chr (10)||       'FIELDS TERMINATED BY '','''||chr (10)||       'TRAILING NULLCOLS' || chr (10) || '('from   user_tableswhere  table_name = upper ('&tname'); select decode (rownum, 1, '   ', ' , ') ||       rpad (column_name, 33, ' ')      ||       decode (data_type,           'VARCHAR2', 'CHAR NULLIF ('||column_name||'=BLANKS)',           'FLOAT',    'DECIMAL EXTERNAL NULLIF('||column_name||'=BLANKS)',           'NUMBER',   decode (data_precision, 0,                       'INTEGER EXTERNAL NULLIF ('||column_name||                       '=BLANKS)', decode (data_scale, 0,                       'INTEGER EXTERNAL NULLIF ('||                       column_name||'=BLANKS)',                       'DECIMAL EXTERNAL NULLIF ('||                       column_name||'=BLANKS)')),           'DATE',     'DATE "&dformat" NULLIF ('||column_name||'=BLANKS)', null)from   user_tab_columnswhere  table_name = upper ('&tname')order  by column_id; select ')' from dual;spool off Once executed and given a table name and date format, controlfile.sql will generate a control file with the following contents:   controlfile.par LOAD DATAINFILE 'table_with_one_million_rows.dat'INTO TABLE TABLE_WITH_ONE_MILLION_ROWSFIELDS TERMINATED BY ','

Page 25 of 63

Page 26: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

TRAILING NULLCOLS(   COL1                     DECIMAL EXTERNAL NULLIF (COL1=BLANKS) , COL2                     DECIMAL EXTERNAL NULLIF (COL2=BLANKS) , COL3                     CHAR NULLIF (COL3=BLANKS) , COL4                     CHAR NULLIF (COL4=BLANKS) , COL5                     CHAR NULLIF (COL5=BLANKS) , COL6                     DATE "MM-DD-YYYY" NULLIF (COL6=BLANKS)) The control file can also specify that records are in fixed format.  A file is in fixed record format when all records in a datafile are the same length.  The control file specifies the specific starting and ending byte location of each field.   This format is harder to create and less flexible but can yield performance benefits.  A control file specifying a fixed format for the same table could look like the following:

 LOAD DATAINFILE 'table_with_one_million_rows.dat'INTO TABLE TABLE_WITH_ONE_MILLION_ROWS(   COL1  POSITION(1:4)     INTEGER EXTERNAL , COL2  POSITION(6:9)     INTEGER EXTERNAL , COL3  POSITION(11:46)   CHAR , col4  position(48:83)   CHAR , col5  position(85:120)  CHAR , COL6  POSITION(122:130) DATE "MMDDYYYY" )

The Log File

The log file contains information about the SQL*loader execution.   It should be viewed after each SQL*Loader job is complete.  Especially interesting is the summary information at the bottom of the log, including CPU time and elapsed time.  The data below is a sample of the contents of the log file.  *****************************************************************************************SQL*Loader: Release 9.2.0.1.0 - Production on Mon Mar 10 23:39:04 2003 Copyright (c) 1982, 2002, Oracle Corporation.  All rights reserved. 

Page 26 of 63

Page 27: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

*****************************************************************************************Control File:   sqlload.parData File:      sqlload.txt  Bad File:     sqlload.bad  Discard File:  none specified  (Allow all discards) Number to load: ALLNumber to skip: 0Errors allowed: 50Continuation:    none specifiedPath used:      Direct Table TABLE_WITH_ONE_MILLION_ROWS, loaded from every logical record.Insert option in effect for this table: INSERTTRAILING NULLCOLS option in effect Table TABLE_WITH_ONE_MILLION_ROWS, loaded from every logical record.Insert option in effect for this table: INSERTTRAILING NULLCOLS option in effect    Column Name                  Position   Len  Term Encl Datatype------------------------------ ---------- ----- ---- ---- ---------COL1                                FIRST     *   ,       CHARACTER    NULL if COL1 = BLANKSCOL2                                 NEXT     *   ,       CHARACTER    NULL if COL2 = BLANKSCOL3                                 NEXT     *   ,       CHARACTER    NULL if COL3 = BLANKSCOL4                                 NEXT     *   ,       CHARACTER    NULL if COL4 = BLANKSCOL5                                 NEXT     *   ,       CHARACTER    NULL if COL5 = BLANKSCOL6                                 NEXT     *   ,       DATE MMDDYYYY    NULL if COL6 = BLANKS  

SQL*Loader Options

SQL*Loader provides the following options, which can be specified either on the command line or within a parameter file:   

Page 27 of 63

Page 28: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

         bad – A file that is created when at least one record from the input file is rejected.  The rejected data records are placed in this file.  A record could be rejected for many reasons, including a non-unique key or a required column being null. 

         bindsize –  [256000] The size of the bind array in bytes. 

         columnarrayrows – [5000] Specifies the number of rows to allocate for direct path column arrays.

         control – The name of the control file.  This file specifies the format of the data to be loaded. 

         data – The name of the file that contains the data to load.  

         direct – [FALSE] Specifies whether or not to use a direct path load or conventional.  

         discard – The name of the file that contains the discarded rows.  Discarded rows are those that fail the WHEN clause condition when selectively loading records.

         discardmax – [ALL] The maximum number of discards to allow.

         errors – [50] The number of errors to allow on the load. 

         external_table – [NOT_USED] Determines whether or not any data will be loaded using external tables. The other valid options include GENERATE_ONLY and EXECUTE.    

         file – Used only with parallel loads, this parameter specifies the file to allocate extents from.

         load – [ALL] The number of logical records to load.  

         log – The name of the file used by SQL*Loader to log results. 

         multithreading – The default is TRUE on multiple CPU systems and FALSE on single CPU systems. 

Page 28 of 63

Page 29: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

         parfile – [Y] The name of the file that contains the parameter options for SQL*Loader. 

         parallel – [FALSE] Specifies a filename that contains index creation statements.

         readsize – The size of the buffer used by SQL*Loader when reading data from the input file.   This value should match that of bindsize. 

         resumable – [N] Enables and disables resumable space allocation.  When “Y”, the parametersresumable_name and resumable_timeout are utilized. 

         resumable_name – User defined string that helps identify a resumable statement that has been suspended.  This parameter is ignored unless resumable = Y.

         resumable_timeout – [7200 seconds] The time period in which an error must be fixed.  This parameter is ignored unless resumable = Y.

         rows – [64] The number of rows to load before a commit is issued (conventional path only).  For direct path loads, rows are the number of rows to read from the data file before saving the data in the datafiles. 

         silent – Suppress errors during data load.  A value of ALL will suppress all load messages.  Other options include DISCARDS, ERRORS, FEEDBACK, HEADER, and PARTITIONS.

         skip – [0] Allows the skipping of the specified number of logical records. 

         skip_unusable_indexes – [FALSE] Determines whether SQL*Loader skips the building of indexes that are in an unusable state.

Page 29 of 63

Page 30: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

         skip_index_maintenance – [FALSE] Stops index maintenance for direct path loads only. 

         streamsize – [256000] Specifies the size of direct path streams in bytes.  

         userid – The Oracle username and password.

To check which options are available in any release of SQL*Loader use this command: sqlldr help=y

Maximizing SQL*Loader Performance 

SQL*Loader is flexible and offers many options that should be considered to maximize the speed of data loads. These include: 

1.      Use Direct Path Loads - The conventional path loader essentially loads the data by using standard insert statements.  The direct path loader (direct=true) loads directly into the Oracle data files and creates blocks in Oracle database block format.  The fact that SQL is not being issued makes the entire process much less taxing on the database.  There are certain cases, however, in which direct path loads cannot be used (clustered tables).   To prepare the database for direct path loads, the script$ORACLE_HOME/rdbms/admin/catldr.sql.sql must be executed.

2.      Disable Indexes and Constraints.  For conventional data loads only, the disabling of indexes and constraints can greatly enhance the performance of SQL*Loader.   

3.      Use a Larger Bind Array.  For conventional data loads only, larger bind arrays limit the number of calls to the database and increase performance.  The size of the bind array is specified using the bindsize parameter. The bind array's size is equivalent to the number of rows it contains (rows=) times the maximum length of each row.

Page 30 of 63

Page 31: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

4.      Use ROWS=n to Commit Less Frequently.  For conventional data loads only, the rows parameter specifies the number of rows per commit.  Issuing fewer commits will enhance performance. 

5.      Use Parallel Loads.  Available with direct path data loads only, this option allows multiple SQL*Loader jobs to execute concurrently.

$ sqlldr control=first.ctl  parallel=true direct=true$ sqlldr control=second.ctl parallel=true direct=true

 6.      Use Fixed Width Data.  Fixed width data format saves

Oracle some processing when parsing the data.  The savings can be tremendous, depending on the type of data and number of rows. 

7.      Disable Archiving During Load.  While this may not be feasible in certain environments, disabling database archiving can increase performance considerably.

8.      Use unrecoverable.  The unrecoverable option (unrecoverable load data) disables the writing of the data to the redo logs.  This option is available for direct path loads only.

Using the table  table_with_one_million_rows, the following benchmark tests were performed with the various SQL*Loader options. The table was truncated after each test.   

SQL*Loader Option

Elapsed Time (Seconds)

Time Reduction

direct=falserows=64

135 -

direct=falsebindsize=512000rows=10000

92 32%

direct=falsebindsize=512000rows=10000database in

85 37%

Page 31 of 63

Page 32: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

noarchivelog modedirect=true 47 65%direct=trueunrecoverable

41 70%

direct=trueunrecoverablefixed width data

41 70%

 Table 4.3 – Results indicate conventional path loads take longest. The results above indicate that conventional path loads take the longest.  However, the bindsize and rowsparameters can aid the performance under these loads.  The test involving the conventional load didn’t come close to the performance of the direct path load with the unrecoverable option specified.  It is also worth noting that the fastest import time achieved for this table (earlier) was 67 seconds, compared to 41 for SQL*Loader direct path – a 39% reduction in execution time.  This proves that SQL*Loader can load the same data faster than import. These tests did not compensate for indexes.  All database load operations will execute faster when indexes are disabled.  

CORE CONCEPT

What is Oracle?

“Oracle is a program that is running in the background, maintaining your data for you and figuring out where it should go on your hard drive. “

“Oracle is made up of a set of processes running in your operating system. These processes manage how data is stored and how it is accessed.”

What is SQL?SQL is the Structured Query Language.

Page 32 of 63

Page 33: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

PL/SQL is the procedural language extension to SQL. PL/SQL is a programming language like C, Java or Pascal. In the Oracle world, there is no better way to access your data from inside a program. SQL can be natively embedded in PL/SQL programs. I will be using both SQL and PL/SQL very heavily in my future articles. 

PL/SQL is a feature-rich language geared toward developing database applications. PL/SQL is the procedural language of the database, but it is also the procedural language for most of Oracle's tools. Programs that run inside the database are called stored procedures. These stored procedures are almost always PL/SQL, but can be written in Java.  

Some of Oracle's tools to access the database and create programs are: 

SQL*Plus has a command line interface. With it, you can access the database and write stored procedures, you can run SQL commands to retrieve data and you can run scripts of either SQL, PL/SQL or built-in SQL*Plus commands, or a mixture of those three things. 

Oracle Developer is a 4GL GUI application Builder. With Developer, you can create forms, reports, and graphics. Oracle*Forms and Oracle*Reports are two components of Oracle Developer. Earlier versions created client-server applications, but the more recent versions create web applications that run under the Oracle Application Server (OAS). OAS is a web-based application server sold by Oracle. OAS is licensed separately and is very expensive (as are its closed source competitors). The current version is OAS 10g. 

HTML DB is a fairly new application builder geared toward web development (added to the DB with release 9iR2). HTML DB does not need an application server. This tool runs from the database and can be presented to the web using the Apache web server that comes with the database. Since this is not an additional license, it provides a cheaper way to develop applications. Developer is a feature-rich thick client with all of the normal GUI widgets. HTML DB is HTML-based and is very

Page 33 of 63

Page 34: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

thin and limited to the HTML provided widgets. 

Oracle Enterprise Manager (OEM)  is the Enterprise GUI tool to manage the database. From this tool, you can perform any action in the database that is required. This tool is primarily used for administration but can also be provided to developers for application tuning and monitoring. In Oracle 10g, OEM also provides Grid control.  

There are also a lot of third party tools for accessing the database. For our purposes, our primary tool for data access will be SQL*Plus. In the future, I will cover creating applications with HTML DB and accessing your data with some choice third-party tools. 

ORACLE FUNCTIONS

Oracle functions serve the purpose of manipulating data items and returning a result. Functions are also capable of accepting user-supplied variables or constants and operating on them. Variables or constants are called arguments.

1) Function Name (argument1, argument2,…)

Oracle Function can be clubbed together depending upon whether they operate on a single row or a group of rows retrieved from a table.

2) Group Functions (Aggregate Functions)

Functions that act on a set of a value are called Group Functions. For Example, SUM, is a function, which calculates the total set of number. A group functions return as a single result row for a group of queried rows.

3) Scalar Functions (Single Row Functions)

Functions that act on only one value at a time are called Scalar Functions.For example, LENGTH is a function, which calculates the length of one particular string value. A single

Page 34 of 63

Page 35: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

row function returns one result for every row of a queried table or view.

AGGREGATE FUNCTIONS

1) AVG: Returns an average value of ‘n’, ignoring null values in a column.

SYNTAX: AVG ([<DISTINCT> | <ALL>] <n>)

EXAMPLE: SELECT AVG (CURBAL)”Average Balance” FROM

ACCT_MSTR; OUTPUT: Average Balance ------------------------ 11002) MIN: Returns a minimum value of expr.SYNTAX: MIN ([<DISTINCT> | <ALL>] <expr>)EXAMPLE: SELECT MIN(CURBAL)”Minimum Balance” FROM ACCT_MSTR; OUTPUT: Minimum Balance ------------------------ 500

Two type of SQL function

Page 35 of 63

Page 36: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Single Row function

3) COUNT(expr): Returns the number of rows where expr is not null.SYNTAX: COUNT ([<DISTINCT> | <ALL>] <expr>)EXAMPLE:

SELECT COUNT(ACCT_NO)”No. of Accounts” FROM ACCT_MSTR; OUTPUT: No. of Accounts ------------------------ 10 4) COUNT (*): Returns the no of rows in the table, including duplicates and those with nulls.

SYNTAX: COUNT(*)EXAMPLE:

SELECT COUNT(*)”No. of Records” FROM ACCT_MSTR; OUTPUT:

No. of Records ------------------------ 105) MAX: Return the maximum value of expr.

SYNTAX: MAX ([<DISTINCT> | <ALL>] <expr>)

Page 36 of 63

Page 37: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

EXAMPLE: SELECT MAX(CURBAL)”Maximum Balance” FROM

ACCT_MSTR;

OUTPUT: Maximum Balance

------------------------ 20006) SUM: Return the sum of the value of ‘n’.

SYNTAX: SUM ([<DISTINCT> | <ALL>] <n>)EXAMPLE:

SELECT SUM(CURBAL)”Total Balance” FROM ACCT_MSTR; OUTPUT:

Total Balance ------------------------ 11000

NUMERIC FUNCTIONS

1) ABS: Returns the absolute value of ‘n’.

SYNTAX: ABS(n)

EXAMPLE: SELECT ABS(-15)”Absolute” FROM DUAL;

OUTPUT: Absolute

------------------ 15

2) POWER: Returns m raised to the nth power. N must be an integer, else an error is returned.SYNTAX:

POWER(m, n)EXAMPLE:

SELECT POWER(3,2)”Raised” FROM DUAL;OUTPUT:

Page 37 of 63

Page 38: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

Raised --------------

93) ROUND: Returns n, rounded to m places to the right of a decimal point, if m is omitted, n is rounded to 0 places. m can be negative to round off digits to the left of the decimal point. m must be an integer.

SYNTAX: ROUND(n[,m])

EXAMPLE: SELECT ROUND(15.19,1)”Round” FROM DUAL;

OUTPUT: Round --------------

15.24) SQRT: Returns square root of n, If n<0, NULL. SQRT returns a real result.

SYNTAX: SQRT(n)

EXAMPLE: SELECT SQRT(25)”Square Root” FROM DUAL;

OUTPUT: Square root -------------------

55) EXP: Returns e raised to the nth power, where e = 2.71828183

SYNTAX: EXP(n)

EXAMPLE: SELECT EXP(5)”Exponent” FROM DUAL;

OUTPUT: Exponent

Page 38 of 63

Page 39: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

------------------- 148.413159

6) EXTRACT: Returns a value extracted from a date or an interval value. A DATE can be used only to extract YEAR, MONTH, and DAY, while a timestamp with a time zone data type can be used only to extract TIMEZONE_HOUR and TIMEZONE_MINUTE.

SYNTAX:EXTRACT( {year | month | day | hour | minute | second | timezone_hour | timezone_minute | timezone_region | timezone_abbr} FROM { date_value | interval-value })

EXAMPLE:SELECT EXTRACT(YEAR FROM DATE ‘2004-07-02’) “Year”, EXTRACTMONTH FROM SYSDATE) “Month” FROM DUAL;

OUTPUT: Year Month -----------------------

2002 77) GREATEST: Returns the greatest value in a list of expressions.

SYNTAX: GREATEST(expr1, expr2, . . . . expr_n)

Where, expr1, expr2, . . . . expr_n are expression that are evaluated by the greatest function.

EXAMPLE: SELECT GREATEST(4,5,17)”Num”, GREATEST(‘4’,’5’,’17’) “Text” FROM DUAL;OUTPUT:

Num Text -------------------

Page 39 of 63

Page 40: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

5

8) LEAST: Returns the least value in a list of expressions.

SYNTAX: LEAST(expr1, expr2, . . . . expr_n)

where, expr1, expr2, . . . .expr_n are expression that are evaluated by the least function.EXAMPLE: SELECT LEAST(4,5,17)”Num”, LEAST(‘4’,’5’,’17’) “Text” FROM DUAL;OUTPUT:

Num Text -------------------

17 9) MOD: Returns the remainder of a first number divided by second number passed a parameter. If the second number bis zero, the result is the same as the first number. SYNTAX:

MOD(m, n)EXAMPLE:

SELECT MOD(15,7)”Mod1”,MOD(15.5,7)”Mod2” FROM DUAL;OUTPUT:

Mod1 Mod2 ---------------------- 1 1.7

10) TRUNC: Returns a number truncated to a certain number of decimal places. The decimal place value must be a integer. If this parameter is omitted, the TRUNC function will truncate the number to 0 decimal places. SYNTAX:

TRUNC(number, [decimal_places])EXAMPLE:

Page 40 of 63

Page 41: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

SELECT TRUNC(125.815,1)”Trunc1”,TRUNC(125.815,- 2)”Trunc2” FROM DUAL;OUTPUT:

Trunc1 Trunc2 ----------------------

100

11) FLOOR: Returns the largest integer value that is equal to or less than a number.

SYNTAX: FLOOR(n)

EXAMPLE: SELECT FLOOR(24.8)”Flr1”, FLOOR(13.15’) “Flr2” FROM DUAL;OUTPUT:

Flr1 Flr2 -------------------

1312) CEIL: Returns the smallest integer value that is greater than or equal to a number.. SYNTAX:

CEIL(n)EXAMPLE: SELECT CEIL(24.8)”Ceil1”, CEIL(13.15’) “Ceil2” FROM DUAL;OUTPUT:

Ceil1 Ceil2 -------------------

14STRING FUNCTION

1) LOWER: Returns char, with all letters in lowercase. SYNTAX:

LOWER (char)EXAMPLE:

Page 41 of 63

Page 42: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

SELECT LOWER (‘IVAN BAYROSS’)”Lower” FROM DUAL;OUTPUT:

Lower ------------------- ivan bayross

2) INITCAP: Returns a string with the first letter of each word in upper case. SYNTAX:

INITCAP(char)EXAMPLE: SELECT INITCAP(‘IVAN BAYROSS’)”Title Case” FROM DUAL;OUTPUT:

Title Case ------------------- Ivan Bayross

3) UPPER: Returns char, with all letters forced to uppercase. SYNTAX:

UPPER(char)EXAMPLE: SELECT UPPER(‘Ms. Carol’)”capitalised” FROM DUAL;OUTPUT:

Capitalised ------------------- MS. CAROL

4) SUBSTR: Returns a portion of characters, beginning at character m, and going up to character n. if n is omitted, the result returned is upto the last character in the string. The first position of char is 1. SYNTAX:

SUBSTR(<string>, <start_position>, [<length>]) where, string is the source string. start_position is the position for extraction. The first position in the string is always 1. length is the number of characters to extract.EXAMPLE:

Page 42 of 63

Page 43: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

SELECT SUBSTR(‘SECURE’,3,4’)”Substring” FROM DUAL;OUTPUT:

Substring ------------------- CURE

ASCII: Returns the NUMBER code that represents the specified character. If more than one character is entered, the function will return the value for the first character and ignore all of the characters after the first.

SYNTAX: ASCII(<single_character>)

where, single_character is the specified character to retrive the NUMBER code for,EXAMPLE: SELECT ASCII(‘a’)”ASCII1”, ASCII(‘A’)”ASCII2” FROM DUAL;OUTPUT:

ASCII1 ASCII2 ----------------------------

65

5) COMPOSE: Returns a Unicode string. It can be a char, varchar2, nchar, nvarchar2, clob, or clob. SYNTAX:

COMPOSE(<single>) Below is a listing of unistring values that can be combined with other characters in the compose function.

Unistring Value Resulting character

UNISTR(‘\0300’) grave accent (‘)UNISTR(‘\0301’) acute accent (‘)UNISTR(‘\0302’) circumflex (^)UNISTR(‘\0303’) tilde (~)

Page 43 of 63

Page 44: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

UNISTR(‘\0308’) umlaut (“)

EXAMPLE: SELECT COMPOSE(‘a’ || UNISTR(‘\0301’)) “Composed” FROM DUAL;

OUTPUT: Composed ------------------ a

6) DECOMPOSE: Accepts a string and returns a Unicode string. SYNTAX:

DECOMPOSE(<single>)EXAMPLE: SELECT DECOMPOSE(COMPOSE(‘a’ || UNISTR(‘\0301’))) “Decomposed” FROM DUAL;OUTPUT:

Decomposed ------------------- ‘a ‘

7) INSTR: Returns the location of a substring in a string. SYNTAX:

INSTR(<string1>, <string2>, [<start_position>], [<nth_appearance>]) where, string1 is the string to search, string2 is the substring to search for in string 1. start_position is the position in string 1 where the search will start. were nth_position is the nth appearance of string2. if omitted, it defaults to 1.EXAMPLE: SELECT INSTR(‘SCT on the net’,’t’) “Instr1”, INSTR(‘SCT on the net’,’t’,1,2) “Instr2” FROM DUAL;

OUTPUT: Instr1 Instr2 ---------------------

Page 44 of 63

Page 45: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

148) TRANSLATE: Replaces a sequence of characters in a string with another set of characters. However, it replaces a single character at a time.SYNTAX:

INITCAP(char)EXAMPLE: SELECT TRANSLATE(‘1sct523’,’123’,’7a9’) “Change” FROM DUAL;OUTPUT:

Change ------------------- 7sct5a9

9) LENGTH: Returns the length of a word. SYNTAX:

LENGTH(word)EXAMPLE: SELECT LENGTH(‘PIYUSH’)”Length” FROM DUAL;OUTPUT:

Length ----------------

610) LTRIM: Removes characters from the left of char with initial characters removed upto the first character not in set. SYNTAX:

LTRIM(char[,set])EXAMPLE: SELECT LTRIM(‘PIYUSH’,’P’)”LTRIM” FROM DUAL;OUTPUT:

LTRIM ---------------

IYUSH

11) RTRIM: Returns char, with final characters removed after the last character not in the set. ‘set’ is optional, it defaults to spaces. SYNTAX:

Page 45 of 63

Page 46: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

RTRIM(char,[set])EXAMPLE: SELECT RTRIM(‘PIYUSH’,’H’) ”RTRIM” FROM DUAL;OUTPUT:

RTRIM --------------- PIYUS

12) TRIM: removes all specified characters either from the beginning or the ending of a string. SYNTAX:

RTRIM(char,[set])EXAMPLE: SELECT RTRIM(‘PIYUSH’,’H’) ”RTRIM” FROM DUAL;OUTPUT:

RTRIM --------------- PIYUS

13) RTRIM: Returns char, with final characters removed after the last character not in the set. ‘set’ is optional, it defaults to spaces. SYNTAX: TRIM( [leading | trailing | both [<trim_character> FROM ]] <string1>)

where, leading – remove trim_string from the front of string1.

trailing – remove trim_string from the end of string1. both – remove trim_string from the front and end of string1.EXAMPLE: SELECT TRIM(‘ PIYUSH ’) ”Trim both sides” FROM DUAL;OUTPUT:

Trim both sides --------------------- PIYUSH

14) LPAD: Returns char1, left-padded to length n with the sequence of

Page 46 of 63

Page 47: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

characters specified in char2. if char2 is not specified Oracle uses blanks by default.SYNTAX:

LPAD(char1,n [,char2])EXAMPLE: SELECT LPAD(‘Page 1’,10,’*’) ”LPAD” FROM DUAL;OUTPUT:

LPAD ---------------

****Page1

15) RPAD: Returns char1, right-padded to length n with the sequence of characters specified in char2. if char2 is not specified Oracle uses blanks by default.SYNTAX:

RPAD(char1,n [,char2])EXAMPLE: SELECT RPAD(‘FNAME’,10,’x’) ”RPAD” FROM DUAL;

where FNAME is = PIYUSHOUTPUT:

RPAD -----------------

PIYUSHxxxx16) VSIZE: Returns the number of bytes in the internal representation of an expression.SYNTAX:

VSIZE(<expression>)EXAMPLE: SELECT VSIZE(‘SCT on the net’) ”Size” FROM DUAL;OUTPUT:

Size ------------

14

CONVERSION FUNCTIONS

Page 47 of 63

Page 48: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

TO_NUMBER: Converts char, a CHARACTER value expressing a number, to a NUMBER datatype.SYNTAX:

TO_NUMBER(char)EXAMPLE:

UPDATE ACCT_MSTR SET Curbal = Curbal + TO_NUMBER(SUBSTR(‘$100’,2,3));OUTPUT:

10 rows updated

TO_CHAR: (number conversion): Converts a value of a NUMBER datatype to a character datatype, using the optional format string. TO_CHAR() accepts a number (n) and a numeric format (fmt) in which the number has to appear. If fmt is omitted, n is converted to a char value exactly long enough to hold all significant digits.SYNTAX:

TO_CHAR(n[,fmt])EXAMPLE:

SELECT TO_CHAR(17145,’4099,999’) “Char” FROM DUAL;OUTPUT:

Char --------------

$017,145

TO_CHAR: (date conversion): Converts a value of a DATE datatype to a CHAR value, TO_CHAR) accepts a date, as well as the format (fmt) in which the date has to appear. Fmt must be

Page 48 of 63

Page 49: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

a date format. If fmt is omitted, the date is converteharacter value using the default date format, i.e. “DD-MON-YY”.SYNTAX:

TO_CHAR(date[,fmt])EXAMPLE:

SELECT TO_CHAR(DT,’Month DD, YYYY’) “New Date Format” FROM Trans_Mstr where Trans_No = ‘T1’;OUTPUT:

New Date Format --------------------------- January 05, 2003

DATE CONVERSION FUNCTIONS

TO_DATE: Converts a characters field to a date field.

SYNTAX: TO_DATE(char [,fmt])

EXAMPLE: INSERT INTO CUST_MSTR(CUST_NO, FNAME,

MNAME, LNAME, DOB_INC) VALUES(‘C1’,’Ivan’,Nelson’,’bayross’,

TO_DATE(’25-JUN-1952 10:55 A.M.’,’DD-MON-YY HH:MI A.M.’));

OUTPUT:1 rows created.

1) ADD_MONTHS: returns date after adding the number of months specified in the function.SYNTAX:

ADD_MONTHS(d,n)EXAMPLE:

SELECT ADD_MONTHS(SYSDATE,4) “Add Months” FROM DUAL;OUTPUT:

Add Months

Page 49 of 63

Page 50: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

-------------------- 01-NOV-04

2) LAST_DAY: returns the last date of the month specified with the function.SYNTAX: LAST_DAY(d)EXAMPLE:

SELECT SYSDATE, LAST_DAY(SYSDATE) “LastDay” FROM DUAL;OUTPUT:

SYSDATE LastDay ---------------------------------

01-JUL-04 31-JUL-04

3) MONTH_BETWEEN: Returns number of months between d1 and d2.SYNTAX:

MONTHS_BETWEEN(d1, d2)EXAMPLE:

SELECT MONTHS_BETWEEN(’02-FEB-92’,’02-JAN-92’) “Months” FROM DUAL;OUTPUT:

Months --------------

1

4) NEXT_DAY: Returns the date of the first weekday named bby char that is after the date named by date char must be a ady of the week.SYNTAX:

NEXT_DATE(date, char)EXAMPLE: SELECT NEXT_DAY(’06-JULY-02’,’Saturday’) “NEXT DAY” FROM DUAL;OUTPUT:

NEXT DAY -------------------

13-JULY-02

Page 50 of 63

Page 51: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

5) ROUND: Returns the date rounded to a specified unit of measure. If the second parameter is omitted, the ROOUND function will round the date to the nearest day.SYNTAX:

ROUND(date, char)EXAMPLE: SELECT ROUND(TO_DATE(’01-JUL-04’0,’YYYY’) “Year” FROM DUAL;OUTPUT:

Year -------------------

01-JAN-056) NEW_TIME: Returns the date after converting if from time zone1 to a date in time zone2.SYNTAX:

NEW_TIME(date, zone1, zone2)EXAMPLE: SELECT NEW_TIME(TO_DATE(’2004/07/01 01:45’,’yyyy/mm/dd HH24:MI’),’AST’,’MST’) “MST” FROM DUAL;OUTPUT:

MST -------------------

30-JUN-04

General FunctionsThese functions work with any data type and pertain to using nulls.• NVL (expr1, expr2)• NVL2 (expr1, expr2, expr3)• NULLIF (expr1, expr2)• COALESCE (expr1, expr2, ..., exprn)

NVL FunctionConverts a null to an actual value.• Data types that can be used are date, character and number

Page 51 of 63

Page 52: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

• Data types must match:– NVL(commission_pct,0)– NVL(hire_date,'01-JAN-97')– NVL(job_id,'No Job Yet')

EXAMPLE:SELECT last_name, salary, NVL(commission_pct, 0),(salary*12) + (salary*12*NVL(commission_pct, 0)) AN_SAL FROM employees;

NVL2 FunctionEXAMPLE:SELECT last_name, salary, commission_pct,NVL2(commission_pct,'SAL+COMM', 'SAL') incomeFROM employees WHERE department_id IN (50, 80);

COALESCE FunctionThe advantage of the COALESCE function over the NVL function is that the COALESCE function can take multiple alternate values. If the first expression is not null, it returns that expression; otherwise, it does a COALESCE of the remaining expressions.EXAMPLE:SELECT last_name, COALESCE(commission_pct, salary, 10) commFROM employees ORDER BY commission_pct;

MISCELLANEOUS FUNCTIONS

UID: This function returns an integer value corresponding to the UserID of the user currently logged in.SYNTAX:

UID [INTO <variable>] Where, variable will now contain the id number for the user’s session.EXAMPLE:

SELECT UID FROM DUAL;OUTPUT:

UID

Page 52 of 63

Page 53: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

------------- 61

USER: This function returns the user name of the user who has logged in. the value returned is in varchar2 data type.SYNTAX:

USEREXAMPLE:

SELSECT USER FROM DUAL;OUTPUT:

USER -----------------------

DBA_BANKSYS

SYS_CONTEXT: Can be used to retrieved information about oracle’s environment.SYNTAX:

SYS_CONTEXT (<namespace>, <parameter>, [<length>])EXAMPLE:

SELECT SYS_CONTEXT(‘USERENV’,’NLS_DATE_FORMAT’) “SysContext” FROM DUAL;OUTPUT:

SysContext -----------------------

DD-MON-RRCOALESCE: returns the first non-null expression in the list. If all expression evaluate to null, then the coalesce function will return null.SYNTAX:

COALESCE (<expr1>, <expr2>, . . . . . <expr_n>)EXAMPLE:

SELECT COALESCE(FNAME, CUST_NO) Customers FROM DUAL;

IF-THEN-ELSE statement:IF FNAME IS NOT NULL THEN Customers := CUST_NO;ELSE CUST_NO IS NOT NULL THEN Customers := CUST_NO;

Page 53 of 63

Page 54: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

ELSE Customers := NULL;END IF;OUTPUT:

Customers ---------------------

IVAN PIYUSH DHAVAL

JAY 008

Range Searching and Pattern Matching Operator1) Range Searching:In order to select data that is within a range of values, the BETWEEN operator is used. The BETWEEN operator allows the selection of rows that contain values within a specified lower and upper limit. The range coded after the word BETWEEN is inclusive.

The lower values must be coded first. The two values in between the range must be linked with the keyword AND. The BETWEEN operator can be used with both character and numeric data types. However, the data types can not be mixed.

Example: The lower value of a range of values from a character column and the other from a numeric column.

Synopsis:Tables: TRANS_MSTRColumns: All columnsTechnique: Functions: TO_CHAR(), Operators: BETWEEN, Clauses:

WHERE

Solution:

SELECT * FROM TRANS_MSTR WHERE TO_CHAR (DT,’MM’) BETWEEN 01 AND 03;

Equivalent to:

SELECT * FROM TRANS_MSTR

Page 54 of 63

Page 55: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

WHERE TO_CHAR (DT.’MM’) >= 01 AND TO_CHAR (DT,’MM’) <=03;

Output: TRANS_NO ACCT_NO DT TYPE PARTICULAR DR CR AMT BALANCE

T1 SB1 05-JAN-03 C Initial Payment D 500 500T2 CA2 10-JAN-03 C Initial Payment D 2000 2000T3 SB3 22-JAN-03 C Initial Payment D 500 500T4 CA4 05-FEB-03 B Initial Payment D 2000 2000T5 SB5 15-FEB-03 B Initial Payment D 500 500T6 SB6 27-FEB-03 C Initial Payment D 500 500T7 CA7 14-MAR-03 B Initial Payment D 2000 2000T8 SB8 29-MAR-03 C Initial Payment D 500 5008 rows selected.Explanation:

The above selected will retrieve all those record from the ACCT_MSTR table where the value held in the DT field is between 01 and 03 (both values inclusive). This is doing using TO CHAR () function which Extracts the month value from the DT field. This is then compared using the AND operator.

Example:Synopsis:

Tables: TRANS_MSTRColumns: ACCT_NOTechnique: Functions: TO_CHAR(), Operators: BETWEEN, Clauses:

WHERE

Solution:

SELECT DISTINCT FROM TRANS_MSTR WHERE TO_CHAR (DT,’MM’) NOT BETWEEN 01 AND 04;

Output:

ACCT_NO-----------------

Page 55 of 63

Page 56: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

SB9

2) Pattern Matching:

The use of the LIKE predicate The comparison operators discussed so far have compared one value, exactly to one other value. Such precision may not always be desired necessary. For this purpose oracle provides the LIKE predicate.

The LIKE predicate allows comparison of one string value with another string value, which is not identical. This achieved by using wildcard characters. Two characters that are available:

For character data types:

% allows to match any string of any length (include zero length)_ allows matching on a single character

Example: List the customer whose being with the letters ‘Ch’

Synopsis: Tables: CUST_MSTRColumns: FNAME,LNAME,DOB_INCTechnique: Operators: BETWEEN, Clauses: WHERE, Others: ALIAS

Solution:

SELECT FNAME, LNAME, DOB_INC “BIRTHDATE”, OCCUP FROM CUST_MSTR WHERE FNAME LIKE ‘CH%’;

Output:

FNAME LNAME Birthday OCCUP

Chriselle Bayross 29-OCT-82 Service Chhaya Bankar 06-OCT-76 Service

Explanation:

Page 56 of 63

Page 57: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

In the above examples, all those records where the values held in the FNAME beings with Ch are displayed. The % indicates that any number of characters can follow the letters Ch.

The IN and NOT IN predicates:

The arithmetic operator (=) compares a single value to another single value. In case a value needs to be compared to a list of values then the IN predicate is used. The IN predicates helps reduce the need to use multiple OR conditions.

Example: List the customer details of the customers named Hansel, Mamta, Namita and Aruna.

Synopsis: Tables: CUST_MSTRColumns: FNAME,LNAME,DOB_INCTechnique:

Operators: IN, Clauses: WHERE, Others: ALIAS

Solution:SELECT FNAME, LNAME, DOB_INC “birthday”, OCCUP FROM CUST_MSTR WHERE FNAME IN (‘Hansel’,.Mamta’,Namita’,’Aruna’);Output:FNAME LNAME Birthday OCCUP------------------------------------------------------------------Mamta Muzumdar 28-AUG-75 ServiceHansel Colaco 01-JAN-82 ServiceNamita Kanade 10-JUN-78 Self EmployedExplanation:The above example, displays all those records where the FNAME filed holds any one of the four specified Values.

What is DBA? “A database administrator (DBA) is a person responsible for the design, implementation, maintenance and repair of an organization's database.” Or “The DBA is a person having central control over data and processing accessing that data.”

Page 57 of 63

Page 58: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

They are also known by the titles Database Coordinator or Database Programmer, and is closely related to the Database Analyst, Database Modeler.

The role includes the development and design of database strategies, monitoring and improving database performance and capacity, and planning for future expansion requirements.

The duties of a database administrator vary depending on job description, corporate and Information Technology (IT) policies and the technical features and capabilities of the DBMS being administered.

Duties of DBA

1) Installation of new software: It is the job of the DBA to install new versions of DBMS software, application software, and other software related to DBMS administration. It is important that the DBA or other IS staff members test new software before it is moved into a production environment.

2) Security administration: One of the main duties of the DBA is to monitor and administer DBMS security. This involves adding and removing users, administering quotas, auditing, and checking for security problems.

3) Data analysis: The DBA analyzes data stored in the database and makes recommendations relating to performance and efficiency of that data storage.

4) Database design: The DBA can be involved at the preliminary database-design stages, eliminating many problems that might occur.

5) Configuration of hardware and software with the system Administrator: In many cases the system software can only be accessed by the system administrator. In this case, the DBA works closely with the system administrator to perform software installations, and to configure hardware and software so that it functions optimally with the DBMS.

6) Data modeling and optimization: By modeling the data, it is possible to optimize the system layouts to take the most advantage of the I/O subsystem.

7) Recoverability is one of the most important and vital duty of a Database Administrator. Any type of error such as, data entry

Page 58 of 63

Page 59: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

error, hardware failure, software failure, bugs, virus etc. can result in corrupting database.

8) Planning and implementing a sound backup and recovery strategy.

9) DBA is responsible for create a separate tablespace within the database to hold user objects.

10) DBA is also responsible for authorization of access data and integrity constraint specification.

Backup and Recovery

In general, backup and recovery refers to the various strategies and procedures involved in protecting your database against data loss and reconstructing the data should that loss occur.

BackUp: “A backup is a copy of data. This copy can include important parts

of the database such as the control file and datafiles.” Or “A backup is a safeguard against unexpected data loss and application errors. If you lose the original data, then you can reconstruct it by using a backup.

Backups are divided into physical backups and logical backups. Physical backups, which are the primary concern in a backup and

recovery strategy, are copies of physical database files. You can make physical backups with either the Recovery Manager (RMAN) utility or operating system utilities.

In contrast, logical backups contain logical data (for example, tables and stored procedures) extracted with the Oracle Export utility and stored in a binary file. You can use logical backups to supplement physical backups.

Recovery: To restore a physical backup of a datafile or control file is to

reconstruct it and make it available to the Oracle database server. To recover a restored datafile is to update it by applying archived

redo logs and online redo logs, that is, records of changes made to the database after the backup was taken.

Backup and Recovery Solution: You have two methods for performing Oracle backup and

recovery: Recovery Manager (RMAN) and user-managed backup and recovery.

Page 59 of 63

Page 60: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

RMAN is a utility automatically installed with the database that can back up any Oracle8 or later database. RMAN uses server sessions on the database to perform the work of backup and recovery.

RMAN has its own syntax and is accessible either through a command-line interface or though the Oracle Enterprise Manager GUI.

One of the principal advantages of RMAN is that it obtains and stores metadata about its operations in the control file of the production database.

An alternative method of performing recovery is to use operating system commands for backups and SQL*Plus for recovery. This method, also called user-managed backup and recovery, is fully supported by Oracle Corporation, although use of RMAN is highly recommended because it is more robust and greatly simplifies administration.

Oracle and Client-Server TechnologyOracle server

Oracle server is a multi-user tool that works in a client/server environment. Client/server Programming is a distributed application program.

It has three distinct components, each focusing on a specific job. Three components are

1.Oracle Server2.Oracle Client Tool3.Network for connecting the first two component

Oracle server’s primary job is to manage data optimally, among multi-users that concurrently request for the same data.

Oracle client tools are that part of the system that provides an interface to the user so that the data retrieved from the server can be manipulated.

It allows users to pass data manipulation requests to the oracle server.

The network and communicating software is the vehicle that transports data between oracle client tools and the oracle server.

Oracle Client side tools are:

1. Oracle SQL*Plus2. Oracle Form Designer

Page 60 of 63

Page 61: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

3. Oracle Reports Designer4. Oracle Graphics

Oracle SQL*Plus

Oracle server is a separate toolthat comes as a part of oracle enterprise server as well as Oracle Workgroup server via which user can communicate interactively with the Oracle server.

Oracle provide an interactive SQL tool called SQL*Plus, which allow user to enter ANSI SQL sentences and pass them to the Oracle Engine for execution.

To use ANSI SQL the user must load the SQL*Plus tool in clients memory, link to the server & then communicate with the Oracle Engine loaded on the server.

Note:Oracle server can be called Oracle DBA, Oracle Engine or Oracle Server interchangeably. Granting Privileges When a grantee has been given the GRANT privilege:If the user want to grant privileges to other users, the user must be the owner of the object or must be given the GRANT option by the owner of the object.Example:

GRANT SELECTON xyz.product_masterTO opq;

Revoking Privileges Given Privileges once given can be denied to a user the REVOKE

command. The object owner can revoke privileges granted to another user. A user of an object who is not the owner, but has been granted

the GRANT privilege, has the power to REVOKE the privileges from grantee.

Revoking Permission using the REVOKE statement:The REVOKE satement is used to deny the grant given on an object.Syntax:

REVOKE {object privileges} ON objectnameFROM username;

Example:REVOKE DELETE

ON client_masterFROM xyz;

REVOKE ALLON product_masterFROM abc;

REVOKE SELECT

Page 61 of 63

Page 62: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

ON xyz.product_masterFROM opq;

Note:The REVOKE command cannot be used to revoke the privileges granted through the operating system.

Features of SQL *PLUS: SQL has been a command language for communication with the oracle

9i server from any tool or application Oracle SQL contains many extensions When an SQL statement is entered, it is stored in a part of

memory called the SQL buffer and remains there until a new SQL statement is entered

SQL *PLUS is an oracle tool that recognizes and submits SQL statement to the oracle 9i server for execution. It contains its own command language

SQL *PLUS accepts ad hoc entry of statements. It accepts SOL input from files It provides a line editor for modifying SQL

Statements. It controls environmental settings. It formats query result into basic reports. It accesses local and remote databases

Features of SQL: SQL can be used by a range of user, including those with little or

no programming experience. It is a non procedural language. It reduces the amount of time required for creating and maintaining

systems. It is English -like language.

What is deference between SQL & SQL*PLUS

SQL SQL *PLUSSQL is a language for communicating with the Oracle sever to access data

SQL *PLUS recognizes SQL statements and sends them to the server

SQL is based on American national standards institute(ANSI) standard SQL

SQL*PLUS is the Oracle proprietary interface for executing SQL statements

SQL manipulates data and table definitions in the database

SQL*PLUS does not allow manipulation of values in the database

SQL is entered into the SQL buffer on one or more line

SQL*PLUS is entered one line at a time, not stored in the SQL

Page 62 of 63

Page 63: drronakpanchal.files.wordpress.com · Web viewA Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKHSUBJECT: RDBMS

COURSE: BCA SEM: III

bufferSQL does not have a continuation character

SQL*PLUS uses a dash(-)as a continuation character if the command is longer than one line

It cannot be abbreviated It can be abbreviatedSQL uses a termination character to execute commands immediately

SQL*PLUS does not require termination characters; executes commands immediately

SQL uses functions to perform some formatting.

SQL*PLUS uses commands to format data

Difference between DBMS and RDBMSDBMS RDBMS

In DBMS relation between two tables or files area maintained programmatically

In RDBMS relationship between two table or files can be specified at the time of table creation

DBMS does not support client/server Architecture

Most of the RDBMS supports client/server Architecture

DBMS does not support Distributed databases

Most of the RDBMS supports Distributed databases

In DBMS there is no security of data

In RDBMS there are multiple level of security

1. Logging in at O/S level2. Command level(i.e. at

RDBMS level)3. Object level

Each table is given an extension in DBMS

Many tables are grouped in one database in RDBMS

DBMS may satisfy less than 7 to 8 rules of Dr. E. F. Codd

RDBMS usually satisfy more than 7 to 8 rules of Dr. E.F. Codd

Naming ConventionField Column, AttributesRecord Row, Tuple, EntityFile Table, Relation, Entity class

Page 63 of 63