DBS - Unit 2-1
DBS - Unit 2-1
(22MCA102)
BY
Anantha Murthy
Assistant Professor
Dept. of MCA
NMAM.I.T, Nitte
Unit 2
3
What is RDBMS?
➢
RDBMS stands for Relational Database Management System.
➢
RDBMS is the basis for SQL, and for all modern database systems like MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
➢
A Relational database management system (RDBMS) is a database
management system (DBMS) that is based on the relational model as introduced
by E. F. Codd in 1970.
➢
In RDBMs, the data is represented in the form of tables. i.e. in the form of rows
and columns .
4
How the data is arranged in RDBMS?
➢
The data in an RDBMS is stored in database objects which are called as tables.
This table is basically a collection of related data entries and it consists of
numerous columns and rows.
➢
Every table is broken up into smaller entities called fields.
➢
A record is also called as a row of data is each individual entry that exists in a table.
A record is a horizontal entity in a table.
➢
A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
5
How the data is arranged in RDBMS?
Customer
6
Communicating with a RDBMS Using SQL
7
SQL Statements
8
SQL Statements (Continued)
9
SQL Data Types
10
SQL Data Types (Continued)
➢
A LONG column is not copied when a table is created using a subquery.
➢
A LONG column cannot be included in a GROUP BY or an ORDER BY clause.
➢
Only one LONG column can be used per table.
➢
No constraints can be defined on a LONG column.
11
➢
You may want to use a CLOB column rather than a LONG column.
SQL Data Types (Continued)
➢
The Oracle Server uses constraints to prevent invalid data entry into tables.
➢
Constraints are the rules enforced on data columns on a table.
➢
These are used to limit the type of data that can go into a table.
➢
Enforce rules on the data in a table whenever a row is inserted, updated, or
deleted from that
➢
table. The constraint must be satisfied for the operation to succeed.
➢
Prevent the deletion of a table if there are dependencies from other tables
➢
This ensures the accuracy and reliability of the data in the database.
➢
Constraints can either be column level or table level.
➢
Column level constraints are applied only to one column whereas, table level 13
SQL Constraints
Following are some of the most commonly used constraints available in SQL −
NOT NULL Constraint − Ensures that a column cannot have a NULL value.
DEFAULT Constraint − Provides a default value for a column when none is specified.
UNIQUE Constraint − Ensures that all the values in a column are different.
PRIMARY Key − Uniquely identifies each row/record in a database table.
FOREIGN Key − Uniquely identifies a row/record in any another database table.
CHECK Constraint − The CHECK constraint ensures that all values in a column
satisfy certain conditions.
INDEX − Used to create and retrieve data from the database very quickly.
14
Defining Constraints
Column-level constraint
column [CONSTRAINT constraint_name] constraint_type,
15
Defining Constraints (Continued)
In the syntax:
constraint_name is the name of the constraint
constraint_type is the type of the constraint
16
SQL CREATE Table
The SQL CREATE TABLE statement is used to create a new table. Creating a
basic table involves naming the table and defining its columns and each column's
data type and constraints.
Syntax
CREATE TABLE table_name(
column1 datatype column-level-constraint1,
column2 datatype column-level-constraint2,
column3 datatype column-level-constraint3,
.....
columnN datatype column-level-constraintn,
Table-level-constraint( one or more columns ) 17
SQL CREATE Table (Continued)
18
Naming Rules
Name database tables and columns according to the standard rules for naming any Oracle
database object:
• Table names and column names must begin with a letter and be 1–30 characters
long.
• Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $, and #
(legal characters, but their use is discouraged).
• Names must not duplicate the name of another object owned by the same Oracle
server user.
• Names must not be an Oracle server reserved word.
Note: Use descriptive names for tables and other database objects.
Names are case insensitive. For example, EMPLOYEES is treated as the same name as
eMPloyees or eMpLOYEES. 19
SQL CREATE Table (Continued)
20
SQL DESC command
You can verify if your table has been created successfully by looking at the message
displayed by the SQL server, otherwise you can use the DESC command as follows −
SQL> DESC EMPLOYEE;
+---------+---------------+---------+-------+-----+----------+---------
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+---------+-------+-----+----------+---------
| EmployeeID | NUMBER(5) | NO | PRI | | |
| FirstName | varchar(255) | NO | PRI | | |
| LastName | varchar(255) | NO | | | |
| City varchar | char(255) | YES | | NULL | |
+---------+---------------+--------+--------+------+----------+---------
21
4 rows in set (0.00 sec)
The NOT Null Constraint
22
The UNIQUE Constraint
23
The UNIQUE Constraint (continued)
➢
A UNIQUE key integrity constraint requires that every value in a column or set of columns
(key) be unique—that is, no two rows of a table can have duplicate values in a specified
column or set of columns.
➢
If the UNIQUE constraint comprises more than one column, that group of columns is called a
composite unique key.
➢
UNIQUE constraints allow the input of nulls unless you also define NOT NULL constraints for
the same columns.
➢
In fact, any number of rows can include nulls for columns without NOT NULL constraints
because nulls are not considered equal to anything.
➢
A null in a column (or in all columns of a composite UNIQUE key) always satisfies a UNIQUE
constraint.
24
The UNIQUE Constraint (Continued)
25
The DEFAULT Constraint
The DEFAULT constraint provides a default value to a column when the INSERT
INTO statement does not provide a specific value.
CREATE TABLE CUSTOMERS(
ID number(5) NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE number(5) NOT NULL,
ADDRESS CHAR (25) ,
SALARY number (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID)
);
The above SQL creates a new table called CUSTOMERS and adds five columns.
Here, the SALARY column is set to 5000.00 by default, so in case the INSERT
INTO statement does not provide a value for this column, then by default this
26
column would be set to 5000.00.
The PRIMARY KEY Constraint (Continued)
➢
A PRIMARY KEY constraint creates a primary key for the table. Only one primary
key can be created for each table.
➢
The PRIMARY KEY constraint is a column or set of columns that uniquely
identifies each row in a table.
➢
This constraint enforces uniqueness of the column or column combination and
ensures that no column that is part of the primary key can contain a null value.
➢
PRIMARY KEY constraints can be defined at the column level or table level.
➢
A composite PRIMARY KEY is created by using the table-level definition.
➢
A table can have only one PRIMARY KEY constraint but can have several
UNIQUE constraints.
➢
A UNIQUE index is automatically created for a PRIMARY KEY column. 27
The PRIMARY KEY Constraint
28
The PRIMARY KEY Constraint (Continued)
29
The FOREIGN KEY Constraint
➢
The FOREIGN KEY, or referential integrity constraint, designates a column or
combination of columns as a foreign key and establishes a relationship between a
primary key or a unique key in the same table or a different table.
➢
A foreign key value must match an existing value in the parent table or be NULL.
➢
FOREIGN KEY constraints can be defined at the column or table level.
➢
A composite foreign key must be created by using the table-level definition.
30
The FOREIGN KEY Constraint (Continued)
31
The FOREIGN KEY Constraint (Continued)
32
The FOREIGN KEY Constraint (Continued)
The foreign key can also be defined at the column level, provided the constraint
is based on a single column.
For example:
34
The FOREIGN KEY Constraint Keywords (Continued)
Syntax
The syntax for creating a foreign key with set null on delete using a CREATE TABLE
statement in SQL Server is:
36
The FOREIGN KEY Constraint Keywords (Continued)
38
Viewing Constraints
39
Viewing Constraints (Continued)
Note:
➢
After creating a table, you can confirm its existence by issuing a DESCRIBE
command.
➢
The only constraint that you can verify is the NOT NULL constraint. To view all
constraints on your table, query the USER_CONSTRAINTS table.
➢
Constraints that are not named by the table owner receive the system-assigned
constraint name.
➢
In constraint type, C stands for CHECK, P for PRIMARY KEY, R for referential
integrity, and U for UNIQUE key.
➢
Notice that the NOT NULL constraint is really a CHECK constraint. 40
Viewing the Columns Associated with Constraints
You can view the names of the columns involved in constraints by querying the
USER_CONS_COLUMNS data dictionary view.
This view is especially useful for constraints that use system-assigned names.
41
The ALTER TABLE Statement
After you create a table, you may need to change the table structure because:
you omitted a column or constraint, your column definition needs to be
changed, or you need to remove columns or constraints. You can do this by
using the ALTER TABLE statement.
Note:
●
You cannot specify where the column is to appear. The new column becomes
the last column.
●
If a table already contains rows when a column is added, then the new column
is initially null for all the rows.
44
The ALTER TABLE Statement (Continued)
Modifying a Column
You can change a column’s data type, size, and default value.
Example: ALTER TABLE dept
MODIFY (last_name VARCHAR2(30));
Note:
●
You can increase the width or precision of a numeric column.
●
You can increase the width of numeric or character columns.
●
You can decrease the width of a column only if the column contains only null
values or if the table has no rows.
●
You can change the data type only if the column contains null values.
●
You can convert a CHAR column to the VARCHAR2 data type or convert a
VARCHAR2 column to the CHAR data type only if the column contains null values
or if you do not change the size.
45
The ALTER TABLE Statement (Continued)
Dropping a Column
You can drop a column from a table by using the ALTER TABLE statement with the
DROP COLUMN clause. This is a feature available in Oracle8i and later.
Note:
• The column may or may not contain data.
• Using the ALTER TABLE statement, only one column can be dropped at a time.
• The table must have at least one column remaining in it after it is altered.
• Once a column is dropped, it cannot be recovered.
47
The ALTER TABLE Statement (Continued)
Adding a Constraint
Guidelines
• You can add, drop, enable, or disable a constraint, but you cannot modify its
structure.
• You can add a NOT NULL constraint to an existing column by using the MODIFY
clause of the ALTER TABLE statement.
●
You can define a NOT NULL column only if the table is empty or if the column has
a value for every row.
●
The constraint name in the syntax is optional, although recommended. If you do
not name your constraints, the system will generate constraint names.
48
The ALTER TABLE Statement (Continued)
Examples:
1. Add a FOREIGN KEY constraint to the EMPLOYEES table indicating that a manager
must already exist as a valid employee in the EMPLOYEES table.
2. To add a NOT NULL constraint, use the ALTER TABLE MODIFY syntax:
ALTER TABLE employees
MODIFY (salary CONSTRAINT emp_salary_nn NOT NULL);
49
The ALTER TABLE Statement (Continued)
Dropping a Constraint
To drop a constraint, you can identify the constraint name from the USER_CONSTRAINTS and
USER_CONS_COLUMNS data dictionary views. Then use the ALTER TABLE statement with
the DROP clause. The CASCADE option of the DROP clause causes any dependent
constraints also to be dropped.
Syntax
ALTER TABLE table
DROP PRIMARY KEY | UNIQUE (column) |
CONSTRAINT constraint [CASCADE];
When you drop an integrity constraint, that constraint is no longer enforced by the Oracle
server and is no longer available in the data dictionary. 50
The ALTER TABLE Statement (Continued)
Dropping a Constraint
51
The DROP TABLE Statement
The DROP TABLE statement removes the definition of an Oracle table. When you
drop a table, the database loses all the data in the table and all the indexes
associated with it.
Syntax : DROP TABLE table Example: DROP TABLE dept;
Note :
• All data is deleted from the table.
• Any views and synonyms remain but are invalid.
• Any pending transactions are committed.
• Only the creator of the table or a user with the DROP ANY TABLE privilege can
remove a table.
52
●
The DROP TABLE statement, once executed, is irreversible.
The Data Manipulation Language
➢
Data manipulation language (DML) is a core part of SQL.
➢
When you want to add, update, or delete data in the database, you execute a DML
statement.
➢
Every table has INSERT, UPDATE, and DELETE privileges associated with it.
➢
These privileges are automatically granted to the creator of the table, but in general
they must be explicitly granted to other users.
➢
A collection of DML statements that form a logical unit of work is called a
transaction.
53
The Data Manipulation Language
When Does a Transaction Start and End?
A transaction begins when the first DML statement is encountered and ends when one of the
following occurs:
• A COMMIT or ROLLBACK statement is issued
• A DDL statement, such as CREATE, is issued
• A DCL statement is issued
• The user exits SQL
• A machine fails or the system crashes
After one transaction ends, the next executable SQL statement automatically starts the next
transaction.
A DDL statement or a DCL statement is automatically committed and therefore implicitly ends
a transaction. 54
The INSERT statement (Continued)
55
The INSERT statement (Continued)
Syntax :
Note: This statement with the VALUES clause adds only one row at a time to a table.
➢
Because you can insert a new row that contains values for each column, the
column list is not required in the INSERT clause.
➢
However, if you do not use the column list, the values must be listed according to
the default order of the columns in the table, and a value must be provided for each
column.
56
The INSERT statement (Continued)
Inserting New Rows
➢
You can insert a new row that contains values for each column, the column list is
not required in the INSERT clause.
➢
If you do not use the column list, the values must be listed according to the default
order of the columns in the table, and a value must be provided for each column.
➢
For clarity, use the column list in the INSERT clause.
➢
Enclose character and date values within single quotation marks; it is not
recommended to enclose numeric values within single quotation marks.
➢
Number values should not be enclosed in single quotes, because implicit
conversion may take place for numeric values assigned to NUMBER data type
57
columns if single quotes are included.
The INSERT statement (Continued)
Inserting New Rows
58
The INSERT statement (Continued)
Inserting Rows with Null Values
59
The INSERT statement (Continued)
60
The UPDATE statement
Note:
In general, use the primary key to identify a single row. Using other columns can
unexpectedly cause several rows to be updated. For example, identifying a single row
in the EMPLOYEES table by name is dangerous, because more than one employee
61
may have the same name.
The UPDATE statement (Continued)
62
The DELETE statement
➢
You can remove existing rows by using the DELETE statement.
➢
The DELETE statement does not ask for confirmation. However, the delete
operation is not made permanent until the data transaction is committed.
➢
Therefore, you can undo the operation with the ROLLBACK statement if you make
a mistake.
➢
In the Syntax, condition identifies the rows to be deleted and is composed of
column names, expressions, constants, subqueries, and comparison operators.
63
The DELETE statement (Continued)
64
Data Query Language Statement (DQL)
The SELECT statement
65
The SELECT statement (Continued)
Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.
Example:
67
The SELECT statement with WHERE clause
➢
The SQL WHERE clause is used to specify a condition while fetching the data from
a single table or by joining with multiple tables.
➢
If the given condition is satisfied, then only it returns a specific value from the table.
You should use the WHERE clause to filter the records and fetching only the
necessary records.
➢
The WHERE clause is not only used in the SELECT statement, but it is also used
in the UPDATE, DELETE statement, etc.,
➢
You can specify a condition using the comparison or logical operators like >, <, =,
LIKE, NOT, etc.
68
The SELECT statement with WHERE clause
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >
2000;
70
The SQL Expressions
71
The SQL Expressions
Boolean Expressions
SQL Boolean Expressions fetch the data based on matching a single value.
Syntax −
SELECT column1, column2, columnN FROM table_name
WHERE SINGLE VALUE MATCHING EXPRESSION;
72
The SQL Expressions
Numeric Expression
These expressions are used to perform any mathematical operation in any query.
Syntax
SELECT numerical_expression as OPERATION_NAME
[FROM table_name
WHERE CONDITION] ;
73
The SQL Expressions
Date Expressions
Example:
74
The SQL Logical Operators
75
The SQL Logical Operators
76
The SQL Logical Operators
77
The SQL Logical Operators
78
The SQL Logical Operators
Examples
➢
SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;
➢
SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;
➢
SELECT * FROM CUSTOMERS WHERE AGE IS NOT NULL;
➢
SELECT * FROM CUSTOMERS WHERE NAME LIKE 'Ko%';
➢
SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
➢
SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;
79
The SQL IN Operator
Examples:
➢
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
➢
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
➢
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
80
The SQL IN Operator
➢
The IN operator allows you to specify multiple values in a WHERE clause.
➢
The IN operator is a shorthand for multiple OR conditions.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
81
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign (%) represents zero, one, or multiple characters
The underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern; 82
The SQL LIKE Operator
83
The SQL NOT Operator
84
The Concatenation Operator
A concatenation operator:
Concatenates columns or character strings to other columns
Is represented by two vertical bars (||)
Creates a resultant column that is a character expression
85
The SELECT statement with ORDER BY clause
➢
The order of rows returned in a query result is undefined. The ORDER BY clause
can be used to sort the rows.
➢
If you use the ORDER BY clause, it must be the last clause of the SQL statement.
You can specify an expression, or an alias, or column position as the sort
condition.
➢
If the ORDER BY clause is not used, the sort order is undefined, and the Oracle
server may not fetch rows in the same order for the same query twice.
➢
Use the ORDER BY clause to display the rows in a specific order.
86
The SELECT statement with ORDER BY clause
90
The SELECT statement with ORDER BY clause
Examples:
A concatenation operator:
Concatenates columns or character strings to other columns
Is represented by two vertical bars (||)
Creates a resultant column that is a character expression
92
The SQL GROUP BY Statement
➢
The GROUP BY clause is a SQL command that is used to group rows that have
the same values.
➢
The GROUP BY clause is used in the SELECT statement. Optionally it is used in
conjunction with aggregate functions to produce summary reports from the
database.
➢
The queries that contain the GROUP BY clause are called grouped queries and
only return a single row for every grouped item.
➢
The SELECT statement used in the GROUP BY clause can only be used to contain
column names, aggregate functions, constants and expressions.
➢
SQL Having Clause is used to restrict the results returned by the GROUP BY
93
clause.
The SQL GROUP BY Statement
Syntax
SELECT statements... GROUP BY column_name1[,column_name2,...]
[HAVING condition];
Here
➢
“SELECT statements…” is the standard SQL SELECT command query.
➢
“GROUP BY column_name1” is the clause that performs the grouping based on
column_name1. “[,column_name2,…]” is optional; represents other column names
when the grouping is done on more than one column.
➢
“[HAVING condition]” is optional; it is used to restrict the rows affected by the
GROUP BY clause. It is similar to the WHERE clause.
94
The SQL GROUP BY Statement
Examples:
SELECT gender FROM Members GROUP BY gender ;
95
Aggregate functions in SQL
96
Aggregate functions in SQL
COUNT FUNCTION
➢
COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
➢
COUNT(*) returns the count of all the rows in a specified table. COUNT(*)
considers duplicate and Null.
Syntax
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
97
Aggregate functions in SQL
COUNT FUNCTION Examples
➢
SELECT COUNT(*) FROM PRODUCT_MAST;
➢
SELECT COUNT(*) FROM PRODUCT_MAST WHERE RATE>=20;
➢
SELECT COUNT(DISTINCT COMPANY) FROM PRODUCT_MAST;
➢
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST
GROUP BY COMPANY;
➢
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY
HAVING COUNT(*)>2;
➢
SELECT Pnumber, Pname, COUNT (*) FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno GROUP BY Pnumber, Pname HAVING COUNT (*) > 2;
(For each project on which more than two employees work, retrieve the project number, the
project name, and the number of employees who work on the project.) 98
Aggregate functions in SQL
SUM FUNCTION
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )
99
Aggregate functions in SQL
SUM FUNCTION Examples
➢
SELECT SUM(COST) FROM PRODUCT_MAST;
➢
SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3;
➢
SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3
GROUP BY COMPANY;
➢
SELECT COMPANY, SUM(COST) FROM PRODUCT_MAST
GROUP BY COMPANY HAVING SUM(COST)>=170;
100
Aggregate functions in SQL
AVG FUNCTION
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values.
Syntax
AVG()
or
AVG( [ALL|DISTINCT] expression )
Syntax
MAX()
or
MAX( [ALL|DISTINCT] expression )
Syntax
MIN()
or
MIN( [ALL|DISTINCT] expression )
SELECT employee_id,first_name,salary
FROM employees
WHERE salary > '15000';
104
Aggregate functions in SQL
Explicit Data-Type Conversion :
TO_CHAR Function :
TO_CHAR function is used to typecast a numeric or
date input to character type with a format model
(optional).
SYNTAX :
TO_CHAR(number1, [format], [nls_parameter])
105
Aggregate functions in SQL
Using the TO_CHAR Function with Dates :
SYNTAX :
TO_CHAR(date, ’format_model’)
The format model:
➢
Must be enclosed in single quotation marks and is case sensitive
➢
Can include any valid date format element
➢
Has an fm element to remove padded blanks or suppress leading zeros
➢
Is separated from the date value by a comma
Example:
SELECT employee_id, TO_CHAR(hire_date, ’MM/YY’) Month_Hired
FROM employees WHERE last_name = ’Ram’; 106
Aggregate functions in SQL
Elements of the Date Format Model :
SELECT last_name,
TO_CHAR(hire_date, ’fmDD Month YYYY’)
AS HIREDATE FROM employees;
107
Aggregate functions in SQL
Using the TO_CHAR Function with Numbers :
SYNTAX :
TO_CHAR(number, ’format_model’)
Example:
This modifier specifies the exact matching for the character argument and date
format model of a TO_DATE function.
109
Aggregate functions in SQL
OUTPUT :
LASTNAME HIREDATE
Kumar 24-MAY-99
110
Aggregate functions in SQL
Using TO_NUMBER Function (A string function that converts a string expression to
a value of NUMERIC data type):
111
How to Join Two Tables in SQL
Relational databases are built with multiple tables that refer to each other. Rows from
one table refer to specific rows in another table, which are connected by some ID
column(s).
112
How to Join Two Tables in SQL
Let’s say you need some details from this warehouse database, like the name of the
products, the price and their respective categories.
SELECT
product.product_name,
product.price,
category.category_name
FROM product, category
WHERE
product.category_id =
category.id ;
113
How to Join Two Tables in SQL
Syntax : SELECT * FROM <table1>, <table2> WHERE <condition>
</condition></table2></table1>
Example:
SELECT artist_name, album_name, year_recorded FROM artist, album
WHERE artist.id = album.artist_id;
SQL Join statement is used to combine data or rows from two or more tables based
on a common field between them.
Different types of Joins are as follows:
➢
CARTESIAN JOIN
➢
SELF JOIN
➢
INNER JOIN
➢
LEFT JOIN
➢
RIGHT JOIN OUTER JOINS
➢
FULL JOIN
115
Types of Joins in SQL
CARTESIAN JOIN
➢
The CARTESIAN JOIN is also known as CROSS JOIN.
➢
In a CARTESIAN JOIN there is a join for each row of one table to every row of
another table. This usually happens when the matching column or WHERE
condition is not specified.
➢
In the absence of a WHERE condition the CARTESIAN JOIN will behave like a
CARTESIAN PRODUCT . i.e., the number of rows in the result-set is the product of
the number of rows of the two tables.
➢
In the presence of WHERE condition this JOIN will function like a INNER JOIN.
➢
In General, Cross join is similar to an inner join where the join-condition will always
evaluate to True.
116
Types of Joins in SQL
Consider the following tables
117
Types of Joins in SQL
CARTESIAN JOIN (Syntax and Example)
118
Types of Joins in SQL
SELF JOIN
➢
In SELF JOIN a table is joined to itself.
➢
That is, each row of the table is joined with itself and all other rows depending on
some conditions.
➢
In other words we can say that it is a join between two copies of the same table.
➢
Syntax:
119
Types of Joins in SQL
SELF JOIN Example
120
Types of Joins in SQL
SELF JOIN Example SQL> select * from studentself;
SQL> desc studentself;
Name Null? Type ROLL_NO NAME LEADER
----------------- -------- ----------- ---------- ---------- ----------
ROLL_NO NUMBER(1) 1 ram
NAME VARCHAR2(10) 2 ramesh 1
LEADER NUMBER(3) 3 sujit 1
4 suresh 2
LEADER NAME
---------- ----------
ram ramesh
ram sujit
ramesh suresh 121
Types of Joins in SQL
INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied.
This keyword will create the result-set by combining all rows from both the tables
where the condition satisfies i.e value of the common field will be the same.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.
122
Types of Joins in SQL
Consider the following tables
123
Types of Joins in SQL
INNER JOIN Example:
124
Types of Joins in SQL
LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows
for the table on the right side of the join.
For the rows for which there is no matching row on the right side, the result-set will
contain null.
LEFT JOIN is also known as LEFT OUTER JOIN.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the
same.
125
Types of Joins in SQL
LEFT JOIN Example
126
Types of Joins in SQL
RIGHT JOIN
This join returns all the rows of the table on the right side of the join and matching
rows for the table on the left side of the join.
For the rows for which there is no matching row on the left side, the result-set will
contain null.
RIGHT JOIN is also known as RIGHT OUTER JOIN.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the
same.
127
Types of Joins in SQL
RIGHT JOIN Example
128
Types of Joins in SQL
FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and
RIGHT JOIN.
The result-set will contain all the rows from both tables.
For the rows for which there is no matching, the result-set will contain NULL values.
129
Types of Joins in SQL
FULL JOIN Example
130
Subquery
A Subquery or Inner query or a Nested query is a query within another SQL query
and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
131
Subquery
132
Subquery
133
Creating a Table from an Existing Table
➢
A copy of an existing table can be created using a combination of the CREATE
TABLE statement and the SELECT statement.
➢
The new table has the same column definitions.
➢
All columns or specific columns can be selected.
➢
When you create a new table using the existing table, the new table would be
populated using the existing values in the old table.
Syntax Example
134
Subqueries with the SELECT Statement
Syntax:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
135
Subqueries with the SELECT Statement
SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
136
Subqueries with the INSERT Statement
➢
The INSERT statement uses the data returned from the subquery to insert into
another table.
➢
The selected data in the subquery can be modified with any of the character, date
or number functions.
Syntax:
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE]
137
Subqueries with the INSERT Statement
Example:
➢
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table.
Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table,
you can use the following syntax.
138
Subqueries with the UPDATE Statement
➢
The subquery can be used in conjunction with the UPDATE statement.
➢
Either single or multiple columns in a table can be updated when using a subquery
with the UPDATE statement.
Syntax:
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
139
[ WHERE}) ]
Subqueries with UPDATE Statement
Example:
➢
Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table. The following example updates SALARY by 0.25 times in the
CUSTOMERS table for all the customers whose AGE is greater than or equal to
27.
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
140
Subqueries with the DELETE Statement
Syntax:
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example:
DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
141
WHERE AGE >= 27 );
Using a Subquery in the FROM Clause
142
HAVING clause with subqueries
Find the designation with lowest average salary
143
Multilevel Subquery
Display departments that have minimum salary greater than that of department 1
144
Subquery returning multiple columns
Display details of employees who are having same dno and salary as that of
employee with empno=101
145
Correlated Subqueries
➢
Correlated subqueries are used for
row-by-row processing.
➢
Each subquery is executed once for
every row of the outer query.
➢
A correlated subquery is evaluated
once for each row processed by the
parent statement. The parent
statement can be a SELECT,
UPDATE, or DELETE statement.
146
Correlated Subqueries
You can use a correlated subquery to answer a multipart question whose answer
depends on the value in each row processed by the parent statement.
Note: You can use the ANY and ALL operators in a correlated subquery.
147
Correlated Subqueries
EXAMPLE : Find all the employees who earn more than the average salary in their
department.
148
Correlated Subqueries
EXAMPLE : Display details of those employees who have switched jobs at least
twice.
149
The ANY and ALL operators
➢
The ANY and ALL operators are used with a WHERE or HAVING clause.
➢
The ANY operator returns true if any of the subquery values meet the condition.
SQL ANY compares a value of the first table with all values of the second table and
returns the row if there is a match with any value.
➢
The ALL operator returns true if all of the subquery values meet the condition.
SQL ALL compares a value of the first table with all values of the second table and
returns the row if there is a match with all values.
150
The ANY operator
151
The ANY operator
152
The ANY operator
153
The ANY operator
EXAMPLE :
Find all employees whose salaries are equal to the average salary of their
department, you use the following query:
SELECT first_name, last_name, salary FROM employees WHERE salary = ANY
( SELECT AVG(salary) FROM employees GROUP BY department_id) ORDER BY
first_name, last_name, salary;
Find all employees whose salaries are greater than the average salary in
every department:
SELECT first_name, last_name, salary FROM employees WHERE salary > ANY
(SELECT AVG(salary) FROM employees GROUP BY department_id) ORDER BY
154
salary;
The ALL operator
155
The ANY and ALL operators
156
The Example for ANY
Display the employees whose salary is less than any clerk and who are not clerks
157
The Example for ALL
Display the employees whose salary is greater than the average salaries of all the
departments
158
Nested Subqueries Versus Correlated Subqueries
Nested Subquery Execution
• The inner query executes first and finds a value.
• The outer query executes once, using the value from the inner query.
“With a normal nested subquery, the inner SELECT query runs first and executes once,
returning values to be used by the main query”.
Correlated Subquery Execution
• Get a candidate row (fetched by the outer query).
• Execute the inner query using the value of the candidate row.
• Use the values resulting from the inner query to qualify or disqualify the candidate.
• Repeat until no candidate row remains.
“A correlated subquery, however, executes once for each candidate row considered by the
159
outer query. In other words, the inner query is driven by the outer query”.
Using the EXISTS Operator
➢
The EXISTS operator tests for existence of rows in the results set of the
subquery.
➢
If a subquery row value is found:
–The search does not continue in the inner query
–The condition is flagged TRUE
➢
If a subquery row value is not found:
– The condition is flagged FALSE
– The search continues in the inner query
160
Using the EXISTS Operator
The EXISTS condition in SQL is used to check whether the result of a correlated
nested query is empty (contains no tuples) or not.
The result of EXISTS is a boolean value True or False.
It can be used in a SELECT, UPDATE, INSERT or DELETE statement.
EXISTS Syntax
SELECT column_name(s) FROM table_name
WHERE EXISTS (SELECT column_name(s)
FROM table_name WHERE condition);
161
162
Using the EXISTS Operator (Example)
163
Using the EXISTS Operator (Example)
1. To fetch the first and last name of the customers who placed atleast one
order.
SELECT fname, lname
FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
164
Using the EXISTS Operator (Example)
2. Using NOT with EXISTS
Fetch last and first name of the customers who has not placed any order.
165
Using the EXISTS Operator (Example)
3.Using EXISTS condition with DELETE statement
Delete the record of all the customer from Order Table whose last name is ‘Mehra’.
DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');
UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);
The UNION operator selects only distinct values by default. To allow duplicate values,
168
Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement.
➢
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY
City; (no duplicates)
➢
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER
BY City; (with duplicates)
➢
SELECT City, Country FROM Customers WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers WHERE Country='Germany' ORDER BY
City;
169
INTERSECT Operator
The SQL INTERSECT clause/operator is used to combine two SELECT statements,
but returns rows only from the first SELECT statement that are identical to a row in the
second SELECT statement. This means INTERSECT returns only common rows
returned by the two SELECT statements.
Just as with the UNION operator, the same rules apply when using the INTERSECT
operator.
Syntax:
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
INTERSECT
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] 170
MINUS Operator
The MINUS operator returns all the records in the first SELECT query that are not
returned by the second SELECT query.
Syntax:
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
MINUS
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
171
MINUS Operator Example
172
MINUS Operator Example
The first query SELECT * FROM Employee will be executed first and then the second
query SELECT * from Employee_backup will be executed.
The MINUS operator will return only those records from the first query result that does
not exist in the second query result.
174
Views ( Virtual tables)
➢
A view is a table whose contents are taken or derived from other tables.
➢
A view is a logical table based on a table or another view.
➢
A view contains no data of its own but is like a window through which data from
tables can be viewed or changed.
➢
The tables on which a view is based are called base tables. The view is stored as a
SELECT statement in the data dictionary.
➢
A view also has rows and columns as they are in a real table in the database.
➢
We can create a view by selecting fields from one or more tables present in the
database.
➢
A View can either have all the rows of a table or specific rows based on certain
condition.
➢
Once your view has been created, you can query the data dictionary view called
175
USER_VIEWS to see the name of the view and the view definition.
Simple Views versus Complex Views
There are two classifications for views: simple and complex. The basic difference is
related to the DML (INSERT, UPDATE, and DELETE) operations.
1. A simple view is one that:
➢
Derives data from only one table
➢
Contains no functions or groups of data
➢
Can perform DML operations through the view
177
Uses of a View
➢
Store complex queries –
Views can be used to store complex queries.
➢
Rename Columns –
Views can also be used to rename the columns without affecting the base tables
provided the number of columns in view must match the number of columns specified
in select statement.
➢
Multiple view facility –
Different views can be created on the same table for different users.
178
Creating Views
Symple Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
179
WHERE condition;
Creating Views
180
Guidelines for creating a view
➢
The subquery that defines a view can contain complex SELECT syntax, including
joins, groups, and subqueries.
➢
The subquery that defines the view cannot contain an ORDER BY clause. The
ORDER BY clause is specified when you retrieve data from the view.
➢
If you do not specify a constraint name for a view created with the WITH CHECK
OPTION, the system assigns a default name in the format SYS_Cn.
➢
You can use the OR REPLACE option to change the definition of the view without
dropping and re-creating it or regranting object privileges previously granted on it.
181
Creating Views
Examples:
Creating View from a single table:
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS
FROM StudentDetails WHERE S_ID < 5;
SELECT * FROM DetailsView;
➢
CREATE VIEW sal
AS SELECT employee_id ID_NUMBER, last_name NAME, salary*12
ANN_SALARY
FROM employees WHERE department_id = 50;
➢
CREATE VIEW salv (ID_NUMBER, NAME, ANN_SALARY)
AS SELECT employee_id, last_name, salary*12
FROM employees WHERE department_id = 50;
183
The WITH CHECK OPTION
➢
It is possible to perform referential integrity checks through views. You can also
enforce constraints at the database level. The view can be used to protect data
integrity, but the use is very limited.
➢
The WITH CHECK OPTION clause specifies that INSERTs and UPDATEs
performed through the view cannot create rows which the view cannot select, and
therefore it allows integrity constraints and data validation checks to be enforced on
data being inserted or updated.
➢
If there is an attempt to perform DML operations on rows that the view has not
selected, an error is displayed, with the constraint name if that has been specified.
184
The WITH CHECK OPTION
CREATE OR REPLACE VIEW empvu20 AS SELECT *
FROM employees WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;
ERROR at line 1:
ORA-01402: view WITH CHECK OPTION where-clause violation
Note:
No rows are updated because if the department number were to change to 10, the
view would no longer be able to see that employee. Therefore, with the WITH
CHECK OPTION clause, the view can see only employees in department 20 and
does not allow the department number for those employees to be changed through
185
the view.
Denying DML Operations
You can ensure that no DML operations occur on your view by creating it with the
WITH READ ONLY option.
Example:
CREATE OR REPLACE VIEW empvu(employee_number, employee_name, job_title)
AS SELECT employee_id, last_name, job_id
FROM employees WHERE department_id = 10
WITH READ ONLY;
Any attempts to remove a row from a view with a read-only constraint results in an
error. ORA-01752: cannot delete from view without exactly one key-preserved table
Any attempt to insert a row or modify a row using the view with a read-only constraint
186
results in Oracle server error: 01733: virtual column not allowed here.
Updatable view
All views are not updatable. So, UPDATE command is not applicable to all views. An
updatable view is one which allows performing a UPDATE command on itself without
affecting any other table.
188
Key differences between Table and View
➢
A table is a database object that holds information used in applications and reports.
On the other hand, a view is also a database object utilized as a table and can also
link to other tables.
➢
A table consists of rows and columns to store and organized data in a structured
format, while the view is a result set of SQL statements.
➢
A table is structured with columns and rows, while a view is a virtual table extracted
from a database.
➢
The table is an independent data object while views are usually depending on the
table.
189
Key differences between Table and View
➢
The table is an actual or real table that exists in physical locations. On the other
hand, views are the virtual or logical table that does not exist in any physical
location.
➢
A table allows to performs add, update or delete operations on the stored data. On
the other hand, we cannot perform add, update, or delete operations on any data
from a view. If we want to make any changes in a view, we need to update the data
in the source tables.
➢
We cannot replace the table object directly because it is stored as a physical entry.
In contrast, we can easily use the replace option to recreate the view because it is
a pseudo name to the SQL statement running behind on the database server.
190