Introduction To DBMS and RDBMS: Data
Introduction To DBMS and RDBMS: Data
Introduction
Data:
Database:
Architecture of a DBMS
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.
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 .
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.
A file system is a method of storing and organizing computer files and the data
they contain and to make it easy to find and access them.
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:
Network DBMS:
In a Network DBMS the relationships among data in the database are of
type many-to-many and appears in the form of a network.
The structure of a network database is extremely complicated because of
these many-to-many relationships in which one record can be used as a key
of the entire database.
Schema:
For example the design of the tables for an entire application or project.
Schema is of two types:
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:
Foreign key:
A foreign key is the field in a table that generally references values from
primary key field of other table
Oracle Connectivity
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.
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.
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 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
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.
Multivalued attribute
An attribute with a set of possible values for the same entity. (Eg. Phone no - can
have mobile no , land number).A multivalued attribute is graphically represented
by double ellipse.
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 “One bank deals with many customers”.
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
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
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
Cours
Cours eNam
eCode e
Comp
C2009 uting
Comp
C2009 uting
Busine
ss and
Comp
B2009 uting
How to Decompose
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
Example
The nontrivial functional dependencies in the table , which are violating BCNF are
Writer Location
W1 Hyderabad
W2 Banglore
Writer Location
W3 Chennai
TITLE1 200
TITLE2 100
TITLE3 300
W1 TITLE1
W2 TITLE2
W3 TITLE3
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.
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.
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;
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:
UPDATE Table_name SET Column_name1=value1
[,Column_name2=value2,...]
[WHERE Condition];
DELETE statement
Syntax:
Note: Delete statement without where condition deletes all the rows from
table.
Example
A Transaction begins when the first executable sql statement is encountered. The
Transaction terminates when the following specifications occur.
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 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).
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
If a single column does not qualify for a PRIMARY KEY, we can define a
primary key by combining more than one columns.This is called
COMPOSITE PRIMARY KEY.
Restrictions
A table can have only one PRIMARY KEY.
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.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size), col2 DATATYPE(size), ........,
CONSTRAINT cons_name PRIMARY KEY(col1,col2));
Example:
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:
Syntax:
Foreign Key
A FOREIGN KEY means establishing the relationship between parent and
child tables. (parent – PRIMARY / UNIQUE defined table , child –
FOREIGN KEY defined table)
The PRIMARY KEY and FOREIGN KEY can exist in the same table.
Restrictions
It preserves the defined relationship between the tables when the records are
inserted or deleted.
A FOREIGN KEY constraint can be defined on a table with the help of a CREATE
statement immediately after the column definition with the help of REFERENCES
keyword to refer the parent table.
Syntax :
CREATE TABLE table_name (col_name1 DATATYPE(size) CONSTRAINT
cons_name REFERENCES parent_table_name(col1), col5 DATATYPE(size),
col6 DATATYPE(size) , ........);
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.
Syntax :
We can use ALTER statement to add a Foreign Key to an already created table.
Syntax:
We can remove the foreign key of a table by using the ALTER table and Drop
Constraint command.
Syntax:
ALTER TABLE table_name DROP CONSTRAINT cons_name;
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:
The above example specifies that if at all the records available in the warehouse
table are deleted, then automatically the respective records in the production
table (warehouse_id , warehouse_name) ( which are referring the values of the
composite key warehouse(id,name) of the deleted record from warehouse ) will be
set to null.
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:
NOT NULL is an in-line constraint, which specify that a column cannot
contain null values.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name
NOT NULL,col2 DATATYPE(size) CONSTRAINT cons_name NOT NULL,
col3 DATATYPE(size) , ........);
Example:
CREATE TABLE student (sid NUMBER(4) CONSTRAINT sid_pk
PRIMARYKEY, sname VARCHAR2(30) CONSTRAINT name_nn NOT
NULL,dob DATE CONSTRAINT dob_nn NOT NULL,gender CHAR(1)
CONSTRAINT gndr-chk CHECK (gender ='M' OR gender='F'));
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:
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:
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:
A UNIQUE KEY constraint allows to maintain uniqueness of a table
column values, depending on the column the constraint is applied.
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:
CREATE TABLE supplier ( supp_id NUMBER(4) CONSTRAINT supid_unq
UNIQUE, name VARCHAR2(20), contact_number NUMBER(15));
The above example specifies that every supplier must have a unique value to
identify the supplier.
Syntax :
Example:
The above example specifies that every supplier must have a unique value to
identify the supplier.
Syntax :
Example:
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
CHECK constraint is used to limit the value range that can be placed in a
column.
Restrictions
The CHECK constraint can refer any column of the current table , but
cannot refer any column of another table.
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 :
CREATE TABLE table1 (col1 DATATYPE(size),col2 DATATYPE(size), ........,
CONSTRAINT cons_name CHECK (condition),CONSTRAINT cons_name
CHECK (condition));
Example:
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.
Introduction 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 .
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:
SELECT SQRT(64) As “Square Root” FROM dual;
Output:
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.
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).
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:
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.
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.
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;
Other Oracle Date Functions:
1.months_between()
2.add_months()
3.last_day()
4.next_day()
Conversion Functions:
NVL
NVL2
NULLIF
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)
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
CROSS JOIN
INNER JOIN
EQUI JOIN
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:
The above query returns 35 records. Each row of of Employee table is linked with
each and every row of Department table . So the 101 (Emp Id) record from
Employee table appears 5 times ie once for each record of the Department table. So
101 is appearing in 5 rows in the resultant record set, as below – Some records
from result set
2.Inner Join:
An inner is used when the join fields are guaranteed not to be NULL.
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.
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
The above query displays all the records, which fulfill the join
condition along with the rows from both employee and department tables which do
not fulfill the join condition.
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
SELECT
A.EMP_ID,A.EMP_NAME,A.EMP_SAL,A.EMP_LOC,A.EMP_MGR_ID,B.Emp_N
ame Manager_Name from Employee A,Employee B where
A.EMP_MGR_ID=B.EMP_ID;
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
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 :
SELECT * FROM employee WHERE designation IN (SELECT designation from
employee e,department d WHERE e.did=d.did AND
d.deptname='PRODUCTION');
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.
c. Usage of ALL operator
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
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:
In a relational database, a database object is a data structure used to either store or
reference data. Table and constraints are the most common object used .Other
objects are views, indexes, sequences, synonyms, stored procedures and functions,
triggers and many others are there.
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:
Example:
Complex views:
join conditions
group by clause
order by clause
Example:
Department (deptno,dname,location);
Employee (empno,ename,job,deptno);
- 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 :
Employee (eno,ename,salary,deptno);
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:
DROP view emp_view;
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.
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:
CREATE SEQUENCE customers_seq
MINVALUE 1
MAXVALUE 9999999
START WITH 1
INCREMENT BY 1
CYCLE
CACHE 20;
Using Sequence:
Referencing a Sequence in Select statement
Example:
Here, the first reference to test_seq.nextval returns 1. The second reference returns
2 . Each subsequent references will return a value 1 greater than the previous
reference.
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:
DROP SEQUENCE sequence_name;
Example:
Database Objects:
Index:
An Index is a database object. We create index to optimize the query performance
and to get the sql results in lesser time.
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:
In this example, we have created an index on the products table called
products_idx. It consists of only one field - the product_name field.
We could also create an index with more than one field as in the example below:
Syntax To create Bitmap index :
If we need to create an index on a column having less number of distinct values,
then we should create bitmap index.
Syntax To create function-based index :
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: