Oracle Database Basics
Oracle Database Basics
Oracle Database Basics
1. What is SQL?
➢ Structured Query Language (SQL) is the set of statements with which all Programs and Users
access data in an Oracle Database. The language, Structured English Query Language (SEQueL)
was developed by IBM Corporation. SEQueL later became SQL (still pronounced “sequel”). In
1979, Relational Software, Inc. (now Oracle) introduced the first commercially available
implementation of SQL.
➢ SQL Tasks:
(i) Querying data
(ii) Inserting, Updating and Deleting rows in a table
(iii) Creating, Replacing, Altering and Dropping objects
(iv) Controlling access to the Database and its objects
(v) Guaranteeing database consistency and integrity
2.1 Datatype
Each value manipulated by Oracle Database has a datatype. The datatype of a value associates a
fixed set of properties with the value. These properties cause Oracle to treat values of one datatype
differently from values of another.
The category of datatype divided into following sections:
2.1.1 Oracle Built-in Datatypes
2.1.2 ANSI, DB2, and SQL/DS Datatypes
2.1.3 User-Defined Types
2.1.4 Oracle-Supplied Types
A datatype is either Scalar or Non-Scalar. A scalar type contains an atomic value, whereas a non-
scalar (sometimes called as “Collections”) contains a set of values. A Large Object (LOB) is a special
form of scalar datatype representing a larger scalar value of binary or character data.
DINESH Page 1 of 18
2.1.1 Oracle Built-in Datatypes
2.1.1.1 Character Datatypes
2.1.1.2 Number Datatypes
2.1.1.3 Long and Raw Datatypes
2.1.1.4 Datetime Datatypes
2.1.1.5 Large Object Datatypes
2.1.1.6 ROWID Datatypes
DINESH Page 2 of 18
2.1.3 User-Defined Types
This is defined by User
2.1.4 Oracle-Supplied Types
(i) Any-Types
(ii) XML-Types
(iii) Spatial-Types
(iv) Media-Types
(v) Expression-Filter-Type
2.2 Literals
The term Literals and Constant values are synonymous and refer to a fixed data value. For
Example, ‘JACK’, ‘BLUE ISLANDS’, and ‘101’ are all character literals. 1000, 5000 are Numeric literals.
Character literals are enclosed in single quotation marks so that Oracle can distinguish them from schema
object names.
These are of 4 categories:
2.2.1 Text Literals
2.2.2 Numeric Literals
2.2.3 Datetime Literals
2.2.4 Interval Literals
DINESH Page 3 of 18
• C is any member of the user’s character set. You can include the quotation marks (‘’) in the text
literals made up of C characters. You can also include the quote-delimiter, as long as it is not
immediately followed by a single quotation mark.
• Quote-delimiter is any single or multibyte character except Space, Tab, and Return. If the
opening quote-delimiter is one of [, {, <, or (, then the closing quote-delimiter must be the
corresponding ], }, >, or ).
• A text literal can have maximum length of 4000 bytes.
Example:
q ‘! Name like ‘%DBMS-%%’ !’
q ‘< ‘So, ‘She said, ‘It’s finished.’ >’
q ‘ ” name like ‘[‘ “ ’
DINESH Page 4 of 18
2.2.3 Datetime Literals
Oracle supports four Datetime datatypes:
(A) Date
(B) Timestamp
(C) Timestamp with Time Zone
(D) Timestamp with Local Time Zone
• The Date Function SYSDATE returns the current system Date and Time
• The function CURRENT_DATE returns the current session Date.
DINESH Page 5 of 18
(A) INTERVAL YEAR TO MONTH
Syntax: Interval ‘Integer [-integer]’ YEAR [(Precision)] TO MONTH
Leading Field
Trailing Field This is the maximum number of digits in the Leading field. This
(Optional digit can be from 0 to 9. Default is 2.
Examples:
1. INTERVAL ‘123-2’ YEAR(3) TO MONTH
It means, Interval indicates 123 years, 2 months
2. INTERVAL ‘123’ YEAR(3)
An interval of 123 years, 0 months
3. INTERVAL ‘300’ MONTH(3)
An interval of 300 months
4. INTERVAL ‘4’ YEAR
Maps to INTERVAL ‘4-0’ YEAR TO MONTH and indicates 4 years
5. INTERVAL ‘50’ MONTH
Maps to INTERVAL ‘4-2’ YEAR TO MONTH and indicates 50 months or 4 years 2 months
6. INTERVAL ‘123’ YEAR
Returns an error, because the default precision is 2, and ‘123’ has 3 digits
7. We can add or subtract one interval literal with another.
INTERVAL ‘5-3’ YEAR TO MONTH i.e. 5 years 3 months
+
INTERVAL ‘20’ MONTH i.e. 1 year 8 months
=
INTERVAL ‘6-11’ YEAR TO MONTH i.e. 6 years 11 months
DINESH Page 6 of 18
• In the TO_BINARY_FLOAT and TO_BINARY_DOUBLE functions to Translate CHAR and
VARCHAR2 expressions to BINARY-FLOAT, or BINARY-DOUBLE values.
Examples:
TO_CHAR (5678, ‘9,999’) = ‘5,678’
TO_CHAR (45, ’99.99’) = ’45.00’
Examples:
TO_CHAR (SYSDATE, ‘DD-MM-YY’) = ’05-03-20’
TO_CHAR (SYSDATE, ‘DDTH’) = 04TH
TO_CHAR (SYSDATE, ‘DDSP’) = FOUR
TO_CHAR (SYSDATE, ‘DDSPTH’) = FOURTH
TO_CHAR (SYSDATE, ‘DDTHSP’) = FOURTH
TO_CHAR (SYSDATE, ‘fmDDTH’) = 4th
TO_CHAR (SYSDATE, ‘fmDay’) || ‘ Special’ = Tuesday’s Special
2.4 NULLS
• If a column in a row has no value, then the column is said to be NULL, or to contain
NULL.
• Any Arithmetic expression containing a NULL always evaluates to NULL. For example,
NULL added to 10 is NULL. In fact all operators (except concatenation) return NULL
when given a NULL operand.
• All Scalar functions (except REPLACE, NVL, and CONCAT) return NULL when given a
NULL argument.
• To test for NULLS, use only the comparison conditions IS NULL and IS NOT NULL.
• NULL represents a lack of data, a NULL cannot be equal or unequal to any value or to
another NULL.
• If you use any other condition with Nulls and the result depends on the value of the
NULL, then the result is UNKNOWN.
• A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a
SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN
returns no rows.
DINESH Page 7 of 18
Examples:
2.5 Comments
• Comments can make your application easier for you to read and maintain. Comments
within SQL statements do not affect the statement execution.
• A comment can appear between any keywords, parameters, or punctuation marks in
a statement. You can include a Comment in a statement in two ways:
(A) Begin the comment with a Slash and an Asterisk (/*). Proceed with the
text of the comment. This text can span multiple lines. End the comment with
an Asterisk and a Slash (*/).
(B) Begin the comment with two hyphens (--). Proceed with the text of the
comment. This text cannot extend to a new line. End the comment with a line
break.
• You can associate a comment with a Table, View, Materialized View, or Column using
the COMMENT Command. Comments associated with schema objects are stored in
the data dictionary.
DINESH Page 8 of 18
Object Tables
Objects Types
Object Views
Operators
Packages
Sequences
Stored Functions, Stored Procedures
Synonyms
Tables
Views
DINESH Page 9 of 18
The following schema objects shares one namespace:
Tables
Views
Sequences
Private Synonyms
Stand-alone Procedures
Stand-alone stored Functions
Packages
Materialized Views
User-defined Types
Each of the following nonschema objects also has its own namespace:
User Roles
Public Synonyms
Public Database Links
Tablespaces
Profiles
Parameter Files (PFILEs) and Server Parameter File (SPFILEs)
(F) Non-quoted identifiers are not case sensitive. Oracle interprets them as
Uppercase. Quoted identifiers are case sensitive.
3. Database
The Database is the repository for Data and the Engine that manages access to it. An Oracle
Database is a set of files on disk. It exists until these files are deliberately deleted. A Database
collects data, stores, and organizes data, and retrieves related data used by a business.
4. DBMS
A DataBase Management System (DBMS) controls the storage, organization, and retrieval of data.
In a DBMS, the Kernal code is the software piece that manages the storage and memory component
of the Database. There is Metadata in the DBMS that keeps track of all the components of the
Database, also known as the Dictionary. The Code or language used to retrieve data from the
Database is known as SQL.
DINESH Page 10 of 18
5. RDBMS
A Relational DataBase Management System (RDBMS) is an organized model of Subjects and
characteristics that have relationships among the subjects. RDBMS structures are easy to
understand and build. These structures are logically represented using the Entity-Relational (ER)
model.
6. ORDBMS
An RDBMS that implements Object-Oriented features such as User-defined Types, Inheritance, and
Polymorphism is called ORDBMS. It lets you create User-defined Object Types in the Relational
Database system.
8. Logical Model
In the design phase of the system development cycle, a Logical model of the database is created. A
logical model of an RDBMS is typically a block diagram of Entities and Relationships, referred to as
Entity-Relationship (ER) model or ER Diagram. An ER model has Entity, Relationship, and Attributes.
The Logical model also provides information known as access paths.
An Entity in a logical model is much like a Noun in grammar – a person, place or thing.
The characteristics of an Entity are known as its Attributes. Attributes are detailed
information about an entity that serves Qualify, Identify, Classify, or Quantify it.
There are Optional and Mandatory attributes. An Asterisk (*) along with the attribute
name indicates that it is mandatory. The Optional attribute may be indicated with a small
“o”.
Relationship identifies the relation between the tow or more entities. In the ER model, a
solid line (___) represents a mandatory relationship, and a Crowfoot represents the
“Many”. Optional occurrence is represented by a dotted line (-----).
Unique Identifier (UID) is represented in the diagram using a Pound (#) symbol.
DINESH Page 11 of 18
ER MODEL
There are three types of relationships can be defined between the Entities:
(i) One-to-One: A One-to-One relationship is one in which each occurrence of one entity is
represented by a single occurrence in another entity.
(iii) Many-to-Many: A Many-to-Many relationship is one in which an occurrence from one entity
can be represented by one or more occurrences in another entity, and an occurrence from the
second entity may be represented by one or many occurrences in the first entity.
Many-to-Many relationships should not exist in RDBMS because they cannot be properly joined
to represent a single row correctly. To solve this, create another entity that has an One-to-Many
relationship with the first entity and an One-to-Many relationship with the second entity.
9. Physical Model
The Physical Model is created by taking the logical model and creating a database and database
objects to represent the entities and relationships.
In the Physical model, each Entity becomes a TABLE and attributes of the entity become COLUMNS
of the table. The relationship between the entities is part of one or more CONSTRAINTS between
the tables.
The Unique Identifiers (UID) of an entity become the PRIMARY KEY of the table. Stored procedures,
functions, and Triggers may be created to enforce business rules.
DINESH Page 12 of 18
Defining FOREIGN KEY ensures the referential integrity of the data. It defines the relationship
between the tables.
Oracle implements the RDBMS characteristics using the following set of structures:
Tables are used for data storage.
Views and Synonyms are created for data access.
Indexes are used to speed up data retrieval.
Primary Keys, Foreign Keys, and Unique Keys are called Constraints and are created to
enforce data integrity.
Triggers are created to satisfy the business rules.
Roles and Privileges are used for Security.
Procedures, Function, and Packages are used to code the Application.
The physical structure of an Oracle Database server consists of two major components: The
Database and the Instance.
The Database is a set of physical files saved on the disk that store information.
The Instance is a set of memory structures and processes that uses the physical components to
manipulate and retrieve data.
Host Machine * The host machine is where the Oracle Instance is running
Instance
User
SGA
PGA
Background
Processes
Storage Disk
Database
Files
Files
Files
DINESH Page 13 of 18
❖ SYSTEM is a powerful administrative user in the database. Initially, you use this user
connection to create database users and other administrations in the database.
❖ In a container database, the users are either common or local. Common users are visible on
the container as well as in all pluggable databases. They have the same Username and
Password across all pluggable database and in the container database. The schema for
common user is still local to each pluggable database and the container database.
❖ A Schema is a collection of database objects owned by a user account in the database. A
Schema and a User have a One-to-One relationship in the database. A schema is created as
a user in the database, but when the user owns database objects, it is called a Schema.
❖ When an object is created under someone’s schema, the user has full privilege on the object
by default.
❖ Using Oracle’s Roles and Privileges, a schema owner or administrator can grant privilege on
his or her object (such as a table) to another user in the same database. This is known as
Object-level privilege.
❖ For certain user, you may want to grant privileges on all the objects in the database. This is
accomplished by using the System Privileges.
Connecting to SQL*Plus
SQL*Plus is Oracle’s Command-Line interface to the Oracle database.
Once you are in SQL*Plus, you can connect to another database or change your connection
by using the CONNECT command, with the below Syntax:
CONNECT <username>/<password>@<connect-string>
The slash separates the username and password. The connect string following @ is the
database alias name known as the net service name.
You may replace the connect string with a construct called the easy connect.
Syntax: [//]Host[:Port]/<service-name>
For example: To connect to database service named C12DB1 on Machine DINESH_PC, where
the listener is running in port 1521, use:
SQLPLUS system@”DINESH_PC:1521/C12DB1”
Once you are connected to SQL*Plus, you will get the SQL> prompt. This is default prompt,
which can be changed using the SET SQLPROMPT command. To Exit from SQL*Plus, use the
EXIT or QUIT command.
DINESH Page 14 of 18
11. Operators
Operator Description
+ Addition operator
:= Assignment operator
=> Association operator
% Attribute indicator
' Character string delimiter
. Component indicator
|| Concatenation operator
/ Division operator
** Exponentiation operator
( Expression or list delimiter (begin)
) Expression or list delimiter (end)
: Host variable indicator
, Item separator
<< Label delimiter (begin)
>> Label delimiter (end)
/* Multiline comment delimiter (begin)
*/ Multiline comment delimiter (end)
* Multiplication operator
" Quoted identifier delimiter
.. Range operator
= Relational operator (equal)
<> Relational operator (not equal)
!= Relational operator (not equal)
~= Relational operator (not equal)
^= Relational operator (not equal)
< Relational operator (less than)
> Relational operator (greater than)
<= Relational operator (less than or equal)
>= Relational operator (greater than or equal)
@ Remote access indicator
-- Single-line comment indicator
; Statement terminator
- Subtraction or negation operator
12. Identifiers
Identifiers name PL/SQL elements, which include:
• Constants
• Cursors
• Exceptions
• Keywords
• Labels
• Packages
• Reserved words
DINESH Page 15 of 18
• Subprograms
• Types
• Variables
DINESH Page 16 of 18
OBJECT, OCICOLL, OCIDATE, OCIDATETIME, OCIDURATION, OCIINTERVAL, OCILOBLOCATOR, OCINUMBER, OCIRAW, OCIREF, OCIREFCURSOR,
OCIROWID, OCISTRING, OCITYPE, OLD, ONLY, OPAQUE, OPEN, OPERATOR, ORACLE, ORADATA, ORGANIZATION, ORLANY, ORLVARY, OTHERS,
O OUT, OVERRIDING
PACKAGE, PARALLEL_ENABLE, PARAMETER, PARAMETERS, PARENT, PARTITION, PASCAL, PIPE, PIPELINED, PLUGGABLE, PRAGMA, PRECISION,
P PRIOR, PRIVATE
RAISE, RANGE, RAW, READ, RECORD, REF, REFERENCE, RELIES_ON, REM, REMAINDER, RENAME, RESULT, RESULT_CACHE, RETURN,
R RETURNING, REVERSE, ROLLBACK, ROW
SAMPLE, SAVE, SAVEPOINT, SB1, SB2, SB4, SECOND, SEGMENT, SELF, SEPARATE, SEQUENCE, SERIALIZABLE, SET, SHORT, SIZE_T, SOME,
SPARSE, SQLCODE, SQLDATA, SQLNAME, SQLSTATE, STANDARD, STATIC, STDDEV, STORED, STRING, STRUCT, STYLE, SUBMULTISET,
S SUBPARTITION, SUBSTITUTABLE, SUM, SYNONYM
TDO, THE, TIME, TIMESTAMP, TIMEZONE_ABBR, TIMEZONE_HOUR, TIMEZONE_MINUTE, TIMEZONE_REGION, TRAILING, TRANSACTION,
T TRANSACTIONAL, TRUSTED
U UB1, UB2, UB4, UNDER, UNPLUG, UNSIGNED, UNTRUSTED, USE, USING
V VALIST, VALUE, VARIABLE, VARIANCE, VARRAY, VARYING, VOID
W WHILE, WORK, WRAPPED, WRITE
Y YEAR
Z ZONE
Predefined Identifiers
Predefined identifiers are declared in the predefined package STANDARD.
An example of a predefined identifier is the exception INVALID_NUMBER.
For a list of predefined identifiers, connect to Oracle Database as a user who has the
DBA role and use this query:
SELECT TYPE_NAME FROM ALL_TYPES WHERE PREDEFINED='YES';
BFILE CLOB NAMED COLLECTION PL/SQL LONG RAW TIMESTAMP WITH LOCAL TZ
BINARY ROWID DATE NAMED OBJECT PL/SQL LONG RAW REF TIMESTAMP WITH TZ
BINARY_DOUBLE FLOAT NUMBER PL/SQL PLS INTEGER TABLE UROWID
PL/SQL BINARY
BINARY_FLOAT INTEGER INTEGER PL/SQL RECORD TIME VARCHAR
INTERVAL DAY TO TIME WITH
BLOB SECOND PL/SQL BOOLEAN PL/SQL REF CURSOR TZ VARCHAR2
INTERVAL YEAR TO
CHAR MONTH PL/SQL COLLECTION PL/SQL ROWID TIMESTAMP VARYING ARRAY
User-Defined Identifiers
A user-defined identifier is:
• Composed of characters from the database character set
• Either ordinary or quoted
DINESH Page 17 of 18
– Number sign (#)
– Underscore (_)
• Is not a reserved word.
The database character set defines which characters are classified as letters and digits.
The representation of the identifier in the database character set cannot exceed 30
bytes.
Examples of acceptable ordinary user-defined identifiers:
X
t2
phone#
credit_limit
LastName
oracle$number
money$$$tree
SN##
try_again_
Examples of unacceptable ordinary user-defined identifiers:
mine&yours
debit-amount
on/off
user id
The representation of the quoted identifier in the database character set cannot exceed
30 bytes (excluding the double quotation marks).
A quoted user-defined identifier is case-sensitive, with one exception: If a quoted user defined
identifier, without its enclosing double quotation marks, is a valid ordinary
user-defined identifier, then the double quotation marks are optional in references to
the identifier, and if you omit them, then the identifier is case-insensitive.
DINESH Page 18 of 18