Вы находитесь на странице: 1из 34

Introduction to Database

A database is a collection of information that is organized so that it can easily be accessed,


managed, and updated. It is the collection of schemas, tables, queries, reports, views, and
other objects.
In computing, databases are sometimes classified according to their organizational approach.
The most prevalent approach is the relational database, a tabular database in which data is
defined so that it can be reorganized and accessed in a number of different ways. A
distributed database is one that can be dispersed or replicated among different points in a
network. An object-oriented programming database is one that is congruent with the data
defined in object classes and subclasses.
Computer databases typically contain aggregations of data records or files, such as sales
transactions, product catalogs and inventories, and customer profiles. Typically, a database
manager provides users the capabilities of controlling read/write access, specifying report
generation, and analyzing usage.
A database management system (DBMS) is a computer software application that interacts
with the user, other applications, and the database itself to capture and analyze data. A
general-purpose DBMS is designed to allow the definition, creation, querying, update, and
administration of databases. Well-known DBMSs include MySQL, MongoDB, Microsoft
SQL Server, Oracle, etc.

Oracle Database
Oracle Database (commonly referred to as Oracle RDBMS or simply as Oracle) is an object-
relational database management system produced and marketed by Oracle Corporation. It is
most widely database used in the world. It runs virtually every kind of computer. It functions
virtually identically on all the machines, so when we learn it on one, we can use it on any
other. This fact makes knowledgeable oracle user and developers very much in demand, and
makes oracle knowledge and skills very portable.
Oracle is an Object-relational database. A relational database is an extremely simple way of
thinking and managing the data used in business. It is nothing more than a collection of tables
of data. We all encounter table every day: weather reports, stocks charts, sports scores. These
all tables, with column headings and rows of information simply presented. Even so the
relational approach can be sophisticated and powerful enough for even the most complex of
business. An object relational database supports all of the features of a relational database
while also supporting object-oriented concepts and features.
Oracle has grown from its humble beginnings as one of a number of databases available in
the 1970s to the market leader of today. In its early days, Oracle Corporation was known
more as an aggressive sales and promotion organization than a technology supplier. Over the
years, the Oracle database has grown in depth and quality, and its technical capabilities now
are generally recognized as the most advanced. With each release, Oracle has added more
power and features to its already solid base while improving the manageability.

1|Page
Oracle 10g
As of the Oracle Database 10g release, Oracle Corporation seems to have started to make an
effort to standardize all current versions of its major products using the "10g" label. Major
products include:

Oracle Database 10g


Oracle Application Server 10g a middleware product
Oracle Enterprise Manager 10g
Oracle Applications Release 11i (also known as Oracle e-Business Suite, Oracle
Financials or Oracle 11i) a suite of business applications
Oracle Developer Suite 10g
Oracle JDeveloper 10g a Java integrated development environment

Oracle Database 10g


Oracle Database 10g was the first RDBMS release from Oracle Corporation designed for grid
computing, the most flexible and cost-effective way to manage enterprise information. It cut
costs of management while providing the highest possible quality of service. Grid computing
is all about computing as a utility. If you are a client, you need not know where your data
resides and which computer stores it. You should be able to request information or
computation on your data and have it delivered to you.
Oracle Database 10g manages all your data. This is not just the object relational data that you
expect an enterprise database to manage. It can also be unstructured data such as:
Spreadsheets
Word documents
PowerPoint presentations
XML
Multimedia data types like MP3, graphics, video, and more
The data does not even have to be in the database. Oracle Database 10g has services through
which you can store metadata about information stored in file systems. You can use the
database server to manage and serve information wherever it is located.
The Oracle10g release offers a comprehensive high-performance infrastructure, including:
Scalability from departments to enterprise e-business sites
Robust, reliable, available, and secure architecture
One development model; easy deployment options
One management interface for all applications
Industry standard technologies; no proprietary lock-in

SQL

Using SQL, you can communicate with the Oracle server.

2|Page
The history of SQL begins in an IBM laboratory in San Jose, California, where SQL
was developed in the late 1970s.
SQL stands for Structured Query Language, and the language itself is often referred to
as "sequel."
It is a standard and programming language.
SQL lets you access and manipulate databases.
It was originally developed for IBM'sDB2 product.
American National Standard Institute is primary organization for fostering of
technology standard. Long established computer standard includes the American code
for information interchange (ANSI).
SQL is a nonprocedural language, in contrast to the procedural or third generation
languages (3GLs) such as COBOL and C that had been created up to that time.
Nonprocedural means what rather than how. For example, SQL describes what data to
retrieve, delete, or insert, rather than how to perform the operation.
Some common RDBMS that used SQL are ORACLE, CYBASE, and Microsoft SQL
SERVER.

Oracles RDBMS
Oracle provides a flexible RDBMS called Oracle Database 10g. Using its features, you can
store and manage data with all the advantages of a relational structure plus PL/SQL, an
engine that provides you with the ability to store and execute program units. Oracle
Database 10g also supports Java and XML. The Oracle server offers the options of retrieving
data based on optimization techniques. It includes security features that control how a
database is accessed and used. Other features include consistency and protection of data
through locking mechanisms.
The Oracle10g release provides an open, comprehensive, and integrated approach to
information management. An Oracle server consists of an Oracle database and an Oracle
server instance. Every time a database is started, a system global area (SGA) is allocated and
Oracle background processes are started. The SGA is an area of memory that is used for
database information shared by the database users. The combination of the background
processes and memory buffers is called an Oracle instance.

SQL Statements

Oracle SQL complies with industry-accepted standards. Oracle Corporation ensures future
compliance with evolving standards by actively involving key personnel in SQL standards
committees. Industry-accepted committees are the American National Standards Institute
(ANSI) and the International Standards Organization (ISO). Both ANSI and ISO have
accepted SQL as the standard language for relational databases.

3|Page
Statement Description
SELECT
Retrieves data from the database, enters new rows, changes existing
INSERT
rows, and removes unwanted rows from tables in the database,
UPDATE
respectively.
DELETE
Collectively known as data manipulation language (DM L).
MERGE
CREATE
ALTER
DROP Sets up, changes, and removes data structures from tables.
RENAME Collectively known as data definition language (DDL).
TRUNCATE
COMMENT
Gives or removes access rights to both the Oracle database and the
GRANT
structures within it. Collectively known as data control language
REVOKE
(DCL).
COMMIT Manages the changes made by DML statements. Changes to the data
ROLLBACK can be grouped together into logical transactions. Collectively
SAVEPOINT known as Transaction control (TC).

SELECT Statement

A SELECT statement retrieves information from the database. With a SELECT statement,
you can use the following capabilities:
Projection: Choose the columns in a table that are returned by a query. Choose as
few or as many of the columns as needed.
Selection: Choose the rows in a table that are returned by a query. Various criteria
can be used to restrict the rows that are retrieved.
Joining: Bring together data that is stored in different tables by specifying the link
between them.
In its simplest form, a SELECT statement must include the following:
A SELECT clause, which specifies the columns to be displayed.
A FROM clause, which identifies the table containing the columns that are listed in
the SELECT clause.

Syntax:
SELECT *| {[DISTINCT] column | expression [alias]...} FROM table;

In the syntax:
SELECT is a list of one or more columns
* selects all columns
DISTINCT suppresses duplicates
column | expression selects the named column or the expression
alias gives selected columns different headings
FROM table specifies the table containing the columns

4|Page
Selecting All Columns of All Rows
You can display all columns of data in a table by following the SELECT keyword with
an
asterisk (*).You can also display all columns in the table by listing all the columns after
the SELECT keyword.
SELECT * FROM table_name;
SELECT col1, col2 ... coln FROM table_name;

Selecting Specific Columns of All Rows


You can use the SELECT statement to display specific columns of the table by
specifying
the column names, separated by commas.
SELECT location_id, department_id FROM departments;

Arithmetic Expressions
You may need to modify the way in which data is displayed, or you may want to perform
calculations or look at what-if scenarios. These are all possible using arithmetic expressions.
An arithmetic expression can contain column names, constant numeric values, and the
arithmetic operators.

Arithmetic Operators
The arithmetic operators that are available in SQL are:
* Multiply
/ Divide
- Subtract
+ Add
You can use arithmetic operators in any clause of a SQL statement (except the FROM
clause).
Eg:- SELECT last_name, salary, salary + 300 FROM employees;

Null Values
If a row lacks a data value for a particular column, that value is said to be null or to contain a
null. A null is a value that is unavailable, unassigned, unknown, or inapplicable. A null is not
the same as a zero or a space. Zero is a number, and a space is a character.
Columns of any data type can contain nulls. However, some constraints (NOT NULL and
PRIMARY KEY) prevent nulls from being used in the column.
If any column value in an arithmetic expression is null, the result is null. For example, if you
attempt to perform division by zero, you get an error. However, if you divide a number by
null, the result is a null or unknown.

Column Alias
Renames a column heading
Is useful with calculations
Immediately follows the column name (There can also be the optional AS
keyword between the column name and alias.)

5|Page
Requires double quotation marks if it contains spaces or special characters or if it
is case sensitive.
Eg:- SELECT last_name AS name, commission_pct comm FROM employees;
Eg:- SELECT last_name "Name" , salary*12 "Annual Salary" FROM employees;

Concatenation Operator
You can link columns to other columns, arithmetic expressions, or constant values to create
a character expression by using the concatenation operator (||). Columns on either side of
the operator are combined to make a single output column.
Eg: SELECT last_name||job_id AS "Employees" FROM employees;
The AS keyword before the alias name makes the SELECT clause easier to read.
If you concatenate a null value with a character string, the result is a character string.
LAST_NAME || NULL results in LAST_NAME.
Literal Character Strings
A literal is a character, a number, or a date that is included in the SELECT list and that is
not
a column name or a column alias. It is printed for each row returned. Literal strings of
free format text can be included in the query result and are treated the same as a column
in the
SELECT list.
Date and character literals must be enclosed by single quotation marks (' '); number
literals
need not be so enclosed.
Eg: In the following example, the last name and salary for each employee are concatenated
with a literal to give the returned rows more meaning:
SELECT last_name ||': 1 Month salary = '||salary Monthly FROM employees;
Alternative Quote (q) Operator
Many SQL statements use character literals in expressions or conditions. If the literal
itself
contains a single quotation mark, you can use the quote (q) operator and choose your own
quotation mark delimiter.
You can choose any convenient delimiter, single-byte or multibyte, or any of the
following
character pairs: [ ], { }, ( ), or < >.
Eg: SELECT department_name || q'[, it's assigned Manager Id: ]' || manager_id
AS "Department and Manager" FROM departments;
The string contains a single quotation mark, which is normally interpreted as a delimiter of a
character string. By using the q operator, however, the brackets [] are used as the quotation
mark delimiter. The string between the brackets delimiters is interpreted as a literal character
string.

Restricting and Sorting Data

6|Page
Limiting the Rows That Are Selected
You can restrict the rows that are returned from the query by using the WHERE clause. A
WHERE clause contains a condition that must be met, and it directly follows the FROM
clause. If the condition is true, the row meeting the condition is returned.
Syntax: SELECT * | {[DISTINCT] column | expression [alias],...} FROM table
[WHERE condition(s)];
In the syntax:
WHERE restricts the query to rows that meet a condition
condition is composed of column names, expressions, constants, and a comparison operator
The WHERE clause can compare values in columns, literal values, arithmetic expressions, or
functions. It consists of three elements:
- Column name
- Comparison condition
- Column name, constant, or list of values

Character Strings and Dates


Character strings and dates in the WHERE clause must be enclosed by single quotation
marks(''). Number constants, however, should not be enclosed by single quotation marks.
All character searches are case-sensitive. In the following example, no rows are returned
because the EMPLOYEES table stores all the last names in mixed case:
SELECT last_name, job_id, department_id FROM employees
WHERE last_name = 'WHALEN';
Oracle databases store dates in an internal numeric format, representing the century, year,
month, day, hours, minutes, and seconds. The default date display is DD-MON-RR.

Comparison Conditions
Operator Meaning

<> Not equal to

Between two values BETWEEN

IN(set) Match any of a list of values

LIKE Match a character pattern

IS NULL Is a null value

< Less than

<= Less than or equal to

>= Greater than or equal to

> Greater than

= Equal to
Comparison conditions are used in conditions that compare one expression to another value
or expression. They are used in the WHERE clause in the following format:

7|Page
Syntax
... WHERE expr operator value
Example:
... WHERE hire_date = '01-JAN-95'
... WHERE salary >= 6000
... WHERE last_name = 'Smith'
An alias cannot be used in the WHERE clause.
Using the BETWEEN Condition
You can display rows based on a range of values using the BETWEEN range condition.
The range that you specify contains a lower limit and an upper limit.
Eg: SELECT last_name, salary FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;
Values that are specified with the BETWEEN condition are inclusive. You must specify
the lower limit first. You can also use the BETWEEN condition on character values:
Eg: SELECT last_name FROM employees
WHERE last_name BETWEEN 'King' AND 'Smith';

Using the IN Condition


To test for values in a specified set of values, use the IN condition. The IN condition is
also known as the membership condition.
Eg: SELECT employee_id, last_name, salary, manager_id FROM employees
WHERE manager_id IN (100, 101, 201) ;
The IN condition can be used with any data type. The following example returns a row
from the EMPLOYEES table for any employee whose last name is included in the list of
names in the WHERE clause:
SELECT employee_id, manager_id, department_id FROM employees
WHERE last_name IN ('Hartstein', 'Vargas');
If characters or dates are used in the list, they must be enclosed by single quotation marks.

Using the LIKE Condition


You may not always know the exact value to search for. You can select rows that match a
character pattern by using the LIKE condition. The character patternmatching operation
is referred to as a wildcard search. Two symbols can be used to construct the search
string.
% Represents any sequence of zero or more characters
_ Represents any single character

Eg: SELECT first_name FROM employees WHERE first_name LIKE 'S%';


This SELECT statement returns the employee first name from the EMPLOYEES
table for any employee whose first name begins with the letter S. Names beginning with
an s are not returned.
The LIKE condition can be used as a shortcut for some BETWEEN comparisons. The
following example displays the last names and hire dates of all employees who joined
between January 1995 and December 1995:
SELECT last_name, hire_date FROM employees WHERE hire_date LIKE '%95';

8|Page
Using the NULL Conditions
The NULL conditions include the IS NULL condition and the IS NOT NULL condition.
The IS NULL condition tests for nulls. A null value means the value is unavailable,
unassigned, unknown, or inapplicable. Therefore, you cannot test with = because a null
cannot be equal or unequal to any value.
Eg: SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL ;
This example retrieves the last names and managers of all employees who do not have a
manager.
Eg: To display last name, job ID, and commission for all employees who are not entitled
to receive a commission, use the following SQL statement:
SELECT last_name, job_id, commission_pct FROM employees
WHERE commission_pct IS NULL;

Logical Conditions
A logical condition combines the result of two component conditions to produce a single
result based on those conditions, or it inverts the result of a single condition. A row is
returned only if the overall result of the condition is true. Three logical operators are
available in SQL: AND, OR, NOT

Using the AND Operator


Eg: SELECT employee_id, last_name, job_id, salary FROM employees
WHERE salary >=10000 AND job_id LIKE '%MAN%' ;
Here both conditions must be true for any record to be selected. Therefore, only
employees who have a job title that contains the string MAN and earn $10,000 or more
are selected. All character searches are case-sensitive. No rows are returned if MAN is
not uppercase. Character strings must be enclosed by quotation marks.
AND Truth Table
The following table shows the results of combining two expressions with AND:
AND TRUE FALSE NULL
TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL

Using the OR Operator


Eg: SELECT employee_id, last_name, job_id, salary FROM employees
WHERE salary >= 10000 OR job_id LIKE '%MAN%' ;
In the example, either condition can be true for any record to be selected. Therefore, any
employee who has a job ID that contains the string MAN or earns $10,000 or more is
selected.
OR Truth Table
The following table shows the results of combining two expressions with OR:

OR TRUE FALSE NULL


TRUE TRUE TRUE TRUE
FALSE TRUE FALSE NULL
NULL TRUE NULL NULL

9|Page
Using the NOT Operator
Eg: SELECT last_name, job_id FROM employees WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
The example displays the last name and job ID of all employees whose job ID is not
IT_PROG, ST_CLERK, or SA_REP.
NOT Truth Table
The following table shows the result of applying the NOT operator to a condition:
NOT TRUE FALSE NULL

FALSE TRUE NULL

Using the ORDER BY Clause


Sort retrieved rows with the ORDER BY clause:
ASC: ascending order, default
DESC: descending order
The ORDER BY clause comes last in the SELECT statement:
SELECT last_name, job_id, department_id, hire_date FROM
employees
ORDER BY hire_date ;

Using Single-Row Functions to Customize Output

Single row functions can be character functions, numeric functions, date functions, and
conversion functions. Note that these functions are used to manipulate data items. These
functions require one or more input arguments and operate on each row, thereby returning
one output value for each row. Argument can be a column, literal or an expression. Single
row functions can be used in SELECT statement, WHERE and ORDER BY clause. Single
row functions can be -
General functions - Usually contains NULL handling functions. The functions under
the category are NVL, NVL2, NULLIF, COALESCE, CASE, DECODE.
Case Conversion functions - Accepts character input and returns a character value.
Functions under the category are UPPER, LOWER and INITCAP.
o UPPER function converts a string to upper case.
o LOWER function converts a string to lower case.
o INITCAP function converts only the initial alphabets of a string to upper case.
Character functions - Accepts character input and returns number or character value.
Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD,
RPAD, TRIM and REPLACE.
o CONCAT function concatenates two string values.
o LENGTH function returns the length of the input string.
o SUBSTR function returns a portion of a string from a given start point to an
end point.
o INSTR function returns numeric position of a character or a string in a given
string.

10 | P a g e
o
LPAD and RPAD functions pad the given string upto a specific length with a
given character.
o TRIM function trims the string input from the start or end.
o REPLACE function replaces characters from the input string with a given
character.
Date functions - Date arithmetic operations return date or numeric values. Functions
under the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY,
LAST_DAY, ROUND and TRUNC.
o MONTHS_BETWEEN function returns the count of months between the two
dates.
o ADD_MONTHS function add 'n' number of months to an input date.
o NEXT_DAY function returns the next day of the date specified.
o LAST_DAY function returns last day of the month of the input date.
o ROUND and TRUNC functions are used to round and truncates the date
value.
Number functions - Accepts numeric input and returns numeric values. Functions
under the category are ROUND, TRUNC, and MOD.
o ROUND and TRUNC functions are used to round and truncate the number
value.
o MOD is used to return the remainder of the division operation between two
numbers.
Illustrations
The SELECT query below demonstrates the use of NVL function.
SELECT first_name, last_name, salary, NVL (commission_pct,0)
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of case conversion functions.
SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id)
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of CONCAT function to concatenate
two string values.
SELECT CONCAT (first_name, last_name)
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of SUBSTR and INSTR functions.
SUBSTR function returns the portion of input string from 1st position to 5th position.
INSTR function returns the numeric position of character 'a' in the first name.
SELECT SUBSTR (first_name,1,5), INSTR (first_name,'a')
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print
the employee and job information.
SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_')
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of ROUND and TRUNC functions.
SELECT ROUND (1372.472,1) FROM dual;
SELECT TRUNC (72183,-2) FROM dual;

11 | P a g e
The SELECT query below shows a date arithmetic function where difference of
employee hire date and sysdate is done.
SELECT employee_id, (sysdate - hire_date) Employment_days
FROM employees WHERE rownum < 5;
The SELECT query below demonstrates the use of MONTHS_BETWEEN,
ADD_MONTHS, NEXT_DAY and LAST_DAY functions.
SELECT employee_id, MONTHS_BETWEEN (sysdate, hire_date)
Employment_months FROM employees WHERE rownum < 5;
SELECT ADD_MONTHS (sysdate, 5), NEXT_DAY (sysdate), LAST_DAY (sysdate)
FROM dual;

Reporting Aggregate data using the Group functions


SQL has numerous predefined aggregate functions that can be used to write queries to
produce exactly this kind of information. The GROUP BY clause specifies how to group
rows from a data table when aggregating information, while the HAVING clause filters out
rows that do not belong in specified groups.
Aggregate functions perform a variety of actions such as counting all the rows in a table,
averaging a column's data, and summing numeric data. Aggregates can also search a table to
find the highest "MAX" or lowest "MIN" values in a column. As with other types of queries,
you can restrict, or filter out the rows these functions act on with the WHERE clause. For
example, if a manager needs to know how many employees work in an organization, the
aggregate function named COUNT(*) can be used to produce this information. The
COUNT(*) function shown in the below SELECT statement counts all rows in a table.
SELECT COUNT(*)
FROM employees;
The result table for the COUNT(*) function is a single column from a single row known as a
scalar result or value. Some of the commonly used aggregate functions are as below -
SUM( [ALL | DISTINCT] expression )
AVG( [ALL | DISTINCT] expression )
COUNT( [ALL | DISTINCT] expression )
COUNT(*)
MAX(expression)
MIN(expression)
The ALL and DISTINCT keywords are optional, and perform as they do with the SELECT
clauses. The ALL keyword is the default where the option is allowed. The expression listed
in the syntax can be a constant, a function, or any combination of column names, constants,
and functions connected by arithmetic operators. However, aggregate functions are most
often used with a column name. Except COUNT function, all the aggregate functions
consider NULL values.
There are two rules that you must follow when using aggregates:
Aggregate functions can be used in both the SELECT and HAVING clauses.
Aggregate functions cannot be used in a WHERE clause.

Illustrations
The below SELECT query counts the number of employees in the organization.

12 | P a g e
SELECT COUNT(*) Count FROM employees;
The below SELECT query returns the average of the salaries of employees in the
organization.
SELECT AVG(Salary) average_sal FROM employees;
The below SELECT query returns the sum of the salaries of employees in the
organization.
SELECT SUM(Salary) total_sal FROM employees;
The below SELECT query returns the oldest and latest hired dates of employees in the
organization.
SELECT MIN (hire_date) oldest, MAX (hire_date) latest FROM employees;

GROUP BY

Aggregate functions are normally used in conjunction with a GROUP BY clause. The
GROUP BY clause enables you to use aggregate functions to answer more complex
managerial questions such as:
What is the average salary of employees in each department?
How many employees work in each department?
How many employees are working on a particular project?
Group by function establishes data groups based on columns and aggregates the information
within a group only. The grouping criterion is defined by the columns specified in GROUP
BY clause. Following this hierarchy, data is first organized in the groups and then WHERE
clause restricts the rows in each group.
Guidelines of using GROUP BY clause
(1) All the dependent columns or columns used in GROUP BY function must form the basis
of grouping, hence must be included in GROUP BY clause also.
(2) GROUP BY clause does not support the use of column alias, but the actual names.
(3) GROUP BY clause can only be used with aggregate functions like SUM, AVG, COUNT,
MAX, and MIN. If it is used with single row functions,
(4) Aggregate functions cannot be used in a GROUP BY clause.Below query lists the count
of employees working in each department.
SELECT DEPARTMENT_ID, COUNT (*)
FROM employees
GROUP BY DEPARTMENT_ID;
Similarly, below query to find sum of salaries for respective job ids in each department. Note
the group is established based on Department and Job id. So they appear in GROUP BY
clause.
SELECT DEPARTMENT_ID, JOB_ID, SUM (SAL)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
The below query also produces the same result. Please note that grouping is based on the
department id and job id columns but not used for display purpose.
SELECT SUM (SALARY)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;

13 | P a g e
Use of DISTINCT, ALL keywords with Aggregate functions

By specifying DISTINCT keyword with the input parameter, group by function considers
only the unique value of the column for aggregation. By specifying ALL keyword with the
input parameter, group by function considers all the values of the column for aggregation,
including nulls and duplicates. ALL is the default specification.

The HAVING clause

The HAVING clause is used for aggregate functions in the same way that a WHERE clause
is used for column names and expressions. Essentially, the HAVING and WHERE clauses do
the same thing, that is filter rows from inclusion in a result table based on a condition. While
it may appear that a HAVING clause filters out groups, it does not. Rather, a HAVING
clause filters rows.
When all rows for a group are eliminated so is the group. To summarize, the important
differences between the WHERE and HAVING clauses are:
A WHERE clause is used to filter rows BEFORE the GROUPING action (i.e., before
the calculation of the aggregate functions).
A HAVING clause filters rows AFTER the GROUPING action (i.e., after calculation
of the aggregate functions).
SELECT JOB_ID, SUM (SALARY) FROM employees
GROUP BY JOB_ID HAVING SUM (SALARY) > 10000;
The HAVING clause is a conditional option that is directly related to the GROUP BY
clause option because a HAVING clause eliminates rows from a result table based on
the result of a GROUP BY clause.

Displaying Data from Multiple Tables


The related tables of a large database are linked through the use of foreign and primary keys
or what are often referred to as common columns. The ability to join tables enables to add
more meaning to the result table that is produced. For 'n' number tables to be joined in a
query, minimum (n-1) join conditions are necessary. Based on the join conditions, Oracle
combines the matching pair of rows and displays the one which satisfies the join condition.
Joins are classified as below
Natural join (also known as an equijoin or a simple join) - Creates a join by using a
commonly named and defined column.
Non-equality join - Joins tables when there are no equivalent rows in the tables to be
joined-for example, to match values in one column of a table with a range of values in
another table.
Self-join - Joins a table to itself.
Outer join - Includes records of a table in output when there's no matching record in
the other table.

14 | P a g e
Cartesian join (also known as a Cartesian product or cross join) - Replicates each row
from the first table with every row from the second table. Creates a join between
tables by displaying every possible record combination.
Natural Join
The NATURAL keyword can simplify the syntax of an equijoin. A NATURAL JOIN is
possible whenever two (or more) tables have columns with the same name, and the columns
are join compatible, i.e., the columns have a shared domain of values. The join operation
joins rows from the tables that have equal column values for the same named columns.
Eg: Consider the one-to-many relationship between the DEPARTMENTS and EMPLOYEES
tables. Each table has a column named DEPARTMENT_ID. This column is the primary key
of the DEPARTMENTS table and a foreign key of the EMPLOYEES table.
SELECT E.first_ name NAME, D.department_name DNAME
FROM employees E NATURAL JOIN departments D;

Eg: The below SELECT query joins the two tables by explicitly specifying the join condition
with the ON keyword.
SELECT E.first_name NAME,D.department_name DNAME
FROM employees E JOIN departments D
ON (E.department_id = D.department_id);

USING Clause Using Natural joins, Oracle implicitly identify columns to form the basis of
join. Many situations require explicit declaration of join conditions. In such cases, we use
USING clause to specify the joining criteria. Since, USING clause joins the tables based on
equality of columns, it is also known as Equijoin. They are also known as Inner joins or
simple joins.
Syntax:
SELECT <column list>
FROM TABLE1 JOIN TABLE2
USING (column name)

Consider the below SELECT query, EMPLOYEES table and DEPARTMENTS table are
joined using the common column DEPARTMENT_ID.
SELECT E.first_name NAME,D.department_name DNAME
FROM employees E JOIN departments D
USING (department_id);

Self Join
A SELF-JOIN operation produces a result table when the relationship of interest exists
among rows that are stored within a single table. In other words, when a table is joined to
itself, the join is known as Self Join.

15 | P a g e
Consider EMPLOYEES table, which contains employee and their reporting managers. To
find manager's name for an employee would require a join on the EMP table itself. This is a
typical candidate for Self Join.
SELECT e1.FirstName Manager,e2.FirstName Employee
FROM employees e1 JOIN employees e2
ON (e1.employee_id = e2.manager_id)
ORDER BY e2.manager_id DESC;
Non Equijoins
A non-equality join is used when the related columns can't be joined with an equal sign-
meaning there are no equivalent rows in the tables to be joined. A non-equality join enables
you to store a range's minimum value in one column of a record and the maximum value in
another column. So instead of finding a column-to-column match, you can use a non-equality
join to determine whether the item being shipped falls between minimum and maximum
ranges in the columns. If the join does find a matching range for the item, the corresponding
shipping fee can be returned in the results. As with the traditional method of equality joins, a
non-equality join can be performed in a WHERE clause. In addition, the JOIN keyword can
be used with the ON clause to specify relevant columns for the join.
SELECT E.first_name, J.job_hisal, J.job_losal, E.salary
FROM employees E JOIN job_sal J
ON (E.salary BETWEEN J.job_losal AND J.job_losal);

Outer Joins
An Outer Join is used to identify situations where rows in one table do not match rows in a
second table, even though the two tables are related.
There are three types of outer joins: the LEFT, RIGHT, and FULL OUTER JOIN. They all
begin with an INNER JOIN, and then they add back some of the rows that have been
dropped. A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left)
table in the join condition, and output columns from the second (right) table are set to NULL.
A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table
in the join condition, and output columns from the first (left) table are set to NULL. The
FULL OUTER JOIN adds back all the rows that are dropped from both the tables.
Right Outer Join
A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table
in the join condition, and output columns from the first (left) table are set to NULL. Note the
below query lists the employees and their corresponding departments. Also no employee has
been assigned to department 30.
SELECT E.first_name, E.salary, D.department_id
FROM employees E, departments D
WHERE E.DEPARTMENT_ID (+) = D.DEPARTMENT_ID;

Left Outer Join

16 | P a g e
A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left) table in
the join condition, and output columns from the second (right) table are set to NULL. The
query demonstrated above can be used to demonstrate left outer join, by exchanging the
position of (+) sign.
SELECT E.first_name, E.salary, D.department_id
FROM employees E, departments D
WHERE D.DEPARTMENT_ID = E.DEPARTMENT_ID (+);

Full Outer Join

The FULL OUTER JOIN adds back all the rows that are dropped from both the tables. Below
query shows lists the employees and their departments. Note that employee 'MAN' has not
been assigned any department till now (its NULL) and department 30 is not assigned to any
employee.
SELECT nvl (e.first_name,'-') first_name, nvl (to_char (d.department_id),'-') department_id
FROM employee e FULL OUTER JOIN department d
ON e. depARTMENT_ID = d. depARTMENT_ID;

Cartesian product or Cross join


For two entities A and B, A * B is known as Cartesian product. A Cartesian product consists
of all possible combinations of the rows from each of the tables. For example, joining the
employee table with eight rows and the department table with three rows will produce a
Cartesian product table of 24 rows (8 * 3 = 24). Cross join refers to the Cartesian product of
two tables. It produces cross product of two tables. The above query can be written using
CROSS JOIN clause.
A Cartesian product result table is normally not very useful. In fact, such a result table can be
terribly misleading. If you execute the below query for the EMPLOYEES and
DEPARTMENTS tables, the result table implies that every employee has a relationship with
every department, and we know that this is simply not the case!
SELECT E.first_name, D.DNAME
FROM employees E,departments D;
Cross join can be written as,
SELECT E.first_name, D.DNAME
FROM employees E CROSS JOIN departments D;

Using Sub queries to Solve Queries


A sub query is best defined as a query within a query. Sub queries enable you to write queries
that select data rows for criteria that are actually developed while the query is executing at
run time. More formally, it is the use of a SELECT statement inside one of the clauses of
another SELECT statement. In fact, a sub query can be contained inside another sub query,
which is inside another sub query, and so forth. A sub query can also be nested inside

17 | P a g e
INSERT, UPDATE, and DELETE statements. Sub queries must be enclosed within
parentheses.
A sub query can be used any place where an expression is allowed providing it returns a
single value. This means that a sub query that returns a single value can also be listed as an
object in a FROM clause listing. This is termed an inline view because when a sub query is
used as part of a FROM clause, it is treated like a virtual table or view. Sub query can be
placed either in FROM clause, WHERE clause or HAVING clause of the main query.
Oracle allows a maximum nesting of 255 sub query levels in a WHERE clause. There is no
limit for nesting sub queries expressed in a FROM clause. In practice, the limit of 255 levels
is not really a limit at all because it is rare to encounter sub queries nested beyond three or
four levels.
A sub query SELECT statement is very similar to the SELECT statement used to begin a
regular or outer query. The complete syntax of a sub query is:
( SELECT [DISTINCT] subquery_select_parameter
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ] ...]
[HAVING search_conditions] )
Types of Sub queries
Single Row Sub Query: Sub query which returns single row output. They mark the
usage of single row comparison operators, when used in WHERE conditions.
Multiple row sub query: Sub query returning multiple row output. They make use of
multiple row comparison operators like IN, ANY, ALL. There can be sub queries
returning multiple columns also.
Correlated Sub Query: Correlated subqueries depend on data provided by the outer
query.This type of subquery also includes subqueries that use the EXISTS operator to test
the existence of data rows satisfying specified criteria.

Single Row Sub Query


A single-row sub query is used when the outer query's results are based on a single, unknown
value. Although this query type is formally called "single-row," the name implies that the
query returns multiple columns-but only one row of results. However, a single-row sub query
can return only one row of results consisting of only one column to the outer query.
In the below SELECT query, inner SQL returns only one row i.e. the minimum salary for the
company. It in turn uses this value to compare salary of all the employees and displays only
those, whose salary is equal to minimum salary.
SELECT first_name, salary, department_id FROM employees
WHERE salary = (SELECT MIN (salary) FROM employees);

18 | P a g e
A HAVING clause is used when the group results of a query need to be restricted based on
some condition. If a sub query's result must be compared with a group function, you must
nest the inner query in the outer query's HAVING clause.
SELECT department_id, MIN (salary)
FROM employees
GROUP BY department_id
HAVING MIN (salary) < (SELECT AVG (salary) FROM employees)

Multiple Row Sub Query


Multiple-row sub queries are nested queries that can return more than one row of results to
the parent query. Multiple-row sub queries are used most commonly in WHERE and
HAVING clauses. Since it returns multiple rows, it must be handled by set comparison
operators (IN, ALL, ANY).While IN operator holds the same meaning as discussed in earlier
chapter, ANY operator compares a specified value to each value returned by the sub query
while ALL compares a value to every value returned by a sub query.
Below query shows the error when single row sub query returns multiple rows.
SELECT first_name, department_id FROM employees
WHERE department_id = (SELECT department_id FROM employees WHERE
LOCATION_ID = 100)

Usage of Multiple Row operators


[> ALL] More than the highest value returned by the subquery
[< ALL] Less than the lowest value returned by the subquery
[< ANY] Less than the highest value returned by the subquery
[> ANY] More than the lowest value returned by the subquery
[= ANY] Equal to any value returned by the subquery (same as IN)

Above SQL can be rewritten using IN operator like below.


SELECT first_name, department_id FROM employees
WHERE department_id IN (SELECT department_id FROM departments WHERE
LOCATION_ID = 100)

Note in the above query, IN matches department ids returned from the sub query, compares it
with that in the main query and returns employee's name who satisfy the condition.
Correlated Sub Query
As opposed to a regular sub query, where the outer query depends on values provided by the
inner query, a correlated sub query is one where the inner query depends on values provided
by the outer query. This means that in a correlated sub query, the inner query is executed
repeatedly, once for each row that might be selected by the outer query.
Correlated sub queries can produce result tables that answer complex management questions.

19 | P a g e
Consider the below SELECT query. Unlike the sub queries previously considered, the sub
query in this SELECT statement cannot be resolved independently of the main query. Notice
that the outer query specifies that rows are selected from the employee table with an alias
name of e1. The inner query compares the employee department number column
(Department Number) of the employee table with alias e2 to the same column for the alias
table name e1.
SELECT EMPLOYEE_ID, salary, department_id FROM employees E
WHERE salary > (SELECT AVG(salary) FROM EMP T
WHERE E.department_id = T.department_id)

Multiple Column Sub Query


A multiple-column sub query returns more than one column to the outer query and can be
listed in the outer query's FROM, WHERE, or HAVING clause. For example, the below
query shows the employee's historical details for the ones whose current salary is in range of
1000 and 2000 and working in department 10 or 20.
SELECT first_name, job_id, salary FROM emp_history
WHERE (salary, department_id) in (SELECT salary, department_id FROM employees
WHERE salary BETWEEN 1000 and 2000 AND department_id BETWEEN 10 and 20)
ORDER BY first_name;

When a multiple-column sub query is used in the outer query's FROM clause, it creates a
temporary table that can be referenced by other clauses of the outer query. This temporary
table is more formally called an inline view. The sub query's results are treated like any other
table in the FROM clause. If the temporary table contains grouped data, the grouped subsets
are treated as separate rows of data in a table. Consider the FROM clause in the below query.
The inline view formed by the sub query is the data source for the main query.
SELECT *
FROM (SELECT salary, department_id FROM employees
WHERE salary BETWEEN 1000 and 2000);

SET OPERATORS
The set operators combine the results of two or more component queries into one result. Queries
containing set operators are called compound queries.

Operator Returns
UNION All distinct rows selected by either query
UNION ALL All rows selected by either query, including all duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows that are selected by the first SELECT statement
and not selected in the second SELECT statement

All set operators have equal precedence. If a SQL statement contains multiple set operators,
the Oracle server evaluates them from left (top) to right (bottom) if no parentheses explicitly
specify another order.

20 | P a g e
UNION Operator
The UNION operator returns all rows that are selected by either query. Use the UNION
operator to return all rows from multiple tables and eliminate any duplicate rows. By
default, the output is sorted in ascending order of the first column of the SELECT
clause. Consider the following example showing use of UNION:
SELECT employee_id, job_id, department_id
FROM employees
UNION
SELECT employee_id, job_id, department_id
FROM job_history;

UNION ALL Operator


Use the UNION ALL operator to return all rows from multiple queries. The UNION
ALL operator returns results from both queries, including all duplications.

INTERSECT Operator
Use the INTERSECT operator to return all rows that are common to multiple queries.
The number of columns and the data types of the columns being selected by the
SELECT statements in the queries must be identical in all the SELECT statements used
in the query. The names of the columns need not be identical.
Example:
SELECT employee_id, job_id, department_id
FROM employees
INTERSECT
SELECT employee_id, job_id, department_id
FROM job_history;

MINUS Operator
Use the MINUS operator to return rows returned by the first query that are not present
in the second query (the first SELECT statement MINUS the second SELECT
statement). All of the columns in the WHERE clause must be in the SELECT clause
for the MINUS operator to work.
Example:
SELECT employee_id, job_id
FROM employees
MINUS
SELECT employee_id, job_id
FROM job_history;
Set Operator Guidelines
The expressions in the select lists of the queries must match in number and data type.
Queries that use UNION, UNION ALL, INTERSECT, and MINUS operators in their
WHERE clause must have the same number and type of columns in their SELECT list.
The ORDER BY clause:
Can appear only at the very end of the statement
Will accept the column name, an alias, or the positional notation
The column name or alias, if used in an ORDER BY clause, must be from the first
SELECT list.

21 | P a g e
Set operators can be used in subqueries.

The Oracle Server and Set Operators


When a query uses set operators, the Oracle server eliminates duplicate rows automatically
except in the case of the UNION ALL operator. The column names in the output are
decided by the column list in the first SELECT statement. By default, the output is sorted
in ascending order of the first column of the SELECT clause.

MANIPULATING DATA
Data manipulation language (DML) is a core part of SQL. When you want to add, update, or
delete data in the database, you execute a DML statement. A collection of DML statements
that form a logical unit of work is called a transaction.

Adding a New Row to a Table


You can add new rows to a table by issuing the INSERT statement.
Syntax
INSERT INTO table [(column [, column...])] VALUES (value [, value...]);
In the syntax:
table is the name of the table
column is the name of the column in the table to populate
value is the corresponding value for the column.

Example:
INSERT INTO departments (department_id,department_name, manager_id,
location_id)
VALUES (70, 'Public Relations', 100, 1700);

This statement with the VALUES clause adds only one row at a time to a table. List values in
the default order of the columns in the table. Optionally, list the columns in the INSERT clause.
Enclose character and date values in single quotation marks. Number values should not be
enclosed in single quotation marks, because implicit conversion may take place for numeric
values that are assigned to NUMBER data type columns if single quotation marks are included.

Methods for Inserting Null Values


There are two ways of inserting a null value in table:
Implicit: Omit the column from the column list.
Explicit: Specify the NULL keyword in the VALUES list;specify the empty string ('')
in the VALUES list for character stringsand dates.

Common errors that can occur during user input:


Mandatory value missing for a NOT NULL column
Duplicate value violates uniqueness constraint
Foreign key constraint violated
CHECK constraint violated
Data type mismatch
Value too wide to fit in column.

22 | P a g e
Inserting Special Values by Using SQL Functions
The SYSDATE function records the current date and time. Inserting Specific Date and Time
Values. The DD-MON-YY format is usually used to insert a date value. With this format, recall
that the century defaults to the current century. Because the date also contains time information,
the default time is midnight (00:00:00).

Creating a Script
You can save commands with substitution variables to a file and execute the commands in the
file. Run the script file and you are prompted for input for each of the & substitution variables.
After entering a value for the substitution variable, click the Continue button. The values that
you input are then substituted into the statement. This enables you to run the same script file
over and over but supply a different set of values each time you run it.
Example:
INSERT INTO departments(department_id, department_name, location_id)
VALUES (&department_id, '&department_name',&location);

Copying Rows from Another Table


You can use the INSERT statement to add rows to a table where the values are derived from
existing tables. In place of the VALUES clause, you use a subquery.
Syntax:
INSERT INTO table [ column (, column) ] subquery;
In the syntax:
table is the table name
column is the name of the column in the table to populate
subquery is the subquery that returns rows to the table

The number of columns and their data types in the column list of the INSERT clause must
match the number of values and their data types in the subquery. To create a copy of the rows
of a table, use SELECT * in the subquery:

INSERT INTO copy_emp


SELECT *
FROM employees;

Changing Data in a Table


You can modify existing rows by using the UPDATE statement. Update more than one row at
a time (if required). The UPDATE statement modifies specific rows if the WHERE clause is
specified.

Syntax:
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

In the syntax:
table is the name of the table
column is the name of the column in the table to populate
value is the corresponding value or subquery for the column

23 | P a g e
condition identifies the rows to be updated and is composed of column names,
expressions, constants, subqueries, and comparison operators

Example: UPDATE employees


SET department_id = 70
WHERE employee_id = 113;

Updating Two Columns with a Subquery


You can update multiple columns in the SET clause of an UPDATE statement by writing
multiple subqueries.
Syntax:
UPDATE table
SET column =(SELECT column
FROM table
WHERE condition [column = (SELECT column
FROM table
WHERE condition)]
[WHERE condition ] ;

Updating Rows Based on Another Table


You can use subqueries in UPDATE statements to update rows in a table. Use subqueries in
UPDATE statements to update rows in a table based on values from another table.

Example:
UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
WHERE employee_id = 100)
WHERE job_id = (SELECT job_id
FROM employees
WHERE employee_id = 200);

Removing a Row from a Table


You can remove existing rows by using the DELETE statement.
Syntax:
DELETE [FROM] table [WHERE condition];

Example: DELETE FROM departments


WHERE department_name = 'Finance';

All rows in the table are deleted if you omit the WHERE clause.

Deleting Rows Based on Another Table


You can use subqueries to delete rows from a table based on values from another table. Use
subqueries in DELETE statements to remove rows from a table based on values from another
table.
Example:
DELETE FROM employees
WHERE department_id =(SELECT department_id

24 | P a g e
FROM departments
WHERE department_name LIKE '%Public%');

TRUNCATE Statement
A more efficient method of emptying a table is with the TRUNCATE statement. We can use
the TRUNCATE statement to quickly remove all rows from a table or cluster.
Syntax:
TRUNCATE TABLE table_name;

Removing rows with the TRUNCATE statement is faster than removing them with the
DELETE statement for the following reasons:
The TRUNCATE statement is a data definition language (DDL) statement and
generates no rollback information.
If the table is the parent of a referential integrity constraint, you cannot truncate the
table. You need to disable the constraint before issuing the TRUNCATE statement.

DATA TRANSACTION
The Oracle server ensures data consistency based on transactions. Transactions give you more
flexibility and control when changing data, and they ensure data consistency in the event of
user process failure or system failure. Transactions consist of DML statements that make up
one consistent change to the data.

Transaction Types Type Description

Datamanipulation Consists of any number of DML statements that the Oracle


language (DML) server treats as a single entity or a logical unit of work
Data definition language Consists of only one DDL statement
(DDL)
Data control language Consists of only one DCL statement
(DCL)

When Does a Transaction Start and End?


A transaction begins when the first DML statement is encountered and ends when one of the
following occurs:
A COMMIT or ROLLBACK statement is issued.
A DDL statement, such as CREATE, is issued.
A DCL statement is issued.

Advantages of COMMIT and ROLLBACK Statements


With COMMIT and ROLLBACK statements, you can:
Ensure data consistency
Preview data changes before making changes permanent
Group logically related operations

Explicit Transaction Control Statements


You can control the logic of transactions by using the COMMIT, SAVEPOINT, and
ROLLBACK statements

25 | P a g e
Statement Description
COMMIT Ends the current transaction by making all pending data
changes permanent
SAVEPOINT name Marks a save point within the current transaction

ROLLBACK ROLLBACK ends the current transaction by discarding all


pending data changes.
ROLLBACK TO ROLLBACK TO SAVEPOINT rolls back the current
SAVEPOINT name transaction to the specified savepoint, thereby discarding any
changes and or savepoints that were created after the
savepoint to which you are rolling back. If you omit the TO
SAVEPOINT clause, the ROLLBACK statement rolls back the
entire transaction. Because savepoints are logical, there is no
way to list the savepoints that you have created.

State of the Data Before COMMIT or ROLLBACK


The previous state of the data can be recovered.
The current user can review the results of the DML operations by using the SELECT
statement.
Other users cannot view the results of the DML statements by the current user.
The affected rows are locked; other users cannot change the data in the affected rows.

State of the Data After COMMIT


Data changes are made permanent in the database.
The previous state of the data is permanently lost.
All users can view the results.
Locks on the affected rows are released; those rows are available for other users to
manipulate.
All save points are erased.

State of the Data After ROLLBACK


Discard all pending changes by using the ROLLBACK statement:
Data changes are undone.
Previous state of the data is restored.
Locks on the affected rows are released.

Read Consistency
Database users access the database in two ways:
1. Read operations (SELECT statement)
2. Write operations (INSERT, UPDATE, DELETE statements)
You need read consistency so that the following occur:
The database reader and writer are ensured a consistent view of the data.
Readers do not view data that is in the process of being changed.
Writers are ensured that the changes to the database are done in a consistent way.
Changes made by one writer do not disrupt or conflict with changes that another writer
is making.
The purpose of read consistency is to ensure that each user sees data as it existed at the last
commit, before a DML operation started.

26 | P a g e
USING DDL STATEMENTS TO CREATE AND MANAGE TABLES
Database Objects
An Oracle database can contain multiple data structures. Each structure should be outlined in
the database design so that it can be created during the build stage of database development.
Table: Stores data
View: Subset of data from one or more tables
Sequence: Generates numeric values
Index: Improves the performance of some queries
Synonym: Gives alternative names to objects

Oracle Table Structures


Tables can be created at any time, even while users are using the database.
You do not need to specify the size of a table. The size is ultimately defined by the
amount of space allocated to the database as a whole. It is important, however, to
estimate how much space a table will use over time.
Table structure can be modified online.

Naming Rules
You name database tables and columns according to the standard rules for naming any
Oracle database object:
Table names and column names must begin with a letter and be 130 characters long.
Names must contain only the characters AZ, az, 09, _ (underscore), $, and # (legal
characters, but their use is discouraged).
Names must not duplicate the name of another object owned by the same Oracle server
user.
Names must not be an Oracle server reserved word.

CREATE TABLE Statement


You create tables to store data by executing the SQL CREATE TABLE statement
Syntax:
CREATE TABLE [schema.] table (column datatype [DEFAULT expr][, ...]);
Example: CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);
It further confirms the creation of the table by issuing the DESCRIBE command.

Data Types
When you identify a column for a table, you need to provide a data type for the column.
There are several data types available:

Data Type Description


VARCHAR2(size) Variable-length character data (A maximum
size must be specified: minimum size is 1;
maximum size is 4,000.)

27 | P a g e
CHAR [(size)] Fixed-length character data of length size
bytes (Default and minimum size is 1;
maximum size is 2,000.)
NUMBER [(p,s)] Number having precision p and scale s
DATE Date and time values to the nearest second
between January 1,
4712 B.C., and December 31, 9999 A.D.
LONG Variable-length character data (up to 2 GB)
CLOB Character data (up to 4 GB)
BLOB Binary data (up to 4 GB)

Constraints
The Oracle server uses constraints to prevent invalid data entry into tables. Constraints can be
defined at the time of table creation or after the table has been created.
You can use constraints to do the following:
Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from
that table. The constraint must be satisfied for the operation to succeed.
Prevent the deletion of a table if there are dependencies from other tables
Provide rules for Oracle tools, such as Oracle Developer

Data Integrity Constraints

Constraint Description
NOT NULL Specifies that the column cannot contain a null value
UNIQUE Specifies a column or combination of columns whose
values
must be unique for all rows in the table
PRIMARY KEY Uniquely identifies each row of the table
FOREIGN KEY Establishes and enforces a foreign key relationship
between the
column and a column of the referenced table
CHECK Specifies a condition that must be true

Defining Constraints
We can create the constraints at either the column level or table level. Constraints defined at
the column level are included when the column is defined. Table-level constraints are defined
at the end of the table definition and must refer to the column or columns on which the
constraint pertains in a set of parentheses. NOT NULL constraints must be defined at the
column level.

Syntax:
CREATE TABLE [schema.] table (column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);

Column-level constraint: column [CONSTRAINT constraint_name] constraint_type,

28 | P a g e
Example: CREATE TABLE employees( employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),
...);

Table-level constraint: column,...[CONSTRAINT constraint_name] constraint_type


(column, ...),

Example: CREATE TABLE employees( employee_id NUMBER(6),


first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));

In the syntax:
schema is the same as the owners name
table is the name of the table
DEFAULT expr specifies a default value to use if a value is omitted in the
INSERT statement
Column is the name of the column
datatype is the columns data type and length
column_constraint is an integrity constraint as part of the column definition
table_constraint is an integrity constraint as part of the table definition

NOT NULL Constraint


The NOT NULL constraint ensures that the column contains no null values. Columns without
the NOT NULL constraint can contain null values by default. NOT NULL constraints must be
defined at the column level.

UNIQUE Constraint
A UNIQUE key integrity constraint requires that every value in a column or set of columns
(key) be uniquethat is, no two rows of a table can have duplicate values in a specified column
or set of columns. The column (or set of columns) included in the definition of the UNIQUE
key constraint is called the unique key. If the UNIQUE constraint comprises more than one
column, that group of columns is called a composite unique key.

PRIMARY KEY Constraint


A PRIMARY KEY constraint creates a primary key for the table. Only one primary key can
be created for each table. The PRIMARY KEY constraint is a column or set of columns that
uniquely identifies each row in a table. This constraint enforces uniqueness of the column or
column combination and ensures that no column that is part of the primary key can contain a
null value.

FOREIGN KEY Constraint


The FOREIGN KEY (or referential integrity) constraint designates a column or combination
of columns as a foreign key and establishes a relationship between a primary key or a unique

29 | P a g e
key in the same table or a different table.The foreign key is defined in the child table, and the
table containing the referenced column is the parent table. The foreign key is defined using a
combination of the following keywords:
FOREIGN KEY is used to define the column in the child table at the table-constraint
level.
REFERENCES identifies the table and column in the parent table.
ON DELETE CASCADE indicates that when the row in the parent table is deleted, the
dependent rows in the child table are also deleted.
ON DELETE SET NULL converts foreign key values to null when the parent value is
removed.
The default behavior is called the restrict rule, which disallows the update or deletion of
referenced data. Without the ON DELETE CASCADE or the ON DELETE SET NULL
options, the row in the parent table cannot be deleted if it is referenced in the child table.

CHECK Constraint
The CHECK constraint defines a condition that each row must satisfy. The condition can use
the same constructs as query conditions, with the following exceptions:
References to the CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns
Calls to SYSDATE, UID, USER, and USERENV functions
Queries that refer to other values in other rows
A single column can have multiple CHECK constraints that refer to the column in its definition.
There is no limit to the number of CHECK constraints that you can define on a column.

Integrity Constraint Error


When you have constraints in place on columns, an error is returned to you if you try to violate
the constraint rule. For example, if you attempt to update a record with a value that is tied to
an integrity constraint, an error is returned.If you attempt to delete a record with a value that is
tied to an integrity constraint, an error is returned.

Creating a Table from Rows in Another Table


A second method for creating a table is to apply the AS subquery clause, which both creates
the table and inserts rows returned from the subquery.
Syntax:
CREATE TABLE table [(column, column...)]
AS subquery;
In the syntax:
table is the name of the table
column is the name of the column, default value, and integrity constraint
subquery is the SELECT statement that defines the set of rows to be inserted into
the new table.

Example: CREATE TABLE dept80


AS
SELECT employee_id, last_name, salary*12 ANNSAL, hire_date
FROM employees
WHERE department_id = 80;

ALTER TABLE Statement


After you create a table, you may need to change the table structure. Use the ALTER TABLE
statement to:

30 | P a g e
Add a new column
Modify an existing column
Define a default value for the new column
Drop a column

Dropping a Table
The DROP TABLE statement removes the definition of an Oracle table. When you drop a
table, the database loses all the data in the table and all the indexes associated with it. All data
and structure in the table are deleted.
Any pending transactions are committed.
All indexes are dropped.
All constraints are dropped.
You cannot roll back the DROP TABLE statement.

Syntax :
DROP TABLE table
In the syntax, table is the name of the table.

CREATING OTHER SCHEMA OBJECTS


There are several other objects in a database in addition to tables. With views, you can present
and hide data from tables. Many applications require the use of unique numbers as primary key
values. You can either build code into the application to handle this requirement or use a
sequence to generate unique numbers. If you want to improve the performance of some queries,
you should consider creating an index. You can also use indexes to enforce uniqueness on a
column or a collection of columns. You can provide alternative names for objects by using
synonyms.

View
You can present logical subsets or combinations of data by creating views of tables. A view is
a logical table based on a table or another view. A view contains no data of its own but is like
a window through which data from tables can be viewed or changed. The tables on which a
view is based are called base tables. The view is stored as a SELECT statement in the data
dictionary.

Syntax:
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)]
AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];

In the syntax:
OR REPLACE re-creates the view if it already exists
FORCE creates the view regardless of whether or not the base tables exist
NOFORCE creates the view only if the base tables exist (This is the default.)
View is the name of the view
alias specifies names for the expressions selected by the views query.
subquery is a complete SELECT statement
WITH CHECK OPTION specifies that only those rows that are accessible to the view can
be inserted or updated

31 | P a g e
constraint is the name assigned to the CHECK OPTION constraint
WITH READ ONLY ensures that no DML operations can be performed on this view

Example:
CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS SELECT employee_id, first_name || ' '|| last_name, salary, department_id
FROM employees
WHERE department_id = 80;

Retrieving Data from a View


You can retrieve data from a view as you would from any table. You can display either the
contents of the entire view or just specific rows and columns.

Modifying a View
With the OR REPLACE option, a view can be created even if one exists with this name already,
thus replacing the old version of the view for its owner. This means that the view can be altered
without dropping, re-creating, and regranting object privileges.

Performing DML Operations on a View


You can perform DML operations on data through a view if those operations follow certain
rules.You can remove a row from a view unless it contains any of the following:
Group functions
A GROUP BY clause
The DISTINCT keyword
The pseudocolumn ROWNUM keyword

Using the WITH CHECK OPTION Clause


You can ensure that DML operations performed on the view stay in the domain of the
view by using the WITH CHECK OPTION clause:
CREATE OR REPLACE VIEW empvu20
AS SELECT *
FROM employees
WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;
Any attempt to change the department number for any row in the view fails because it
violates the WITH CHECK OPTION constraint.

Removing a View
You can remove a view without losing data because a view is based on underlying tables in the
database.
Syntax:
DROP VIEW view;

Advantages of Views
Views restrict access to the data because the view can display selected columns from
the table.

32 | P a g e
Views can be used to make simple queries to retrieve the results of complicated queries.
For example, views can be used to query information from multiple tables without the
user knowing how to write a join statement.
Views provide data independence for ad hoc users and application programs. One view
can be used to retrieve data from several tables.
Views provide groups of users access to data according to their particular criteria.

Sequences
A sequence is a database object that creates integer values. You can create sequences and then
use them to generate numbers. A sequence is a user-created database object that can be shared
by multiple users to generate integers. We can define a sequence to generate unique values or
to recycle and use the same numbers again. A typical usage for sequences is to create a primary
key value, which must be unique for each row. The sequence is generated and incremented (or
decremented) by an internal Oracle routine. This can be a time-saving object because it can
reduce the amount of application code needed to write a sequence-generating routine. Sequence
numbers are stored and generated independently of tables. Therefore, the same sequence can
be used for multiple tables.
Syntax:
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
In the syntax:
sequence is the name of the sequence generator
INCREMENT BY n specifies the interval between sequence numbers, where n is an
integer
START WITH n specifies the first sequence number to be generated
MAXVALUE n specifies the maximum value the sequence can generate
NOMAXVALUE specifies a maximum value of 10^27 for an ascending sequence
and 1 for a descending sequence
MINVALUE n specifies the minimum sequence value
NOMINVALUE specifies a minimum value of 1 for an ascending sequence and
(10^26) for a descending sequence

Modifying a Sequence
If you reach the MAXVALUE limit for your sequence, no additional values from the sequence
are allocated and you will receive an error indicating that the sequence exceeds the
MAXVALUE. To continue to use the sequence, you can modify it by using the ALTER
SEQUENCE statement.
Syntax
ALTER SEQUENCE sequence
[INCREMENT BY n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

33 | P a g e
Indexes
An Oracle server index is a schema object that can speed up the retrieval of rows by using a
pointer. Indexes can be created explicitly or automatically. If we do not have an index on the
column, then a full table scan occurs.An index provides direct and fast access to rows in a table.
Its purpose is to reduce the necessity of disk I/O by using an indexed path to locate data quickly.
The index is used and maintained automatically by the Oracle server. After an index is created,
no direct activity is required by the user. Indexes are logically and physically independent of
the table that they index. This means that they can be created or dropped at any time and have
no effect on the base tables or other indexes.

Creating an Index
Syntax:
CREATE INDEX index ON table (column[, column]...);

Removing an Index
Remove an index from the data dictionary by using the DROP INDEX command:
DROP INDEX index;
To drop an index, you must be the owner of the index or have the DROP ANY INDEX
privilege.

Synonyms
Synonyms are database objects that enable you to call a table by another name. We can create
synonyms to give an alternate name to a table.

Syntax:
CREATE [PUBLIC] SYNONYM synonym
FOR object;
In the syntax:
PUBLIC creates a synonym that is accessible to all users
synonym is the name of the synonym to be created
object identifies the object for which the synonym is created

Removing a Synonym
To remove a synonym, use the DROP SYNONYM statement. Only the database administrator
can drop a public synonym.
DROP SYNONYM synonym;

34 | P a g e

Вам также может понравиться