Oracle Database Modes and Objects Guide
Oracle Database Modes and Objects Guide
DB Logical view
DB objects
Database mode:
open (or) Read/write mode: users can use the DB ex: raw materials
Inactive mode: none can use the DB, this is where pre-requisites are defined.
Database—Tablespace—Segment—Block
Database object list: tables, views, Functions, Indexes, materialized views, Triggers, Stored Procedure,
Packages.
Vies- is a query like a virtual table where u store ur query and it has two or more table and multiple
column. Table stored in the database is view
Stored procedures: small procedural unit which give result after. Have procedural way to perform
action
VARCHAR 2: memory allocation 3 spaces. Accepts alphabet, number and symbol. Maximum length is
5.
Primary key : only one column can be declared as primary key in a table. No duplicates are allowed.
No null values are allowed. Auto-Indexed ( marking it as important)
Unique key : more than one column can be declared as unique key in a table. No duplicate value
allowed. Null values are allowed. Auto indexed.
Foreign key – reference key: more than one column can be declared as foreign key is a table.
Duplicates allowed as they are referenced values. Null values are allowed as they are referenced
value.
When a primary column referenced in another table then in that another table it becomes a foreign
key.
Nut null : not supposed to be left blank. More than one column can be declared as not null column
in a table. Duplicate values are allowed. No null values are allowed.
CHECK : any column can be checked for its value. Eg salary>20000- this allow only the values greater
than 20000 in the declared column.
CREATE STATEMENTS ::
Type 1 :: CREATE TABLE ALL-TEST ( TEST_CODE VARCHAR( 10) , TEST_TYPE CHAR( 10), TEST_SUBJ-
MARK INT);
Type 2 : CREATE TABLE ALL _TEST2 ( TEST_CODE VARDCHAR(10) PRIMARY KEY, TEST_DOMAIN
VARCHAR (20) NOT NULL , TEST_TYPE CHAR(10) NOT NULL, TEST_SUBJ_CODE CHAR (4) UNIQUE,
{ TEST_CODE VARCHAR (10) REFERENCES ALL_TEST2 ( TEST_CODE), --- to check foreign column
TEST_STATE CHAR ( 2) ,
TYPE 4 ::
CREATE TABLE ALL_TEST4 AS SELECT * FROM ALL_TEST1; -- to create a table by selecting a particular
table to require column of the table.
Data Definition language.: to define the database objects in a Database. :: CREATE , ALTER, DROP ,
TRUNCATE, RENAME.
Add ::
ALTER TABLE ALL_TEST 1 ADD CONSTRAINT TC_PK_ADDED PRIMARY KEY (TEST_CODE);---- TO ADD
PRIMARY KEY
ALTER TABLE TEST_TBL1 ADD CONSTRAINT TNM_NN_ADDED CHECK( TEST_NAME IS NOT NULL);--
ADD NOT NULL CONSTRAINT
ALTER TABLE TEST_TBL1 ADD CONSTRAINT TC_REF_ADDED FOREIGN KEY (TEST_CODE) REFERENCES
ALL_TEST1(TEST_CODE):---ADD FOREIGN KEY CONSTRAINT.
RENAME
--MODIFY
ALTER TABLE ALL_TEST1 MODIFY TEST_DOMAIN VARCHAR2(15); ---MODIFY THE LEGTH OF THE
COLUMN ( when there is a data in the column cannot reduce the size of the column but we can
increase the length of the column by modify )
ALTER TABLE ALL_TEST1 MODIFY TEST_DOMAIN NOT NULL; --- Modify to not null constraint.
--Drop
ALTER TABLE TEST_TBL1 DROP COLUMN TEST_STATE; -- TO drop a column.
ALTER TABLE ALL_TEST1 DROP CONSTRAINT TC_PK_ADDED CASCADE; (( TO Drop primary key
constraint) CASCADE word tried to eliminate the foreign key as well).
Disable
ALTER TABLE TEST_TBL3 DISABLE CONSTRAINT TID_PK; ---DISABLE primary key . so it cut the
reference .
Enable :
ALTER TABLE TEST_TBL3 ENABLE CONSTRAINT TID_P;--- TO enable primary key – so that it can again
has the reference.
TRUNCATE STATEMENT ::: ( to remove the data from the table but the structure would be there )
--
RENAME STATEMENT
--
INSERT
UPDATE
DELETE
--
INSERT STATEMENTS ::
UPDATE STATEMENTS ::
TYPE 1 :
DELETE STATEMENTS ::
COMMIT :: TO SAVE
ROLLBACK :: UNDO
SAVEPOINT
--
GRANT
REVOKE
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE ON HR, TEST_TBL1 TO MGR;--- here ‘MGR’ is
manager role
GRANT SELECT , INSERT , UPDATE , DELETE , CREATE ON HR.TST_TBL1 TO CHRIS; ---here ‘CHRIS’ Is
user with grant access.
GRANT SELECT, INSERT, UPDATE, DELETE , CREATE ON HR.TEST_TBL1 TO CHRIS WITH GRANT OPTION;
---- Here ‘CHRIS’ is user with GRANT ACCESS.
GRANT SELECT ON HR.TEST_TBL1 TO RAM; ---- Here chris gives select access to ram
== REVOKE
REVOKE CREATE, DELETE, INSERT, UPDATE, SELECT ON HR.TEST_TBL1 FROM CHRIS; ( RAM will also
loses access on the table as he is a successor of CHRIS
SELECT STATEMENTS ::
Type 2
Type 3
CONDITIONED RETRIEVAL
Type 4
CONDITIONED ON NULL VALUE ::
Type 5 :
Type 6
Type 7
SIMPLE SUB_QUERIES
SQL FUNCTION :: sql functions are built into oracle database and are available for use in various
appropriate SQL statements.
--
String/char functions ::
INSTR::
---
SUBSTR
SELECT SUBSTR (‘Believe in yourself’, -3, 3) FROM DUAL ; ( - 3 means it will start from the end)
--
LENGTH
Result : NULL
Result : 1
SELECT LENGTH( ‘Hope’) FROM DUAL; ( count the length of the string)
--
LOWER
--
UPPER
--
TRIM
SELECT TRIM ( LEADING ‘0’ FROM ‘000123’) FROM DUAL; ( result 123 .. leading means prior to the
that)
SELECT TRIM( TRAILING ‘1’ FROM ‘Learn1’ ) FROM DUAL; result = Learn
SELECT TRIM( BOTH ‘1’ FROM ‘123Learn111’) FROM DUAL; result= 23learn
NUMERIC/MATH FUNCTIONS
--
COUNT
SELECT COUNT (COUNTRY_ID) FROM CONUNTRIES; result--- 25.
--
MAX
--
ROWNUM
SELECT ROWNUM, EMPLOYEES. *FROM EMPLOYEES WHERE EMPLOYEE_ID > 115; result :: list of
records having employee_id greater than 115.
--
SUM
SELECT SUM( SALARY ) AS “Total Salary” FROM EMPLOYEES WHERE SALARY > 10000;
--
SUM WITH DISTINCT – (using the distinct – if there are 4 salaries wd same amount it will consider
only one while adding)
SELECT SUM (DEISTINCT salary) AS “Total salary” FROM employee WHERE SALARY> 10000;
--
SELECT TRUNC(125.815, -1) FROM DUAL; result = 120 – so here -1 represents unit place which is 5 so
5 would be subtracted from 125.
SELECT TRUNC(125.851, -2) FROM DUAL; result = 100 -- -2 represent tens value which is here 25
LAST_DAY – To display last date of the month or any given date value
--
Date Function
==SYSDATE
==SYSTIMESTAMP
==CURRENT DATE
==CURRENT_TIMESTAMP
==LAST_DAY
CONVERSTION FUNCTIONS
=== TO DATE
== TO CHAR
=== TO NUMBER
===
Join statements
---
FROM EMPLOYEES E
ON E. DEPARTMENT_ID=D. DEPARTMENT_ID;
----
LEFT OUTER JOIN- ALL RECORD FROM LEFT TABLE AND MATCHING FROM RIGHT TABLE
FROM EMPLOYEES E
ON E.DEPATMENT_ID=D.DEPARTMEN_ID;
----
RIGHT OUTER JOIN- ALL RECORDS FROM RIGHT TABLE AND MATCHING RECORDS FROM LEFT TABLE
FROM EPLOYEES E
ON E.DEPATRMENT_ID=D.DEPATRMENT_ID;
---
FULL OUTER JOIN- ALL RECORDS FROM BOTH LEFT AND RIGHT TABLE ( INCLUDING UNMATCHED
RECORDS)
FROM EMPLOYEE E
ON E. DEPARTMENT_ID=D.DEPARTMENT_ID;
Note :: computer -based information system can serve a variety of complex tasks in a coordinated
manner.
Such system handles large volumes of data, multiple users and several applications for activities
occurring in a central and / or distributed environment.
DBMS provides for storage, retrieval and updation of data in an organized manner.
Goals of DBMS :: to provide an environment which will efficiently provide access to data in a
database. .. Enforce information security – database security , concurrency control, cash recovery.
General Purpose:: - defining database-specifying the types of data to be stored in the database.
== why database ??
File management system had drawbacks which lead to database:: - data is separated for every
individual program.
Benefits of DBMS ::
- Redundancy is reduced
- Inconsistency is avoided
- Data is shared
- Standard is enforced
- Security is applied
- Integrity is maintained.
- Data independency is provided.
Database management system :: an agent that allows communication of the users with the physical
database and the operating system ( without the users knowing how it is done).
Metadata is data about the DATA stored in DB , i.e. structure of data stored in the DB.
- Data model :: the main tool which provides the data abstraction ( database approach ) by
hiding the details of data storage which is not needed by the users. i.e., set of concepts used
to describe the structure of the database.
- high – level/ conceptual- provides details on the way users perceive the data. Using Entity ,
Attribute and Relationship.
- Low-level /Physical – provides details on how data is stored. Indexing which makes the
search efficient based on the structure.
- Representational/ implementation- Between above 2 extremes, that provides details on both
which are understood by end user and not too many details are hidden.
Database architecture::
- External – the one at the user end which is concerned how the user views the data.
- Internal- the one at the physical DB end which is concerned on how the data is stored in DB.
- Conceptual – the one between the above mentioned which is concerned on how they are
connected.
3 level DB Architecture::
- External schema
- Conceptual schema
- Internal schema
Types of database models:: the most known record-based models are Hierarchical , Network and
Relational models.
Major Types:
- The data is perceived by the user as tables ( and nothing but tables)
- The operators at the user’s disposal – E.g. for data retrieval – are operators that generate
new tables from old, and those include at least SELECT, PROJECT and JOIN.
CODD RULES ::
- Information rule
- Guaranteed access rule
- Systematic treatment of null values
- Dynamic on-line catalog based on the relational model
- Dynamic on-line catalog based on the relational model
- View updating rule
- High level insert update and delete rule
- Physical data independence rule
- Logical data independence rule
- Integrity independency rule
- Distribution rule
- Non subversion rule
Features ::
- The ability to create multiple relations ( tables) and enter data into them.
- An interactive query language
- Retrieval of information stored in more than one table
- Provide a catalog or dictionary, which itself consists of tables( called system tables)
Important terms ::
- Relation- a table
- Tuple – a row in a table
- Attribute- a column in a table
- Degree- a number of attributes
- Cardinality – number of tuples
- Primary key- a unique identifier for the table
- Domain- a set of possible values that a given attribute can have
Keys ::
canditat
E-R modelling
Notation
Emp ID Deptid
== participation constraints :: how the relationship is establish and what kind of relationship they
have.
== Is A HIERARCHIES :: an entity having a relationship and branching out. The entity having its own
attribute and then branching out and not having a direct relation.
== Aggregation::
- Functional dependencies
- Inclusion dependencies
- General constraints.
NORMALIZATON:: decomposing a larger, complex table into several smaller , simpler ones.
Why normal forms ? – to understand that how complex our data base is.
Insert anomalies – says that the data needs to be reentered for every new subjective data.
Update anomalies- says that the data needs to be updated in multiple places which in turn increase
the cost of the performance of the application .
Delete anomalies- says that the data might get lost due to delete actions for the entire record
including the subjective data.
=== First normal form :: if all the values in a relation are of atomic in nature, then it can be
considered as it is 1st normal form.
Second normal form ::: any relation to be in 2NF :: it should be in INF. All the attribute should
have full dependency on primary key. No partial dependencies allowed, hence it must be
removed.
= third normal form:: any relation to be in 3 NF: it should be in 2NF. No transitive dependencies,
hence it must be removed.
All the attributes should be truly dependent only on the primary key not even partially on other
attributes.
==BOYCE-CODD NORMAL FORM ( BCNF) :: the intention of having BCNF, is if in case there are
composite or overlapping candidate keys. It is said BCNF , only if every determinant is a
candidate key.
==== DENORMALIZATION ::
SELECT FIRST_NAME FROM EMPLOYEE WHERE EMPLOYEE_ID in ( 106, 201, 100, 111);
SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE FIRST_NAME LIKE ‘_a%’ AND DEPARTMENT_ID
= 50;
- Numeric values are displayed with the lowest values first ( 1 to 999)
- Date values are displayed with the earliest value first ( 01-jan -92 before 01-jan-95)
- Character values are displayed in the alphabetical order
- Null values are displayed last for ascending sequences and first for descending sequences
- Can also sort by a column that is not in the SELECT list.
- The default sort order is ascending
- Can use column alias in the ORDER BY clause
- Sorting by using the column’s position
- Sorting by multiple columns
SELECT EMPLOYEE_ID, DEPARTMENT_ID, JOB_ID AS JOB FROM EMPLOYEES ORDER BY JOB DESC;
SUBSTITUTION VARIABLES ::
Use substitution variables to temporarily store values with single-ampersand ( &) and double-
ampersand (&&)
-WHERE clause
- ORDER BY clause
-COLUMN NAME
-TABLE NAME
-DEFINE STATEMENT
-VERIFY COMMAND
Syntax :
---
DEFINE DEPARTMENT_ID = 90
FROM EMPLOYEES
UNDEFINCE DEPARTMENT_ID
---
SET VERIFY ON
FROM EMPLOYEES
- Accept arguments ( user-supplies, variable, column and Expression) and return one value.
- Return one result per row
- Return value data type may be different
- Can be nested
- Can be used in SELECT, WHERE, and ORDER BY clauses.
Types of Functions::
- String/Char Functions
- Numeric/Math Functions
- Date/time functions
- Conversion function
- General functions.
General Functions ::
- NVL function :: converts a null value to an actual value. Data types must match
- NVL2 function :: if expr1 (source) is not null, it returns expr2(replace value)
- NULLIF Function:: compares two expressions and returns null if they are equal; returns the
first expression if they are not equal . Logically equivalent to CASE function.
NVL ::
FROM EMPLOYEES;
So here ( commission pct , 0 means if there is null value the null will replace wd 0 )
NVL2 ::
FROM EMPLOYEES
Here if commission pct null it will show sal and if it has a value it will be as sal + comm
NVLIF: :
FROM EMPLOYEES; result :: if the length of first and last names are equal then the result will null.
COALESCE FUNCTION :: returns the first non-null expression in the expression list.
FROM EMPLOYEES;
NESTING FUNCTIONS ::
Single- Row functions can be nested to any level. Nested functions are evaluated from the innermost
to the outermost level.
CONDITIOANL EXPRESSION ::
METHODS :: Provide the use of the IF-THEN -ELSE logic within a SQL statement
- CASE expression
- DECODE function
CASE EXPRESSION :: Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE Statement
CASE JOB_ID
ELSE SALARY
FROM EMPLOYEES;
DECODE FUNCTIONS:: Facilitates conditional inquiries by doing the work of a case expression or an
IF-THEN-ELSE statement
If the default value is omitted, a null value is returned where a search value does not match any of
the result values.
DECODE (TRUNC(SALARY/2000, 0) ,
0, 0.00,
1, 0.09,
2, 0.20,
3, 0.30,
4, 0.40,
0.45) TAX_RATE
FROM EMPLOYEES
GROUP FUNCTIONS :: Group functions operate on sets of rows to give one result per group
Types of group funcions:: avg, count, max, min, stddev, sum , variance.
- All group functions ignore NULL values , but NVL functions forces to include NULL values
- Divide the table into smaller groups
- Cannot use column alias in the GROUP clause
- Use WHERE conditions to exclude the rows before grouping , but cannot use for restriction
- Use HAVING clause to restrict the groups
- Use ORDER BY clause to display order
- GROUP BY clause is mandatory is Nesting-Group functions.
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
TYPES OF JOINS ::
Oracle joins ::
Equi joins
Non-Equi joins
Self join
Cross join
Natural join
--
Ambiguous Columns ::
Use table prefixes to qualify column names that are in multiple tables
Table Alias gives a table a shorter name : -keeps SQL code smaller, uses less memeory
Use column aliases to distinguish columns that have identical names, but reside in different tables.
--
NATURAL JOIN ::
The join can happen on only those columns having same data type and column names
FROM EMPLOYEES
-Joins with USING clause, used when column names are same but not the data types
-Also, simple join or Equi join or Inner join are all same.
- If the same column is used elsewhere in the SQL statement, do not alias it.
USING (DEPARTMENT_ID);
ON clause::
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID
SELF Join ::
ON E. MANAGER_ID = M.EMPLOYEE_ID;
FROM EMPLOYEES E
JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D. DEPARTMENT_ID
JOIN LOCATIONS L
ON D.LOCATION_ID = L.LOCATOION_ID.
FROM EMPLOYEES E
JOIN DEPARTMENTS D
USING ( DEPARTMENT_ID)
JOIN LOCATIONS L
USING (LOCATION_ID) ;
=== Joining two tables with more than one where conditions
ON E. DEPARTMENT_ID = D . DEPARTMENT_ID
WHERE E.DEPARTMENT_ID = 80
== NON-EQUI JOIN ::
- The relationship is obtained using an operator other than the equality ( = ) operator
- Table alias can be used for performance reasons, not because of possible ambiguity.
ON E.MANAGER_ID = M. EMLOYEE_ID;
== CROSS JOIN ::
SUB- QUERY :: A sub-query is a SELECT statement that is embedded in the clause of another SELECT
statement. Can place the sub-query in number of SQL clauses:
- WHERE
- HAVING
- FROM
Types of sub-queries ::
- Single row – queries that return only one row from the inner SELECT statement
- MULTIPLE ROW – queries that return more than one row from inner SELECT statement
NOTE :: The outer and inner query can be from different tables.
FROM EMPLOYEES
FROM EMPLOYEES
WHERE SALARY > (SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 40) ;
FROM EMPLOYEES
AND JOB_ID = (SELECT JOB_ID FROM JOBS WHERE JOB_TITLE = ‘Stock Manager’ ) ;
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
HAVING MIN ( SALARY) > (SELECT MIN ( SALARY ) FROM EMPLOYEES WHRE DEPARTMENT_ID =
50 ) ;
FROM EMPLOYEES
WHERE SALARY < ANY ( SELECT SALARY FROM EMPLOYEES WHERE JOB_ID = ‘IT_PROG’)
FROM EMPLOYEES
WHERE SALARY < ALL ( SELECT SALARY FROM EMPLOYEES WHERE JOB_ID = ‘IT_PROG’)
FROM DEPARTMENTS
SET OPERATORS ::
Set operators combine the results of 2 or more component queries into one result.
Key notes::
Union operator ::
SELECT DEPARTMENT_ID
FROM EMPLOYEES
UNION
SELECT DEPARTMENT_ID
SELECT DEPARTMENT_ID
FROM EMPLOYEES
UNION ALL
SELECT DEPARTMENT_ID
Intersect Operator::
FROM EMPLOYEES
INTERSECT
FROM JOB_HISTORY;
Minus operator ::
- Returns all the distinct rows selected by the first query, but not present in the second query
result set.
- Number of columns must be same
- Data type must be from same data type group
- Column names can be different
SELECT DEPARTMENT_ID
FROM EMPLOYEES
MINUS
FROM JOB_HISTORY;
- For UNION operator, must match the number of columns and data types.
- If column is not present in other table have to use the DUMMY table to match the SELECT
statement to perform UNION operator.
FROM DEPARTMENTS
FROM LOCATIONS;
- The order by clause can appear only once at the end of the compound query
- The component queries cannot have independent order by clauses
- The order by recognizes only the columns of the first SELECT query
- By default, the first column of the first SELECT query is used to sort the output in an
ascending order.
- Cannot use second query to sort the result.
FROM EMPLOYEES
UNION
SELECT DEPARTMENT_ID, 0
FROM DEPARTMENTS
- FOR UPDATE will lock all the rows involved in the where condition.
- We can use FOR UPDATE for multiple tables also ( join statement)
- If used in join statement , then we can exclusively mention to lock only the relevant rows
instead of locking all rows from both the tables.
- Hence, FOR UPDATE OF column_name
FROM EMPLOYEES
FOR UPDATE
USING ( DEPARTMENT_ID)
FOR UPDATE
ORDER BY E . EMPLOYEE_ID; ---all rows of both table locked for the where condition
ORDER BY E . EMPLOYEE_ID; --- all rows of employee table locked because E . SALARY is meant to be
locked exclusively not any rows from DEPARTMENT table
USING ( DEPARTMENT_ID)
ORDER BY E . EMPLOYEE_ID;
ORDER BY E . EMPLOYEE_ID;
ORDER BY E . EMPLOYEE_ID;
SCHEMA OBJECTSS
- To make complex queries easy – querying the view makes it easier for the user
- To provide data independence- one view to retrieve data from several tables( application
users)
- To present different views of the same data- Group of users access as per capita.
Simple view and complex view ::
[ ( alias[ , alias]…..) ]
As subquery
- group functions
- A group by clause
- DISTINCT keyword
- ROWNUM keyword.
- Group functions
- A GROUP BY clause
- DISTINCT keyword
- ROWNUM keyword
- Columns defined by expressions
- NOT NULL columns in base table that are not selected by view.
- WITH CHECK OPTION:: INSERT or UPDATE operations can be done but only for the rows
satisfying the WHERE condition in SELECT.
- To protect data integrity.
- This makes sure that no DML operations can be performed through the view
AS
FROM EMPLOYEES
AS
FROM EMPLOYEES
AS
ON E . DEPARTMENT_ID = D . DEPARTMENT_ID
== to recreate :
AS
SELECT *
FROM EMPLOYEES
WHRE DEPARTMENT_ID = 80
AS
SELECT *
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 80
A sequence :
A sequence :
- NEXTVAL – returns the next available sequence value. It returns a unique value every time it
is referenced, even for different users.
- CURRVAL – obtains the current sequence value
NEXTVAL must be issued to the sequence before the CURRVAL contains the value.
- A ROLLBACK occurs
- The system crashes
- A SEQUENCE is used in another table
=MODIFY A SEQUENCE ::
- Change the increment value, maximum value, minimum value, cycle option, or cache option;
- Cannot change the START WITH
- Drop and Re-create to restart the sequence with different number
- You must be the owner or have the ALTER privilege for the sequence
- Only future sequence numbers are affected using ALTER
- To remove a sequence use the DROP statement
- Some validation is performed, a new MAXVALUE cannot be less than the current sequence
number
INCREMENT BY 10
MAXVALUE 999
NOCACHE
NOCYCLE;
THEN Insert ::
INCREMENT BY 20
MAXVALUE 999999
NOCACHE
NOCYCLE;
INDEXES ::
- It is also be created automatically, AUTOINDEX , when primary key and unique are defined
- Can be used to speed up the retrieval of rows by using a pointer.
- Can reduce disk input/output by using rapid path access method to locate data quickly
- Is independent of table that it indexes, i.e. can be created or dropped anytime
- When you drop a table , respective indexes are also dropped
- If you don’t have an INDEX then full scan of the table happens
- INDEXES are used and maintained by Oracle server.
- Automatically : a unique index is created automatically when you define a PRIMARY KEY or
UNIQUE KEY constraint in a table definition
- Manually : Users can create nonunique indexes on columns to speed up access to the rows.
To DROP an INDEX
ON EMP(JOB_ID);
SYNONYM :: simplify access to objects by creating a SYNONYM ( another name for an object). With
synonyms, you can ::
= CREATE- the DBA can create a public synonym that is accessible to all users
FOR EMP_DETAILS_VIEW;
= SET UNUSED :: - ALTER statement to add, modify, drop and rename are applied on constraint and
column.
- Dropping a column can take a while if the column has large number of values.
- Hence better to set it to be UNUSED and DROP it when only few users are on the system to
avoid extended locks.
- Also, we cannot drop more than one column in a table. Hence making it to UNUSED and then
we can drop all the UNUSED columns
- If the column is set to UNUSED then no longer it can be accessed
- UNUSED columns are not shown in SELECT or DESCRIBE statements
- UNUSED is equivalent to DROP but still hold data, hence on demand of system resource is
lower we can drop it.
---+ = ON DELETE CASCADE – use it to delete child rows when a parent key is deleted.
ON DELETE SET NULL – use it set the child rows value to NULL when a parent key is deleted, else it
will not allow the delete of parent key values
- A constraint is deferred if the system does not check if it is satisfied, until COMMIT statement
is submitted.
- If a deferred constraint is violated, the DB returns an error, and it will be rolled back.
- If a constraint is immediate it will check at the end of each statement, if violated it will be
rolled back immediately
- Use SET CONSTRAINTS to check , at end of each DML statement or when each transaction is
committed.
- To create deferrable constraint, should create a nonunique index for that onstraint
- OPTIONS :
DEFERRABLE or NOT DEFERRABLE
INITIALLY DEFERRED OT INITIALLY IMMEDIATE
=ALTER SESSION
Dropping a table will not release the space, rather DB renames and places in recycle bin.
If you want to drop the table and release the space along with it, then PURGE is used in DROP
statement
PURGE only when you want to drop and do not want to recover.
This reduces one step of dropping and purging from the recycle bin, directly it drops and purges
in same transaction.
FLASHBACK TABLE ::
NOTE :: SCN is system change number ( integer value) generated for each COMMIT statement.
RECYCLEBIN::
- IT is a table that holds data that exists only for the duration of a transaction or session.
- Data in a temporary table is private to the session
- Used mostly in applications where a result set must be buffered
- Once the data is moved to permanent table then the temporary data is automatically
dropped
- Indexes can also be created for the temporary tables, which are also temporary
- Can also create view or trigger on a temporary table
- Temporary tables can be created with 2 options.
Delete rows- transaction specific
Preserve rows- session specific.
CREATE GLOBAL TEMPORARY TABLE CART(PRODUCT VARCHAR 2 (2) , DETAILS VARCHAR2 (20) )
EXTERNAL TABLES ::
NOTE—this is onetime load, it cannot be updated, inserted or deleted with any data.
== ORACLE_LOADER ::
AS ‘ / . . . /emp_dir’ ;
ORGANIZATION EXTERNAL
TYPE ORACLE_LOADER
ACCESS PARAMETERS
NOBADFILE
NOLOGFILE
FIELDS TERMINATED BY ‘ , ‘
PARALLEL 5
DATA DICTIONARY VIEWS :: collection of tables and views, created and maintained by the oracle
server and contains information about the DB.
- Definitions of all schema objects in the database ( tables, views, indexes , synonyms,
sequences, procedures, functions, packages, triggers and so on)
- Default values for columns
- Integrity constraints information
- Names of oracle users
- Privileges and roles that each user has been granted
- Other general database information
ORACLE SERVER
- BASE TABLES
- USER-ACCESSIBLE VIEWS
The SYS user owns all base tables and user-accessible views of the data dictionary. No oracle user
should ever perform any UPDATE/ DELETE/ INSERT any rows in these schema objects.
DESCRIBE DICTIONARY ;
FROM USER_OBJECTS
ORDER BY OBJECT_TYPE;
=DESCRIBE USER_TABLES;
=DESCRIBE USER_TAB_COLUMNS;
FROM USER_TAB_COLUMNS
= DESCRIBE USER_CONSTRAINTS;
FROM USER_CONSTRAINTS
= DESCRIBE USER_CONS_COLUMNS;
FROM USER_CONS_COLUMNS
= DESCRIE USER_VIEWS ;
= DESCRIBE USER_SEQUENCES;
FROM USER_SEQUENCES;
=DESCRIBE USER_IND_COLUMNS;
FROM USER_IND_COLUMNS
IS ‘EMPLOYEE INFORMATION’ ;
- Use subquery in FROM clause of a SELECT, which is similar to how views are used.
- Subquery in FROM clause is Inline View
- DB view can be of simple or complex subquery
- When the DB view is created the SELECT is stored in data dictionary.
= SELECT DEPATMENT_NAME, CITY
FROM DEPARTMENTS
NATURAL JOIN
FROM LOCATONS L
JOIN COUNTRIES C
ON ( L . COUNTRY_ID = C.COUNTY_ID)
--
- Can use subquery in a place of table name in the INTO clause of INSERT
- Select list should match with values of columns
- Any rules in table should be followed while doing this kind of insert
- This way creating a new view for the purpose of insert can be avoided.
----copy data from one table to another- Inserting using subquery as a target
INSERT INTO
(SELECT L . LOCATION_ID, L . CITY , L . COUNTRY_ID
FROM LOCATIONS L
JOIN COUNTRIES C
ON ( L . COUNTRY _ ID = C . COUNTRY _ ID )
JOIN REGIONS USING ( REGION_ID)
WHERE REGION_NAME = ‘Europe’ )
VALUES ( 3300, ‘Cardiff’ , ‘ UK’ ) ;
----
USING WITH CHECK OPTION :: with check option keyword prohibits from changing rows that
are not in the subquery
- Specifying the WITH CHECK OPTION keyword to indicate that if the subquery is used in place
of a table in an INSERT , UPDATE or DELETE,no changes that produce rows that are not
included in the subquery are permitted to that table.
AS
FROM LOCATION L
JOIN COUNTRIES C
ON ( L . COUNTRY_ID = C. COUNTRY_ID)
JOIN REGIONS USING (REGION_ID)
- Use the DEFAULT keyword as a column value where the default column value is desire
- This allows the user to control where and when the default value should be applied to data
- Explicit defaults can be used in INSERT and UPDATE statements, if no default is given , a null
value is used.
- Do not use the values clause in copying data from another table
=default in insert
UPDATE DEPT
FROM EMPLOYEES
Multitable INSERT – you insert result set of sub query into one or more tables
- These are useful in DWH scenarios, where the data load happens on regular basis for
business analysis.
- The data will be copied from different sources and loaded into DWH, this process is called as
---
- WITHOUT- “n” independent INSERT….SELECT statement , processing the same source data
“n” times and increasing the transformation workload “n “ times
- WITH – fast performance, single DML for multiple tables
- Each record from input stream ( non – relational DB), can now be converted into multiple
records for a more relational DB table environment.
---
- Unconditional INSERT – for each row returned by the subquery , a row is inserted into each
of the target tables
- Conditional INSERT ALL – for each row returned by the subquery , a row is inserted into each
target table if the specified condition is met
- Pivoting INSERT – it’s a special case of unconditional INSERT ALL
- Conditional INSERT FIRST- for each row returned by the subquery , a row is inserted into the
very first target table in which the condition is met.
---
UNCONDITIONAL INSERT ::
INSERT ALL
WHERE DEPARTMENT_ID>60 );
CONDITIONAL INSERT :
- Conditional_ insert_ clause : : specify the conditional _ insert_ clause to perform a
conditional multitable INSERT.
- Oracle server filters each insert_ into _ clause through the corresponding WHEN condition,
which determines whether theat insert_ into _ clause is executed.
- A single multitable INSERT can have 127 WHEN clauses.
--- ALL :: Oracle server evaluates each WHEN caluse regardless of the results of the
evaluation of any other WHEN clause.
- For each WHEN clause condition is true, oracle executes corresponding INTO clause list.
----- FIRST :: Oracle server evaluates each WHEN in the order in which it appears in statement
- If the first WHEN clause evaluates to true, oracle executes the corresponding INTO clause
and skips subsequent WHEN clause for the given row.
----- ELSE clause : - If not WHEN clause evaluates to true, and if specified the ELSE clause, then
oracle executes the INTO clause list associated with ELSE clause.
- If not specified the ELSE clause, then oracle takes no action for that row.
INSERT ALL
WHEN HIREDT < ’01- JAN -95’ THEN INTO EMP_HISTROY VALUES ( EMPID, HIREDT, SAL)
WHEN COMN IS NOT NULL THEN INTO EMP_SALES VALUES ( EMPID, SAL, COMN)
FROM EMPLOYEES ;
WHEN SALARY < 5000 THEN INTO SAL_LOW VALUES ( EMPLOYEE_ID , LAST_NAME, SALARY )
WHEN SALARY BETWEEN 5000 AND 10000 THEN INTO SAL_MTD VALUES ( EMPLOYEE_ID,
LAST_NAME, SALARY )
FROM EMPLOYEES;
CREATE TABLE MANAGERS ( LAST_NAME VARCHAR2 (20) , JOB_ID VARCHAR2 ( 20) , SALARY
NUMBER ( 8, 2) ) ;
CREATE TABLE RICHPEOPLE ( LAST_NAME VARCHAR2 ( 20) , JOB_ID VARCHAR2 (20 ) , SALARY
NUMBER ( 8 , 2 ) ) ;
INSERT ALL
WHEN JOB_ID IN ( SELECT JOB_ID FROM JOBS WHERE JOB_TITLE LIKE ‘ &Manager&’ ) THEN INTO
MANAGERS ( LAST_NAME, JOB_ID, SALARY) VALUES ( LAST_NAME, JOB_ID, SALARY )
WHEN SALARY > 10000 THEN INTO RICHPEOPLE ( LAST_NAME, JOB_ID, SALARY ) VALUES
( LAST_NAME, JOB_ID , SALARY )
SALES_MON NUMBER ( 8 , 2) ,
SALES_TUE NUMBER ( 8, 2 ) ,
SALES_WED NUMBER ( 8, 2) ,
SALES_THU NUMBER ( 8, 2) ,
SALES_FRI NUMBER ( 8, 2) );
WEEK NUMBER ( 2) ,
SALES NUMBER ( 8, 2 ) );
INSERT INTO SALES_SOURCES_DATA VALUES ( 1786, 1750, 2200, 1500, 1500, 3000) ;
INSERT ALL
FROM SALES_SOURCE_DATA;
==
MERGE :: Provides the ability to conditionally update, insert , or delete data into a DB table
CREATE TABLE EMPCY AS SELECT * FROM EPLOYEES WHERE SALARY < 10000;
UPDATE SET
E. FIRST_NAME,
E. LAST_NAME,
E. EMAIL,
E. PHONE_NUMBER,
E. HIRE_DATE,
E. JOB_ID,
E. SALARY * 2,
E. COMMISSION_PCT,
E. MANAGER_ID ,
E. DEPARTMENT_ID ) ;
THE VERSIONS clause does not change the plan of the query.
- Running a query on a table that uses the index access method, the same query on same
table with VERSIONS clause continues to use IAM.
- The VERSIONS clause has no effect on the transactional behaviour of a query.
- The default VERSIONS clause can be specified as VERSIONS BETWEEN {SCN|TIMESTAMP}
MINVALUE AND MAXVALUE.
- Can have DML and DDL that use a VERSIONS clause within subqueries.
- Changes made by current active transactions are not returned.
- The row access for a version query can be defined in two categories.
ROWID- based row access- Here all versions of the specified ROWID are returned irrespective
of the row content. This means that all versions of the slot in the block indicated by the
ROWID are returned
All other row access- here all version of the rows are returned.
SELECT SALARY FROM EMP WHERE EMPLOYEE_ID = 107;
COMMIT