notes(5)
notes(5)
Chapter Overview:
• Purpose: Provides prerequisite knowledge for students, though not directly tested in
exams.
• Tools Covered: SQL*Plus and SQL Developer.
• Data Sets: HR and OE schemas provided by Oracle for exercises and examples.
• Topics: Primitive data types, heap-organized table structure, object types (indexes,
constraints, views), sequences, and synonyms.
• SQL*Plus:
o Purpose: Connects to the database, issues SQL commands, creates PL/SQL code,
and formats results.
o Architecture: User process in C, uses Oracle Net protocol. Can connect across
different platforms (e.g., Windows to Unix).
o Availability: On all platforms where the database is ported.
o Usage: Detailed instructions provided for Linux and Windows.
• SQL Developer:
o Functionality: Offers more features compared to SQL*Plus.
o Requirements: Needs a graphical terminal, which SQL*Plus does not.
SQL*Plus on Linux:
SQL*Plus on Windows:
• Versions:
o Character Version: sqlplus.exe.
o Graphical Version: sqlplusw.exe (no longer exists in current releases but still
usable).
• Executable File Location: Typically
D:\app\oracle\product\12.1.0\dbhome_1\BIN\sqlplus.exe.
• Logon:
o Example logon string: system/admin123@coda.
o Shortcut Modification: Use sqlplus /nolog to prevent immediate logon
prompt.
• Launching SQL*Plus: Can be run from the Start menu shortcut or command prompt.
Key Points:
• Purpose:
o Connects to Oracle and some non-Oracle databases.
o Issues ad hoc SQL commands and manages PL/SQL objects.
o Provides a graphical interface with wizards for common tasks.
• Platform and Requirements:
o Written in Java: Requires Java Runtime Environment (JRE).
o Platform Availability: Runs on all platforms supporting the required JRE
version.
o No Significant Platform Differences: Functionality is consistent across
platforms.
• Installation:
o Not Installed with Oracle Universal Installer: It is a standalone product.
o Download: Obtain the latest version from Oracle’s website.
o Installation Process:
§ Unzip the downloaded ZIP file.
§ JDK Requirement:
§ Windows versions may include JDK.
§ Non-Windows platforms require preinstalled JDK.
§ Check JDK Installation: Use java –version command.
§ Example output: java version "1.7.0_71"
§ If the version is incorrect, check the path with which java.
• Launching SQL Developer:
o Windows: Execute sqldeveloper.exe.
o Linux: Execute sqldeveloper.sh.
§ Ensure DISPLAY environment variable is set (e.g., 127.0.0.1:0.0 for
system console).
• User Interface:
o Layout:
§ Left Pane: Navigation for objects and connections.
§ Example: Connection labeled orcl_sys (identifier orcl, user
sys).
§ Right Pane:
§ Upper part for entering SQL statements.
§ Lower part for displaying results.
o Customization: Highly customizable; experiment with settings to find the best
configuration for your needs.
• Troubleshooting:
o Issues with JRE and launching SQL Developer should be referred to a system
administrator.
• Connection Setup:
o Access the connection window by clicking the + symbol on the Connections tab.
o Connection Name: Arbitrary.
o Username and Password:
§ Both must be supplied.
§ Option to save password (for convenience, but poses a security risk).
• Connection Types:
o Oracle Tab:
§ Role Drop-down: Option to connect as sysdba (not needed for
exercises).
§ Connection Type Radio Buttons:
§ Basic: Requires machine name, port, and SID/service.
§ TNS: Uses alias from tnsnames.ora or LDAP directory for name
resolution.
§ LDAP: Queries database service definitions from an LDAP
directory.
§ Advanced: Uses full JDBC connection string, suitable for various
databases.
§ Local/Bequeath: Connects directly to a server process if the
database and client are on the same machine.
• Choosing Connection Types:
o Basic: User needs to know connection details.
o TNS: Requires configuration by the database administrator.
• Object Ownership:
o Objects are owned by database users (e.g., HR).
o Owned objects form a schema.
• Query for Object Types:
o Query: SELECT object_type, COUNT(object_type) FROM dba_objects
GROUP BY object_type ORDER BY object_type;
o Example output shows various object types and their counts in a small teaching
database.
• Views for Object Information:
o DBA_OBJECTS: Contains all objects in the database.
o USER_OBJECTS: Shows objects owned by the user.
o ALL_OBJECTS: Shows objects the user has access to.
o CDB_ Views (12c): For multitenant databases (container and pluggable
databases).
• Common Object Types for SQL Programmers:
o Tables: Store data in rows and columns.
o Views: Named queries that act like tables.
o Synonyms: Aliases for tables/views.
o Indexes: Improve data retrieval speed.
o Sequences: Generate numbers in order on demand.
• Less Common Object Types:
o More relevant to PL/SQL programmers and database administrators.
• Naming Rules:
o Length: 1 to 30 characters (128 for database links).
o Characters Allowed: Letters, numbers, underscore (_), dollar sign ($), hash
symbol (#).
o Case Sensitivity:
§ Names begin with a letter.
§ Lowercase letters converted to uppercase unless enclosed in double
quotes.
• Double Quotes:
o Enclosing names in double quotes allows breaking standard naming rules.
o Must always use double quotes to reference the object later.
• Case Sensitivity Example:
o Two tables named lower and "lower" are different:
o SQL tools like SQL*Plus and SQL Developer convert lowercase to uppercase
unless quoted.
• Best Practices:
o Avoid using lowercase names and nonstandard characters to prevent confusion.
Object Namespaces
• Namespace Concept:
o Defines a group of object types within which names must be unique by schema
and name.
o Objects in different namespaces can have the same name.
• Shared Namespace Object Types:
o Tables
o Views
o Sequences
o Private synonyms
o Stand-alone procedures
o Stand-alone stored functions
o Packages
o Materialized views
o User-defined types and operators
o Note: You cannot have a table and a view with the same name in the same
schema. They share the same namespace, allowing abstraction and security.
• Separate Namespace Object Types:
o Constraints
o Clusters
o Database triggers
o Private database links
o Dimensions
o Note: Indexes can have the same name as tables within the same schema, as these
object types have different namespaces.
Creating Tables
o Minimum Requirements: Table name and at least one column with a data type.
ORGANIZATION HEAP is the default and rarely specified.
o DEFAULT Keyword: Allows specifying default values for columns if not
provided in an INSERT statement.
o Example:
o Details:
§ EMP: Created in SCOTT schema.
§ EMP_NO: Up to 4 digits, rounded to integer.
§ ENAME: Up to 10 characters.
§ HIREDATE: Defaults to current date (midnight) if not provided.
§ SAL: Numeric values up to 7 digits, with 2 decimal places; rounded.
§ COMM: Defaults to 0.03 if not provided.
• Inserting and Selecting Data:
o Example Insertion:
o Example Selection:
o Example 1:
o Example 2:
o Note: Primary, unique, and foreign key constraints are not copied.
• Creating an Empty Table:
o Example:
• Commands:
o Adding Columns:
o Modifying Columns:
ALTER TABLE emp
MODIFY (comm NUMBER(4,2) DEFAULT 0.05);
o Dropping Columns:
o Renaming Columns:
• Notes:
o DDL Commands: All changes are committed automatically and cannot be
reversed if an active transaction is present.
o SET UNUSED: Makes columns invisible to SQL, better alternative to dropping
columns. Use DROP UNUSED COLUMNS to remove all unused columns.
• Restrictions:
o Cannot drop a table if it is referenced by a foreign key constraint or if there is an
active transaction with rows in the table.
o Recycle Bin (Oracle 12c): Dropped tables can be restored unless dropped with
the PURGE option or recycle bin is disabled.
Creating and Using Temporary Tables
• Definition:
o A temporary table is visible to all sessions in terms of its structure, but the rows
inserted are private to the session that inserted them.
• Syntax:
sql
Copy code
CREATE GLOBAL TEMPORARY TABLE temp_tab_name
(column datatype [, column datatype] )
[ON COMMIT {DELETE | PRESERVE} ROWS];
o column datatype: Specifies columns and their data types, similar to a regular
table.
o ON COMMIT {DELETE | PRESERVE} ROWS: Determines the row lifetime.
§ DELETE: Rows are removed when the transaction completes (default
behavior).
§ PRESERVE: Rows are retained until the session ends.
• Characteristics:
o Data Privacy: Each session’s rows are private and isolated from others.
o DML and SELECT Commands: Supported for temporary tables, just like
permanent tables.
o Indexes, Constraints, and Triggers: Can be defined on temporary tables.
o References: Can be used in views, synonyms, and joined with other tables.
• Performance Benefits:
o Temporary Segments: Written to a temporary segment in the user’s temporary
tablespace, which is faster than using permanent tablespaces. I/O operations are
performed directly on disk without involving the database buffer cache.
o No Redo Generation: DML operations do not generate redo because the data is
transient and persists only for the session or transaction duration. This reduces the
strain on redo generation and speeds up operations.
• Creation Tools:
o Temporary tables can be created using SQL*Plus or the Database Control Table
Creation Wizard.
Indexes Overview
• Functions of Indexes:
o Enforce primary key and unique constraints.
o Improve performance by speeding up data retrieval.
• Roles in Index Management:
o Business Analysts: Specify business rules that translate into constraints and thus
indexes.
o Database Administrators (DBAs): Monitor database performance and
recommend indexes.
o Developers: Design indexing strategies based on code and data nature.
Necessity of Indexes
Types of Indexes
• B*Tree Indexes:
o Structure: Balanced tree with nodes pointing to other nodes, containing row
pointers.
o Efficiency: Effective for low retrieval proportions. Rebuild if tree depth exceeds
three or four levels.
o Rowid: Provides the physical location of the row.
o Use Case: Efficient for large tables with high cardinality columns.
• Bitmap Indexes:
o Structure: Stores rowids as bitmaps for each key value.
o Use Case: Effective for columns with low cardinality in data warehouses.
Handles Boolean algebra operations well.
o Advantages: Includes NULLs as distinct values and supports complex queries
with multiple conditions.
Index Type Options
• Unique or Nonunique:
o Unique: Prevents duplicate values.
o Nonunique: Default; allows duplicates.
• Reverse Key Index:
o Function: Reverses key bytes to avoid contention in multiuser systems.
• Compressed Index:
o Function: Stores repeated key values only once, reducing storage for duplicate
values.
• Composite Index:
o Function: Indexes multiple columns concatenated. The index is efficient if
queries use the leftmost columns.
• Function-Based Index:
o Function: Built on the result of functions applied to columns (e.g., UPPER(),
TO_CHAR()). Query must use the same function for index utilization.
• Ascending or Descending:
o Default: Ascending order.
o Descending: Reverses order; affects retrieval order in index full scans.
Tips
• Index Creation:
o Use B*Tree indexes for high cardinality columns.
o Use bitmap indexes for low cardinality columns in data warehouses.
o Keep index count low in transaction-heavy systems to avoid overhead.
o Consider index types based on query patterns and performance needs.
o Indexes:
o Constraints:
o Index Types:
§ Unique Indexes: Prevent duplicate values.
§ Composite Indexes: Include multiple columns.
§ Bitmap Indexes: Used for columns with low cardinality relative to table
rows.
• Index Usage:
o Oracle automatically evaluates and decides on index usage when executing SQL
statements.
o Optimizer Hints: Programmers can use hints to force or avoid specific indexes.
Constraints
• Purpose:
o Enforce business rules and ensure data conforms to the entity-relationship model.
o Example: Ensuring unique identification of customers and orders, preventing
orders before customer creation, validating order dates and amounts.
• Rollback on Constraint Violation:
o Any Data Manipulation Language (DML) statement that violates a constraint will
cause an automatic rollback of the entire statement.
o Exam Tip: Only the statement with the violation is rolled back, not the entire
transaction.
Types of Constraints
• Supported Constraints:
o UNIQUE
o NOT NULL
o PRIMARY KEY
o FOREIGN KEY
o CHECK
o REF (used in object-relational interactions, not covered here)
• Naming Constraints:
o Constraints should be named according to a standard convention, but if unnamed,
Oracle generates names.
Unique Constraints
• Definition:
o Ensures all values in a column or combination of columns are unique.
o Can be a single column (key column) or multiple columns (composite key unique
constraint).
o Columns in a composite key do not need to be adjacent or of the same data type.
• Handling NULL Values:
o NULL values can be inserted into unique constraint columns; multiple NULLs are
allowed because NULL is not equal to any other value.
• Indexing:
o Unique constraints are enforced by indexes (B*Tree indexes).
o NULL values are not included in these indexes, which allows multiple NULLs
but can lead to table scans for WHERE key_column IS NULL.
Not-Null Constraints
• Definition:
o Requires that a column must have a value (mandatory columns).
o Must be defined per column; a group of columns cannot share a single not-null
constraint.
o Defaults can be used to bypass the requirement for specifying values.
• Definition:
o Uniquely identifies each row in a table.
o Combines the uniqueness and not-null requirements.
o Only one primary key per table, but multiple unique and not-null constraints are
allowed.
• Indexing:
o A primary key constraint automatically creates an index if one does not already
exist.
• Exam Tip: Primary and unique key constraints require an index, which is created
automatically if needed.
• Definition:
o Defined on a child table and refers to the primary key or unique constraint
columns in a parent table.
o Columns do not need to have the same names but must be of the same data type.
• Handling NULL Values:
o Foreign key columns can have NULL values, potentially creating orphan rows.
• Constraint Actions:
o ON DELETE CASCADE: Automatically deletes matching rows in the child
table if a row in the parent table is deleted.
o ON DELETE SET NULL: Sets foreign key columns to NULL in the child table
if a row in the parent table is deleted.
o Restrictions: The parent table cannot be dropped or truncated if there are foreign
key relationships, even if the child table is empty.
• Self-Referencing Foreign Key:
o A table can have a foreign key that references itself. Example: An employee table
where an employee's manager is also an employee in the same table.
Check Constraints
• Definition:
o Enforces rules on column values, such as value ranges or conditions.
o Rules must evaluate to TRUE or FALSE and can use literals or other columns but
cannot use subqueries or functions like SYSDATE.
• TIP: The not-null constraint is implemented as a preconfigured check constraint.
Defining Constraints
• Defining Constraints:
o Constraints can be defined when creating a table or added later.
o Inline Definition: Constraints are defined within the column definition. Suitable
for simple constraints but limited in flexibility.
o Table-Level Definition: Constraints are defined at the end of the table definition.
Allows more complex constraints, such as foreign keys spanning multiple
columns or check constraints involving multiple columns.
• Index Creation:
o Unique and primary key constraints require an index.
o If defined at table creation, the index is created along with the table.
• Examples of Constraint Definitions:
o DEPT Table:
1. DEPTNO: Primary key (dept_deptno_pk), numeric, between 10 and 90
(dept_deptno_ck).
2. DNAME: Not null (dept_dname_nn).
o EMP Table:
1. EMPNO: Primary key (emp_empno_pk).
2. ENAME: Not null (emp_ename_nn).
3. MGR: Self-referencing foreign key (emp_mgr_fk).
4. DEPTNO: Foreign key referencing DEPTNO in the DEPT table with ON
DELETE SET NULL (emp_deptno_fk).
5. EMAIL: Unique (emp_email_uk), checked for validity (emp_email_ck).
6. HIREDATE: Checked to be at least 16 years after DOB
(emp_hiredate_ck).
• Additional Constraints Considerations:
o Index Control: Managing index creation for unique and primary key constraints.
o Constraint Timing: Constraints can be checked at insert time or when the
transaction is committed.
o Enforcement: Constraints can be enabled or disabled.
Constraint States
• ENABLE VALIDATE:
o Ensures all existing data and new data conform to the constraint.
• DISABLE NOVALIDATE:
o Allows both conforming and non-conforming data; no validation of existing data.
• ENABLE NOVALIDATE:
o Existing non-conforming data may exist, but new data must conform.
• DISABLE VALIDATE:
o Existing data conforms to the constraint, but new data does not need to; the index
is dropped.
• Practical Example:
sql
Copy code
alter table sales_archive modify constraint sa_nn1 disable novalidate;
insert into sales_archive
select * from sales_current;
alter table sales_archive modify constraint sa_nn1 enable novalidate;
update sales_archive set channel='NOT KNOWN' where channel is null;
alter table sales_archive modify constraint sa_nn1 enable validate;
o Process:
§ Disable constraint temporarily to allow data upload.
§ Re-enable constraint with NOVALIDATE to accommodate existing data.
§ Update the table to fix data issues.
§ Enable constraint with VALIDATE to ensure all data conforms.
Constraint Checking
sql
Copy code
alter table sales_archive add constraint sa_nn1
check (channel is not null) deferrable initially immediate;
§ Explanation:
§ DEFERRABLE: Allows the constraint check to be deferred.
§ INITIALLY IMMEDIATE: Default behavior is to check the
constraint immediately.
• Using Deferrable Constraints:
o Example Usage:
sql
Copy code
set constraint sa_nn1 deferred;
insert into sales_archive
select * from sales_current;
update sales_archive set channel='NOT KNOWN' where channel is
null;
commit;
set constraint sa_nn1 immediate;
§ Process:
§ DEFERRED: Constraint checking is postponed until the
transaction is committed.
§ IMMEDIATE: Constraint checking is resumed after the commit.
• Constraint Status Changes:
o ENABLED/DISABLED and VALIDATE/NOVALIDATE: These status
changes affect all sessions and are a data dictionary update.
o IMMEDIATE/DEFERRED: Changes are session-specific. The default state
applies to all sessions unless explicitly changed.
• Default Behavior:
o Constraints are enabled, validated, and not deferrable by default.
Exam Tip
• By default, constraints are enabled and validated, and they are not deferrable.
Views
• Definition:
o A view appears as a table to users, providing a two-dimensional structure of rows
and columns.
o Technically, a view is a named SELECT statement that executes when users
interact with it.
o Views can include any valid SELECT commands: joins, aggregations, sorts, etc.
• Namespace:
o Views share the same namespace as tables. A view name can be used wherever a
table name can be used.
• Reasons for Using Views:
o Security: Restrict access to specific rows or columns.
o Simplify SQL: Hide complex queries or aggregations.
o Prevent Errors: Provide a clear, unambiguous representation of data.
o Data Comprehensibility: Present normalized data in an understandable format.
o Performance: Optimize queries and simplify tuning.
• Enforcing Security with Views:
o Create views to show only relevant columns or rows, e.g.:
sql
Copy code
create view hr.emp_fin as
select hire_date, job_id, salary, commission_pct, department_id
from hr.employees;
o Users can query the view without seeing sensitive information, e.g.:
sql
Copy code
select * from emp_fin where department_id=50;
sql
Copy code
create view dept_sal as
select d.department_name, sum(e.salary) dept_sal
from departments d
left outer join employees e on d.department_id=e.department_id
group by d.department_name
order by d.department_name;
o Users query the simplified view without dealing with joins or aggregations.
• Preventing Errors with Views:
o Provide views to prevent misinterpretation of data, e.g.:
sql
Copy code
create view current_staff as select * from emp where active='Y';
sql
Copy code
create view dept_emp as
select /*+USE_HASH (employees departments)*/ department_name,
last_name
from departments
natural join employees;
o This view forces the use of a hash join for better performance.
• Simple vs. Complex Views:
o Simple Views:
§ Draw data from a single detail table.
§ No functions or aggregations.
§ Usually allow INSERT, UPDATE, DELETE operations.
o Complex Views:
§ May join multiple tables, use functions, or perform aggregations.
§ Generally do not support direct DML operations due to complexity.
• Examples:
o Simple View: May not allow INSERT if it lacks a mandatory column, even if it's
technically simple.
o Complex View: Often cannot handle INSERT due to functions or other complex
elements, but may allow DELETE.
Key Points:
• Schema Object: Views are schema objects and can reference tables owned by different
users.
• Default Location: Views are created in the current schema by default.
• Optional Keywords:
o OR REPLACE: Drops the view if it already exists before creating a new one.
o FORCE: Creates the view even if detail tables do not exist.
o NOFORCE: Default behavior; causes an error if detail tables do not exist.
o WITH CHECK OPTION: Prevents insertion of rows or updates that affect
visibility in the view.
o WITH READ ONLY: Prevents DML operations through the view.
o CONSTRAINT constraintname: Names the constraints for error messages.
• Aliases: Optional. If not provided, columns will use table names or aliases from the
subquery.
ALTER VIEW:
• Purpose: Compiles the view. A view must compile successfully to be usable.
• Compilation Check: Oracle checks for the existence of detail tables and columns during
view creation.
o FORCE Option: Allows creation of the view even if tables or columns are
missing, but the view remains unusable until those objects are created and
recompiled.
• Automatic Compilation: Oracle will attempt to recompile an invalid view when queried.
If successful, users may experience slower query performance.
• Manual Compilation: Recommended to ensure views compile successfully.
• OR REPLACE: When used with CREATE VIEW, automatically drops an existing view
before creating a new one.
Synonyms
Definition:
Benefits:
Example:
Instead of:
Types of Synonyms:
• Private Synonyms:
o Scope: Must be in the user's schema or qualified with the schema name.
o Uniqueness: Must have unique names within their schema.
• Public Synonyms:
o Scope: Independent of any schema; accessible by any user with permission.
o Naming: Can have the same name as schema objects.
Name Resolution:
• Oracle searches for the object in the local schema first. If not found, it then searches for a
public synonym.
Syntax:
• Create Synonym:
• Drop Synonym:
• Compile Synonym:
Permissions:
• If the referred object is dropped, the synonym remains but will return an error if accessed.
• The synonym must be recompiled if the object is recreated.
EXAM TIP:
• Public Synonym: The term "public" indicates that it is not tied to a specific schema and
cannot be prefixed with a schema name, but it does not imply that everyone has
permissions to use it.
Sequences
Definition:
• A sequence generates unique integer values, ensuring each value is unique and
incremented.
Use Cases:
• Primary Keys: Commonly used to generate primary key values for tables (e.g., customer
numbers, order numbers).
• Simplification: Helps in systems where complex identifiers (e.g., telephone numbers,
timestamps) are impractical for primary keys.
Characteristics:
• Serialization: Only one session can read and increment the sequence at a time, ensuring
unique values.
• Independence: Operates independently of tables, row locking, and transaction
processing, allowing for high performance in generating values.
Creating Sequences:
• Syntax:
• Options:
o INCREMENT BY: Defines the value increment (default is +1).
o START WITH: Sets the initial value (default is 1).
o MAXVALUE: Sets the maximum value for ascending sequences (default is no
maximum).
o MINVALUE: Sets the minimum value for descending sequences (default is no
minimum).
o CYCLE: Allows the sequence to restart from the beginning after reaching
MAXVALUE or MINVALUE (default is no cycle).
o CACHE: Determines the number of values pre-generated and cached for
performance (default is 20). Larger values can improve performance.
o ORDER: Ensures that values are issued in order in a clustered database (useful in
multi-instance setups).
Using Sequences:
COMMIT;
Commit Behavior:
• Persistence: Sequence values are permanent and visible immediately upon being issued;
they cannot be rolled back.
• Gaps: Sequences may have gaps due to system restarts or cached values being lost during
a database failure.
Handling Gaps:
• If no gaps are acceptable, alternative methods (e.g., using a table to store current values)
can be employed, but they are less efficient and can cause contention.
Modifying Sequences:
• Syntax:
• Note: You cannot change the starting value with ALTER SEQUENCE. To reset the
sequence, drop and recreate it: