Dbms
Dbms
Dbms
Introduction
Data:
Database:
Architecture of a DBMS
DBMS Architecture and Data Abstraction :
Abstraction simplifies database design and separates the applications from physical
data storage.
Physical Level: This is the third level ,the physical schema of the DBMS
architecture depicted in the diagram above.This is the lowest level of data
abstraction.
Logical Level: This is the middle layer of database architecture. This is the
second level, the conceptual schema of the DBMS architecture depicted in the
diagram above. This level comprises of what information is actually to be stored in
the database in the form of tables. It also describes the relationship among the data
entities in relatively simple structures.
View Level: This is the top most layer of the database architecture. This is the
first level, the external level of the DBMS architecture depicted in the diagram
above.This is the highest level of abstraction. Each user uses only a part of the
actual database. This level exists to ease the accessibility of the database by an
individual user. As per requirement of each individual user, multiple views of the
same database may exist. Users can just view the data and interact with the
database, independent of storage and implementation details of it.
Physical level data independence : The characteristic of being able to modify the
physical schema without any alterations to the conceptual or logical schema, done
for optimization purposes, e.g., we can easily make any change in the storage size
of the database system, without affecting the conceptual structure of the database .
Logical level data independence: The characteristic of being able to modify the
logical schema without affecting the external schema or application programs. The
user view of the data would not be affected by any changes to the conceptual view
of the data like insertion or deletion of attributes, altering table structures entities
or relationships to the logical schema etc.
Data Modeling
Data model is the logical design and structure of a database. Data model defines
how data will be stored, accessed and updated in a database management system. It
defines data elements and relationships among various data elements for a
specified system and the constraints to maintain data integrity.
Data modeling is the process of documenting the logical design in the form of an
easily understood diagram, using text and symbols to represent the way data needs
to flow. This diagram can be used as a blueprint for the construction of the
database for applications to be developed.
To overcome the limitations of the traditional file processing system , the modern
DBMS was created.
Advantages of DBMS :
Types of DBMS
Hierarchical Database
Network database
Object relational database
Relational database
Hierarchical DBMS:
In hierarchical DBMS , the relationships among data in the database are
established in such a way that one data item is present as the subordinate of
another one .
The data structure "tree" is followed by the DBMS to structure the database.
Network DBMS:
Schema:
For example the design of the tables for an entire application or project.
Instance:
RDBMS terminologies
Relation:
Tuple:
A tuple, also called a row of data, is each individual entry that exists in a table.
Fields:
Keys in DBMS
Super Key:
A Super key is any combination of fields within a table that uniquely identifies
each record within that table.
Candidate Key:
Primary key:
Foreign key:
A foreign key is the field in a table that generally references values from
primary key field of other table
Oracle Connectivity
Connecting to Oracle from Unix/Linux :
If we are going to connect to Oracle from Unix , after successful login to
unix, one can connect to oracle schema from any directory. For example, in
the below screen shot the user has connected to oracle schema from his
“home” directory.
-Use the command sqlplus followed by username@dbname/password.
For example, if user name is “pj01fac01” , db name is “unixdb” and
“tschyd” is the password, command will be as below:
$sqlplus pj01fac01@unixdb/tschyd
For clearing the screen, we can use “cl scr” command at SQL prompt
SQL> cl scr
(Note: “cl” and “scr” are two words separated by space) Or clear
Screen can be used.
To switch from one user to another user, use “connect” command
If you want to execute UNIX commands from SQL prompt, use “!” before
the command as shown below
Note : By using only !, you can go to unix shell prompt. To be back to
oracle, exit is the command.
We can also use “vi” editor for preparing the “.sql” files and editing SQL
queries. To view the buffer content use “L[IST]” Command at SQL prompt.
The last SQL query which is executed at SQL prompt will get stored in
buffer.
To view the buffer content use “L[IST]” Command at SQL prompt.
To edit the buffer content, use “E[DIT]” command at SQL prompt. Edit the
content in insert mode then save and quit from the editor by using “:wq”
command in escape mode.
To execute the buffer content use “/” or “R[UN]” command at SQL prompt.
To disconnect from SQL, use “exit” command as shown below
Introduction
Entity Relationship (ER) model proposed by Peter Chen in 1976 is a conceptual
representation of data. It is capable of describing the data requirements for a new
information system in a direct and easy to understand graphical notation. ER data
model represents the overall logical structure of the
DB. ER diagram is a graphical representation of the logical structure of a database.
Basic ER constructs
The ER model is designed with the help of the below basic constructs:
Entity
Attribute
Relationship
Weak Entity
Weak entity is an entity whose existence depends on existence of another
entity.
A weak entity cannot be uniquely identified by its attributes alone, hence it
must use a foreign key along with its attributes which is a primary key of the
entity on which the weak entity depends upon.
Graphically weak entity is represented by double rectangle.
A relationship can be
a) recursive
b) binary
c) n array
d) have attributes
Recursive relationship
A recursive relationship is the one which involves only one single entity. The
above representation specifies , a person marries another person.
Binary relationship
A relationship which involves two entities. The above representation specifies that
'books' are available in the
'library'.
The above representation specifies that 'books' are available in the 'library'.
Ternary Relationship
A relationship which involves three entities.
The above ERD represents 'Store sells Items and maintains the quantity sold and
the date Item was sold for all the Items sold'.
Simple attribute
An attribute which can have atomic values, which cannot be divided further.
Key attribute
Composite attribute
Derived attribute
An attribute that do not exist in the physical database, but their values are derived
from other attributes present in the database. For example, age of an employee.
Age of an employee need not have to store and can be derived from data_of_birth.
Cardinalities
In case of a relationship between two entity sets , cardinality defines the number
of entities in one entity set, which can be associated with the number of
entities of other set via relationship set..
4 types of cardinalities can be maintained:
a) 1 : 1 ( ONE to ONE )
The above representation indicates 'many stores sells many goods'. Note :( * )
specifies many
Normalization
Eliminate data redundancy(storing the same data in more than one table)
Ensure Data Dependencies(only storing related data in a table)
Ensure Data Consistency
Reduces the amount of space a database consumes
Ensure that data is logically stored.
Normal Forms
The database community has developed a series of guidelines for ensuring that
databases are normalized. The below are the normal forms we can apply to
normalize the tables
To say a table to be in First normal form , the below two rules needs to be satisfied
1. The table should be atomic - Each Column for a respective row should be
atomic in the table"
Let us consider the above table - Which is having "Repeating groups of data" for
the records of students named Ann Smith and John Doe.
As shown in the highlighted boxes, the data in some columns is repeating because
of values to be accommodated in other columns.
Any way the table maintains atomicity as each column / attribute consists of single
value .
To convert the above table into First normal form, We need to avoid the repeating
groups. By splitting this table into two tables as Shown below, that has been
achieved.
Student_Unit Table:
To identify each row uniquely , there is a primary key for each table as below
In the first table student id is primary key where as in second table the combination
of student id and unit code is defined as primary key.
Let us consider the table , which is in first normal form . Let us consider the
following Student_Unit table .
The table is in 1NF but still we can see redundant data in the second and third
columns for the first and the last rows of the table. This redundancy has taken
place because of the partial dependency that exists in the table.
" Every non key attribute of a table should fully depend on Primary key, but
not on part of the Primary Key"
To make the table to be in Second Normal Form, we have to remove the partial
dependency. Hence we have to divide the table into two tables, in such a way that ,
each non key attribute depends fully on primary key, but not on part of Primary
key
If we notice the above tables, all Non Key attributes (UnitCode in first table and
Unit Name in Second table) are fully depends on Primary key
But the above table is not in Second Normal form and as well as there is a
transitive dependency between Course Name ->CourseCode->UnitCode.
Which leads data inconsistency while performing DML operations on the above
table, So let us divide the above table into the below tables in such a way that the
resultant tables are in second normal form and as well as in third Normal Form
CourseCode CourseName
C2009 Computing
C2009 Computing
Business and
B2009 Computing
To convert a table to BCNF, you must split the table using these two steps.
One with attributes of X together with the remaining attributes from the original
relation
Keep repeating the above decomposition process until all of your tables are in
BCNF.
Example
The nontrivial functional dependencies in the table , which are violating BCNF are
None of the above functional dependencies are not violating the BCNF Rules,
The key for the first table is Writer ,The key for the second table is Book title.
The key for the third table is Writer and Book title, together.
Structure Query Language(SQL) is a database query language used for storing and
managing data in Relational DBMS.SQL was the first commercial language
introduced for E.F Codd's Relational model of database. Today almost all
RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) use SQL as the standard
database query language. SQL is used to perform all types of data operations in
RDBMS.
The different categories of SQL used in RDBMS to store and manipulate data are:
CREATE
ALTER
DROP
RENAME
TRUNCATE
Data types
A data type identifies or classifies a particular type of information or data. Some
commonly used data types are:
The CREATE keyword is used for creating database objects like tables,
views,triggers, and indexes
Syntax:
The above statement adds a new column 'age' of number data type with
constraint not null.
The above statements renames the column name salary to em_sal anddrops column
age
Truncate Table:
Remove all the rows and resets schema of the table.
Drop table :
Deletes table entirely from the database.
DROP TABLE Employee;
Renaming a Table:
Changing the name of a table.
RENAME Employee to Emp_table;
The Data Query Language (DQL) is used to retrieve the data from one or more
tables.
The SELECT statement is the only DQL statement.
Using SELECT statement the following operation can be performed
Projection : This operation results subset of columns
Selection : This operation results subset of rows
Projection means selecting set of columns from a table. In the Below table, 3
columns marked with yellow colour suggesting That those columns are selected.
Selection means selecting set of rows from a table. In the Below table, 3 rows
marked with yellow colour suggesting That those rows are selected.
Syntax:
The SELECT and FROM clauses of the statement are mandatory.The remaining
four clauses are optional.
Consider the following table
Table 1.1 customer_details
The where clause can be used to refine selection results by adding search criteria.
The above query displays name and age of customers whose salary more than
50000 From customer_details table
The above query displays name and location of customers who are from Kolkata
and Delhi
The above query displays name and location of customers whose age ranging from
20 to 40
The above query displays name and age of customers whose location not specified
The above query displays name and age of customers whose age available
Name, age and salary of the customers displayed as per the ascending order
of their salary.
DESC keyword can be used to display the list in descending order.
The GROUP BY statement is used to group the result-set by one or more columns.
The above query displays number of customers present in Particular age group.
INSERT statement
Syntax:
INSERT INTO table_name[(column1, column2,...)]
VALUES(value1, value2,....);
If values in all the columns inserted in proper order, column names are not
mandatory.
Syntax-:
Insertion can also be done in interactive way. The records can be inserted in
interactive manner also
Syntax:
UPDATE statement
Syntax:
Syntax:
Example
A Transaction begins when the first executable sql statement is encountered. The
Transaction terminates when the following specifications occur.
A COMMIT or ROLL BACK issued.
A DDL statement issued
A DCL statement issued
Failure of machine or system crashes
A DDL or DCL statement is automatically committed and hence implicitly
ends a Transaction.
COMMIT
SAVEPOINT
ROLLBACK
COMMIT
It ends the current Transaction by making all pending data changes permanent.
Syntax:COMMIT;
SAVEPOINT:
Syntax:SAVEPOINT ;
Ex: SAVEPOINT S1;
ROLLBACK:
Introduction
SQL Constraints are used to specify rules for the data in the table, to ensure
that the data in the table conforms to the requirements defined.
Constraints are very important to maintain the data integrity.
Constraints can be defined when the table is created (with the CREATE
statement) or can be added after the table is created (with the ALTER
statement).
Every constraint is provided with a name (CONSTRAINT_NAME) in the
database and name can be given when it is defined. In case we do not give a
name to the constraint when we declare the constraint, Oracle associates the
constraint with a name.
Within the same scope, no two objects can have same name. Hence one user,
can not use a name as constraint name if it is already used for some other
object.
Constraint Types
There are six types of constraints available to provide rules to the tables.
PRIMARY KEY
UNIQUE
FOREIGN KEY
CHECK
NOT NULL
DEFAULT
Declaration Style
1. Column Level (OR) In-line style : Constraint is defined as part of the definition
of an individual column or attribute. Constraints can be defined at column level
using both the CREATE and ALTER statements. They are usually specified when
the constraint is specific to the column only.
Syntax:
CREATE TABLE sample (col1 DATATYPE(size) CONSTRAINT_NAME,col2
DATATYPE(size)
CONSTRAINT_NAME,…......);
2. Table Level (OR) Out-of-lilne style : Constraint is defined as part of the table
definition. Constraints can be defined at table level using CREATE statement.
They are usually specified when the constraint need to be applied on the
combination of columns together.
Syntax:
CREATE TABLE sample
(col1 DATATYPE(size), col2
DATATYPE(size),col3DATATYPE(size),CONSTRAINT_NAME(col1),
CONSTRAINT_NAME(col2),…......);
Primary Key
Restrictions
A table can have only one PRIMARY KEY.
PRIMARY KEY cannot be defined on the columns having
LOB,LONG,LONG RAW,BFILE etc... data types.
A Composite PRIMARY KEY can be defined only as a table level key.
A composite PRIMARY KEY cannot have more than 32 columns.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name
PRIMARY KEY, col2 DATATYPE(size), col3 DATATYPE(size),........);
The above example specifies that every location must have a unique location_id
value to identify the location and that should not be left blank.
Syntax :
The above example specifies that every location must have a unique value for
location_id and that should not be left blank.
The above example specifies that, for each record in this table , the combination of
the following three fields sales_id , cust_id and prod_id will only give a unique
value but not the value of only one of these fields can be unique .This is an
example of a composite PRIMARY KEY .
Syntax:
Ex:
Foreign Key
Restrictions
It preserves the defined relationship between the tables when the records are
inserted or deleted.
It ensures that key values are consistent across the table
Syntax :
Example :
The above example specifies that the address column values in the person table are
linked/references with the column: loc_id values of the location table.
The above example specifies that in order to maintain the address for each person,
the addresses available in the location table must be linked to the address field of
the person table.
Composite Foreign key
Syntax :
We can use ALTER statement to add a Foreign Key to an already created table.
Syntax:
Ex:
When we use the column value of a parent table as foreign key in a child table, if
the record in the parent table is deleted and the value still remains in the child table
will lead to data inconsistency. Hence, database does not allow it . While creating a
foreign key, we can specify what to do if we try to delete a value from a parent
table which we have used as foreign key in a child table by using clauses like ON
DELETE SET NULL and ON DELETE CASCADE .
A foreign key with ON DELETE SET NULL means , if a record in the parent table
is deleted then the corresponding records in the child table will be automatically set
to NULL.
Syntax:
Ex:
Syntax:
The above example specifies that if any record in the location table (loc_id) is / are
deleted , then automatically the respective records from the person table ( which
are REFERENCING the values of respective loc_id of the deleted record from
Location table) will be set to NULL
ON DELETE CASCADE
Syntax :
The above example specifies that, If the any record is deleted from the location
table, then the corresponding records from the person table ( which are
depending on the values of loc_id of deleted record from location table) will be
deleted automatically
Syntax:
The above example specifies that, If any record is deleted from the warehouse
table , then automatically the records from production table( which are referring
the values of the composite key(id ,name) of the deleted record from
the warehouse table ) will be deleted automatically.
Syntax:
The above example specifies that , If the data is deleted from the location table
location id , automatically they will be removed from person table address field.
Not Null:
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name
NOT NULL,col2 DATATYPE(size) CONSTRAINT cons_name NOT NULL,
col3 DATATYPE(size) , ........);
Example:
The above example specifies that Student id should not contain any duplicate and
null values , student name and date of birth should not contain null values but they
can have duplicate values and gender field is restricted with the specified values.
Suppose a table has been created without a CHECK constraint and later it was
identified to maintain a CHECK constraint in the table , this can be achieved with
the help of ALTER statement.
Syntax:
ALTER TABLE table2 MODIFY (col1 DATATYPE(size) NOT NULL);
Example:
The above statement modifies the existing table schema by adding NOT NULL
constraint on table2 using column modify option. The above example specifies that
student id should not contain any duplicate and null values, student name and date
of birth should always have a value but need not have to be unique and gender
field is restricted with the specified values.
Remove Constraint:
Syntax:
Example:
From the above example we can observe that if at all the government does not
want to maintain a NOT NULL constraint for the dob field, that can be removed.
Unique Key:
Restrictions
A UNIQUE KEY constraint can be defined on a table with the help of a CREATE
statement. UNIQUE KEY can be defined immediately after the column definition.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name
UNIQUE, col2 DATATYPE(size), col3 DATATYPE(size),........);
Example:
The above example specifies that every supplier must have a unique value to
identify the supplier.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size), col2 DATATYPE(size), col3
DATATYPE(size), ........, CONSTRAINT cons_name UNIQUE(col1));
Example:
The above example specifies that every supplier must have a unique value to
identify the supplier.
Syntax :
Example:
The above example specifies that every warehouse need to have a specific id and
specific name, which is possible with composite UNIQUE constraint.
Suppose a table has been created without a UNIQUE KEY constraint and later it
was identified to maintain a UNIQUE constraint in the table, this can be achieved
with the help of ALTER statement.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name UNIQUE(col1);
Example:
The above example specifies that, whenever a customer wants to take a new
simcard , the telephone service provider will collect all the details of the customer
and makes the new_sim_no as UNIQUE so that the new_sim_no can be filled later
once the address_proof submitted is verified.
Remove Constraint:
Syntax:
Example:
From the above example, we can observe that if at all the government does not
want to maintain a UNIQUE constraint, which can be removed.
Check Constraints
Restrictions
The CHECK constraint can refer any column of the current table , but
cannot refer any column of another table.
CHECK constraint condition cannot include any view or sub query.
Syntax :
Example:
The above example specified in the gender fields only the values 'M' or 'F' only
need to be entered.
A CHECK constraint can be defined as a table level definition once finishing all
the column definitions.
Syntax :
The above example specifies that gender fields only the values 'M' or 'F' only need
to be entered.
Suppose a table has been created without a CHECK constraint and later it
was identified to maintain a CHECK constraint in the table , this can be achieved
with the help of ALTER statement.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name CHECK (condition);
Example:
The above example specifies that gender fields only the values 'M' or 'F' only need
to be entered.
In order to remove a CHECK constraint which is defined on a table , we need to
drop the constraint defined.
Syntax:
Example:
From the above example we can observe that if at all the government does not
want to maintain a CHECK constraint for the gender field, that can be removed.
ntroduction to Oracle Built-in Functions
Oracle Built-in Functions are the functions supplied by Oracle that can be used to
manipulate data items and return a result.There are two types of Built-in functions
available in Oracle.
Single Row Functions: Single row or Scalar functions return a value for every
row that is processed.
Group Functions: These functions group the rows of data based on the values
returned by the query, performs the aggregate function(sum,avg etc.) on each
group and return one value per group of rows.
Single row or Scalar functions return a value for every row that is processed .
2) Character or Text Functions: These are functions that accept character input
and can return both character and number values.
3) Numeric Functions: These are functions that accept numeric input and return
numeric values.
4) Date Functions: These are functions that take values that are of data type
DATE as input and return values of data type DATE, except for the
MONTHS_BETWEEN function, which returns a number.
Numeric Functions
Dual table
This is a single row and single column dummy table provided by oracle.
This is used to perform mathematical calculations without using a table.
Oracle presents the output of every operations in a tabular format so that it
seems to the user that the output comes from a table
The ABS function returns the absolute value of the parameter passed.
Syntax : ABS(number)
The above query returns the absolute value of the given 'number'.
The MOD function returns the remainder value of the parameter passed.
Syntax : MOD(number1,number2)
Ex: SELECT MOD(10,4) FROM dual;
Output : 2
The above query returns the remainder when 10 is divided by 4.
Ex:
Cube
64
The above query returns the output when 4 is raised to the power of 3. SQRT
function returns the square root of a number passed as parameter.
Syntax: SQRT(number)
Ex:
Square Root
8
The above query returns the square root value of 64.
The above query returns the largest integer nearest to 7.14 & 7.84.
Ex: SELECT FLOOR(-7.14) FROM dual;
Output : -8
The above query returns the largest integer nearest to -7.14.
The CEIL function returns the smallest integer greater than or equal to the value
mentioned in parameter.
1) The TRUNC function truncates the value present in the column, expression up
to decimal places mentioned in first parameter.
2) If the second argument is 0 or is missing, the value is truncated to zero decimal
places.
Syntax: TRUNC(decimal number,number of places)
Ex:
Ex:
Rounded
137
The above query returns the integer value.
1) The ROUND function round off the value present in the column,expression up
to decimal places mentioned in first parameter.
2) If the second argument is 0 or is missing, the value is rounded to zero decimal
places.
Syntax: ROUND(decimal number,number of places)
Rounded
137.574
The above query returns the decimal number with three digits after the decimal
point where 4th digit is rounded.
Rounded
138
The above query returns the integer value rounded to the next highest value. If the
second argument is negative number, the value is rounded up specified decimal
places to the left (rounded to the nearest unit of 10).
Rounded
140
The above query returns the integer value which is the nearest tens value.
Ex: SELECT ROUND(137.5748,-2) As Rounded FROM DUAL;
100
The above query returns the integer value which is the nearest hundreds value.
Character Functions:
There are two types of character functions.Character to character functions accept
string as input and will give string as output.
INITCAP
LOWER
UPPER
CONCAT
LPAD,RPAD
TRIM
SUBSTR
REPLACE
Character to number functions accept string as input and will give number as
output.
LENGTH
INSTR
INITCAP: This function sets the first character in each word to upper case and the
rest to lower case.
Syntax : INITCAP(expr1)
Ex: SELECT INITCAP(emp_name) FROM Employee:
Amit
Ajay
Sima
Dipa
Anuj
The above query returns all the employee names with the first letter in upper case
and rest other characters in lower case.
LOWER: This function converts all letters in the specified string to lower case. If
there are characters in the string that are not letters, they are unaffected by this
function.
Syntax : LOWER(expr1)
Ex: SELECT LOWER (emp_name) FROM employee:
amit
ajay
sima
dipa
anuj
The above query returns all the characters of the employee name in lower
case.UPPER:This function converts all letters in the specified string to uppercase.
If there are characters in the string that are not letters, they are unaffected by this
function.
Syntax : UPPER(expr1)
Ex: SELECT UPPER (emp_name) FROM Employee:
AMIT
AJAY
SIMA
DIPA
ANUJ
The above query returns all the characters of the employee name in upper case.
The above query returns the emp_name & dep_name concatenated into a single
string.
SUBSTR: Returns specified characters from a string, starting from specific
position to required characters length.
Syntax : SUBSTR(col/expr,m,n)
Syntax : REPLACE(string,search_string,replace_string)
Ex: SELECT REPLACE(branch_name,'Mumbai','Kolkata') FROM Employee
LPAD pads the character value right justified to a total width of n character
positions.
Syntax : LPAD(expr1,padded_length,padded_string)
RPAD pads the character value left justified to a total width of n character
positions.
Syntax : RPAD(expr1,padded_length,padded_string)
The default padding character is space.
Since the third parameter is not specified in the result of the above query will be by
default space padded for the previous four positions.
Ex2: SELECT LPAD('jhon',8 ,'x') FROM dual;
xxxxjhon
The above query fills the four blank spaces with 'x' left of the given string.
The above query fills the four blank spaces with 'x' right of the given string.
TRIM: It enables to trim leading or trailing characters or both from a string.
If we don’t specify anything, it will trim spaces.
The above query removes 'trailing' 's' from the given string.
The above query removes 'leading' 's' from the given string.
The above query removes 'trailing' & 'leading' 's' from the given string.
The above query removes 'trailing' & 'leading' spaces from the given string.
INSTR: This function returns the location of a sub string in a given string.
The above query returns the first position of 'e' searched from the start of the given
string.
The above query returns the second position of 'e' searched from the start of the
given string.
The above query returns the first position of 'e' searched from the fifth position of
the given string.
The above query returns number characters in the branch_name field for each and
every record.
The above query returns the number of characters from the given string.
Date Functions: These are functions that take values that are of data type DATE
as input and return values of data type DATE, except for the
MONTHS_BETWEEN function, which returns a number.
The Oracle date function SYSDATE() returns the current date and time in the
default Oracle date format.
For example,
to_char (SYSDATE, 'MM-DD-YYYY HH:MI:SS');
This Oracle date function returns a string containing not only the current date, but
also the current time down to the second. The most common uses of
SYSDATE()don’t use a date format model:
dStartDate := SYSDATE;
Conversion Functions:
NVL
NVL2
NULLIF
NVL: lets you replace null with a string in the results of a query .
Syntax : NVL( string1, replace_with).
If string1 is null, then NVL returns replace_with .
If string1 is not null, then NVL returns string1.
NVL2: NVL2 function extends the functionality found in the NVL Function.
It lets you substitutes a value when a null value is encountered as well as when a
non-null value is encountered.
Syntax : NVL2(string1,value_if_not_null,value_if_null)
if string1 is not null then NVL2 returns value_if_not_null.
if string1 is null then NVL2 returns value_if_null.
Ex: SELECT NVL2(emp_name,dep_name,'NOT AVAILABLE') FROM
Employee;
NULLIF: NULLIF compares expr1 and expr2. If they are equal, then the function
returns null. If they are not equal, then the function returns expr1 .
Syntax : NULLIF(expr1,expr2)
Ex: SELECT NULLIF( dep_name,'HR') FROM Employee;
The above query returns NULL if dep_name field consists of 'HR', otherwise it
returns job.You cannot specify the literal NULL for expr1.
SUM
AVG
MAX
MIN
COUNT
Syntax:
AVG([DISTINCT] column_name)
Ex: SELECT AVG(salary) as “Average Salary” FROM Employee;
Output :
Average Salary
21500
The above query displays the average salary of all the employees in the table
Employee
Maximum Salary
16000
The above query displays the maximum salary of all the employees in HR
Department in the table Employee.
Syntax:
MIN([DISTINCT] column_name)
Minimum Salary
10000
The above query displays the minimum salary of all the employees in HR
Department in the table Employee.
COUNT: Returns the count of not null values ignoring null values.
Syntax:
COUNT([DISTINCT] column_name)
COUNT:(*) Count function with asterisk returns the count of total number of rows
including null values
Syntax:
COUNT(*)
Ex: SELECT COUNT(*) FROM Employee;
5
The above query displays the total number of rows in table Employee.
GROUP BY clause
Creates a data set, containing several sets of records grouped together based on
a condition.
Syntax:
SELECT [,], AGGREGATE FUNCTION() FROM Table_Name GROUP BY [,] ;
Output :
No of Employee
HR 2
Marketing 2
Admin 1
WHERE clause
Used to apply a filter condition before the Grouping the rows.
Syntax:
SELECT [,], AGGREGATE FUNCTION() FROM Table_Name WHERE GROUP
BY [,] ;
Output :
HR 1
Marketing 1
Admin 1
The above query displays department wise count of salary more than 15000.
HAVING clause
Used to apply a filter condition on Aggregated values.
Syntax:
SELECT [,], AGGREGATE FUNCTION() FROM Table_Name WHERE GROUP
BY [,] HAVING ;
Output :
HR 16000
Marketing 20000
The above query displays the departments for which total salary is less 30000
excluding the Admin department, total salary for which is 40000.
Introduction to Joins:
A join is a query that combines rows from two or more tables based on a
condition based on common column
Join achieves the goal of creating a single SQL query that can fetch data
from two or more tables.
The SELECT statement can select any of the columns from any of the tables
referred in from clause in Join query
Different types of SQL joins :
CROSS JOIN
INNER JOIN
EQUI JOIN
NON EQUI JOIN
OUTER JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
o FULL OUTER JOIN
SELF JOIN
Guidelines:
When writing a SELECT statement that joins tables, if the same column name
appears in more than one table, the column name must be prefixed with the table
name/Alias name of the table. To join 'N' tables , a minimum of 'N-1' join
conditions are required. Consider the below tables:
Consider the below three Tables to understand the joins working mechanism:
1.Cross Join:
The Cross join / Cartesian product is a join query , that does not contain a join
condition. Oracle combines each row of one table with each and every row of the
other.
Syntax:
Ex:
2.Inner Join:
An inner is used when the join fields are guaranteed not to be NULL.
This join condition combines/fetch the data from the matched records of two tables
(Tow copies of same table in case of self-join ) based on the common columns
from the two tables ,on which the join condition is applied .
Syntax :
Ex: To get Department name for each Employee along with the Employee
details
Select EMP_ID,EMP_NAME,EMP_SAL,EMP_LOC,EMP_MGR_ID,EMP_JOB,
EMP_DEPT_ID,DEPT_NAME from Employee,Department where
Employee.EMP_DEPT_ID=Department.DEPT_ID;
The above query return multiple records where each record contains the data from
the matched records of Employee and Department tables , based on the join
condition formed on common column between the two tables
i.e .. For each record of employee table, if there is a matched record in department
table with reference to the department Id , then the Query will fetch some data
from Employee and some data from department table
Note:
Table Name is not mandatory to prefix before the Column in the Select Statement
column list , if the column name is not same across two tables , from which the
data is being fetched.
Syntax :
SELECT tableA.col1, tableA.col2, tableB.col1,..... FROM
tableA, tableB WHERE tableA.col1 BETWEEN tableB.col2 AND tableB.col3;
Example:
The above query retrieves the employee details along with his salary grade
based on the join condition.
3.Outer Join:
Outer join extends the result of Equi join. Outer join returns all the rows from both
the tables that satisfy the join condition and also the rows from one table which do
not satisfy the join condition. The Outer join operator is ( + ) , which is used on
one side of the join condition.
Example:
Retrieve all the employee details along with their department details.
If employees are already tagged then get the tagged department details along with
the employee details , If not tagged to any department then get atleast the employee
details
Query:
select EMP_ID,EMP_NAME,EMP_SAL,EMP_LOC,EMP_MGR_ID,EMP_JOB,
EMP_DEPT_ID,DEPT_Name from Employee,Department where
Employee.EMP_DEPT_ID=Department.DEPT_ID(+);
The above query displays all the records which are matching with the join
condition from both the tables along with the rows from employee table which are
not matched with department table.
If we notice the above output, for the first 5 records, there is a match
of Department Id between two tables. Therefore, the Query retrieves the data
from the matched records from both the tables. However, in case of last two
records from Employee table, there are no records in the department table having
the same department id, so there is no match found in department table. Hence,
only the data from Employee table is displayed.
It is a join which returns all the rows from the right hand side of the table specified
at the join condition and only those rows from the other table which are matching
with the join condition.
Syntax : SELECT tableA.col1,tableA.col2,tableB.col1,..... FROM tableA,tableB
WHERE tableA.col1(+) = tableB.col1;
Example: Fetch the department details for all the departments with the details of
Employee, for all employees tagged to a department. If for any department, there is
no employee, fetch the department details only.
Query:
select EMP_ID,EMP_NAME,EMP_SAL,EMP_LOC,EMP_MGR_ID,EMP_JOB,
EMP_DEPT_ID, DEPT_Name from Employee,Department where
Employee.EMP_DEPT_ID(+)=Department.DEPT_ID;
If we notice the above output, for the first 5 records, there is a match
of Department Id between two tables. Hence, the Query retrieves the data from
the matched records from both the tables. However, for the last two records of
Department table, there are no record in the Employee table having that department
Id. Hence, only the data from Department table is displayed .
It is a join which returns all the rows from both the tables which are placed on
either side of the join condition.
Example:
Retrieve all the records from Employee and Department table in such a way that, if
there is a match between the tables with reference to Department Id, then get the
resulted record from two tables else fetch the employee data though they have not
tagged and Department data though there is no single employee tagged for the
department
Output:
4.Self Join:
It is a join used to join a table to itself. Single table is logically considered as two
tables and joined .
Syntax : SELECT A.* FROM tableA A,tableA B WHERE A.col1 = B.col1 AND
condition;
Example:
GET the names of the Managers for each Employee from Employee table.
In the Employee table, Manager name is not available as a column in the table.
However, every Manager is an Employee. For each row , the value for the attribute
Emp_Mgr_Id is the value of the emp_Id of attribute the employee who is the
manager for that employee.
To solve the query, we have to join the Employee table to itself and compare the
Manager Id of each Employee with the Employee IDs of the other copy of the table
and get the EmpName accordingly from the second copy of the table which is the
manager Name
Output:
The above query is going to display the details of Manager for each Employee
Introduction to Subqueries
A sub query is a query within a query. The outer query is the main query
and the inner query is called sub query.
The sub queries can reside in the WHERE, FROM or SELECT clause.
A sub query in the WHERE clause of a SELECT statement is called
NESTED sub query.
A sub query in the FROM clause of a SELECT statement is called INLINE
VIEW.
For a sub query used in WHERE clause, only up to 255 levels of sub queries
can be written.
In Sub Queries, the inner query is executed and based on the result of inner
query, the records from the outer query is fetched.
General Syntax:
SELECT select_list FROM table_name WHERE col1 WHERE operator
(SELECT select_list FROM table_name);
Consider the below tables
Example: Get the details of all the employees who are working in the
department of Raghava
Single row sub queries returns only one row from the Inner SELECT statement.
The operators that can be used :
= != < <= > >=
Example 1: Display all employees who is working in the same department, where
RAJU is working
Query:
Output Analysis: The above query returns employee details, who are working
along with RAJU in the same department.
Example2: Fetch the details of Employees whose salary is more than the Salary of
Raju
Query Output:
Output Analysis: The above query returns the employee details , who are earning
more than RAJU.
When performing this logic GROUP BY clause should not be available in the inner
query.
Query:
SELECT * FROM employee WHERE salary = (SELECT MAX(salary)
FROM employee);
Output:
We can use HAVING clause in a Sub query. The inner query is executed first and
the results are returned into the HAVING clause of the outer query. When
performing this logic, the outer queries HAVING clause contains GROUP
functions.
Example: Fetch department wise minimum salary for all the departments which
has the minimum salary higher than the minimum salary of employees of the
Department with department number 103.
Query:
SELECT did,MIN(salary) FROM employee GROUP BY did HAVING
MIN(salary) >
(SELECT MIN(salary) FROM employee WHERE did=103);
Output:
The above query displays the details of those department numbers whose minimum
salary is more than the minimum salaried employee who is belonging to the
department number 103.
Usage of joins:
Example:
Query:
SELECT e.* FROM employee e,grade g WHERE did = (SELECT did FROM
employee WHERE name='SANTOSH') AND g.grade='B' AND e.salary BETWEEN
g.losal AND g.hisal;
The above Query displays the details of those employees who belongs to the
department SANTOSH belongs to and are falling in the salary range of grade 'B'.
a. Usage of IN operator
IN → Matches with each and every values returned by the inner query.
Example1:
Query :
The inner query will return the different designated employee details who are
working in the PRODUCTION department. Since the inner query is returning
more than one record, IN operator is used to link between outer and inner
query.Finally the outer query will retrieve all the records whose designations are
matching with the designations of PRODUCTION department.
Example2:
SELECT * FROM employee WHERE salary IN (SELECT MAX(salary) FROM
employee GROUP BY designation);
Output:
The above query displays the records of all the employees who are earning
maximum salary for each designation group.
Example:
SELECT * FROM employee WHERE salary >ANY (SELECT salary FROM
employee WHERE did=102) AND did!=102;
Output:
The above query displays the details of those employees who are earning more
than the minimum salaried employee belonging to department number 102.
Example:
SELECT * FROM employee WHERE salary >ALL (SELECT salary FROM
employee WHERE designation='SENIOR PROGRAMMER');
Output :
<any
</any
The above query displays the details of those employees who are earning more
than the maximum salaried employee, who is a SENIOR PROGRAMMER.
Example2:
SELECT * FROM employee WHERE salary <all
(SELECT salary FROM employee WHERE designation='SENIOR
PROGRAMMER');</all
Output:
The above query displays the details of those employees who are earning less than
the minimum salaried employee, who is a SENIO PROGRAMMER.
Multi column sub queries are the sub queries which returns more than one column
from the Inner SELECT statement.
Example:
SELECT * FROM employee WHERE (did,salary) IN (SELECT did,salary FROM
employee WHERE designation='EXECUTIVE') AND designation!='EXECUTIVE;
The above query displays the details of those employees who belong to the same
department and earning the same salary as of the EXECUTIVE designated
employees.
It is another way of performing queries upon the data with a simulation of joins.
Inthis the information from the Outer SELECT statement participate as a condition
in the Inner SELECT statement.
Syntax:
SELECT select_list FROM table_name alias1 WHERE operator
(SELECT column FROM table_name alias2 WHERE
alias1.column=alias2.column);
Example:
SELECT * FROM employee e1 WHERE salary = (SELECT MIN(salary) FROM
employee e2 WHERE e1.designation=e2.designation);
The above query displays the records of all the employees who are earning
minimum salary for each designation group.
Order of Precedence
First the Outer query is executed.
Passes the executed column value to the Inner queries WHERE clause.
Now the Inner query is executed.
The result of the Inner query is passed to the Outer queries WHERE clause.
Depending on the provided value the condition is qualified for the specific
record.
If successful displays the output.
Example1:
Query:
UPDATE employee SET did=(SELECT did FROM employee WHERE
did='PURCHASE') WHERE did=(SELECT did FROM employee WHERE
did='SALES');
The above queries updates the department numbers of those employees who
are belonging to SALES department to PURCHASE department.
Example2:
DELETE FROM employee WHERE salary > (SELECT AVG(salary) FROM
employee);
The above query deletes all the records from the employee table whose salary is
more than the average salary of all the employees in the organization.
Syntax:
CREATE TABLE table_name2 AS SELECT * FROM table_name1;
Example:
CREATE TABLE employee_bkp AS SELECT name,designation FROM employee
WHERE 1=2;
The above query creates an empty backup table to store only name and
designations.
Syntax:
INSERT INTO table_name2 SELECT * FROM table_name1;
Example:
INSERT INTO employee_bkp SELECT name,designation FROM employee
WHERE did IN (101,103);
Database Objects:
Oracle has the object types or schema already defined. We can create an instances
of them using create command. These instances are objects.
View:
A view is a virtual table created by taking a subset of columns from one or more
tables. A view is a logical table, as view does not contain data itself. The tables
using which we create a view are called base tables. An output of query can be
stored as a view.
Using views, we can hide information and provide security to the database.
Types of Views:
Simple views
Complex views.
Simple views:
Syntax:
Example:
Complex views:
join conditions
group by clause
order by clause
Example:
Department (deptno,dname,location);
- where empno is the primary key and deptno is the foreign key.
To create a view by selecting the empno,ename and job from employee table and
deptno, dname and location from department table.
Read-only views:
Users can only use SELECT and DESCRIBE statements against these views.
Syntax:
Example:
View created WITH CHECK OPTION clause specifies the level of checking to be
done when doing DML against the view. View with check option ensure the
view’s consistency.
Syntax:
Example :
Structure of the employee table is as follows:
Employee (eno,ename,salary,deptno);
We will be able to update deptno value for the records in the view to 10
contradicting the view definition.
We can avoid this type of situations, by creating view with check option.
Force view:
Force view is the view created without having the base table.
Syntax :
Example:
The following view will be created even employee table not exists in our schema.
GROUP BY deptno;
In the above case, the view v_force_view will be created even employee table does
not exist in schema.
Drop View:
Syntax:
Example:
Update View:
We can modify the definition of an Oracle VIEW without dropping it by using the
Oracle CREATE OR REPLACE VIEW Statement.
Syntax :
Sequence:
Syntax:
CREATE SEQUENCE
[ INCREMENT BY
START WITH
MAXVALUE / NOMAXVALUE
MINVALUE / NOMINVALUE
CYCLE / NOCYCLE
CACHE / NOCACHE
ORDER / NOORDER ];
Sequence minimum value(1) is the default value for ascending sequence where for
a descending sequence is the maximum sequence value.
NOCYCLE --Cannot generate more values after reaching the maximum value.
NOCACHE -- Values of a sequence are not pre-allocated and hit the database for
every next value of sequence.
ORDER -- Guarantees that sequence numbers are generate in the order of request
Examples:
MINVALUE 1
MAXVALUE 9999999
START WITH 1
INCREMENT BY 1
CYCLE
CACHE 20;
Using Sequence:
Example:
Using the sequence test_seq created above ,INSERT value in employee table.
Altering Sequence
If we want to start the sequence with new value, we have to drop the old sequence
and have to recreate a new sequence with new start value.
Dropping Sequence:
Example:
Database Objects:
Index:
If we create an index on a column, each value of the column along with row id will
be stored as separate database object.
When we fire a query to fetch the data using this column in where clause, then the
oracle engine will scan the index instead of entire table and will get the other
column values using row id.
Types Of Index:
Index Creation:
Syntax:
Example:
We could also create an index with more than one field as in the example below:
Advantages Of Indexes:
Indexes improve the query performance by avoiding the full table scans.
Indexes are very useful with the tables having large amounts of data.
Disadvantages Of Indexes:
Index is separate database object. For inserting new data or updating data in a
table, the changes needs to be reflected in the table as well as in the index object.
Hence, the cost of DML operations increases.
If we issue one insert statement on base table, oracle fires another insert statement
internally to insert the data into index.
Renaming Index:
Syntax :
Dropping Index:
Syntax:
Note: If the base table is dropped, all the indexes defined on the table will be
dropped.
Synonym:
Synonym is another name for an object like table, view, sequence,
procedure, stored function, package, materialized view etc.
We can simplify access to objects by creating a synonym .
We can provide both data independence and location transparency by
creating Synonym for objects
With synonyms, we can:
Example:
Example: