2. What is RDBMS????
• A RELATIONAL DATABASE MANAGEMENT SYSTEM
(RDBMS) that is based on the relational model.
• RDBMS stores data in the form of related tables.
• RDBMS are powerful because they require few
assumptions about how data is related or how it
will be extracted from the database.
• Today, popular commercial RDBMS for large
database include Oracle, Microsoft SQL Server,
Sybase SQL server, and IBM’s DB2.
3. Dr. E.F. CODD’S 12 RULES
• The relational data model was first developed by
Dr. E.F. Codd, an IBM researcher, in 1970.
• In 1985, Dr. Codd published a list of 12 rules that
concisely defined an ideal relational database.
• These rules have been used as a guideline for the
design of all relational database systems since
then.
• For any DBMS to be a RDBMS it is necessary to
satisfy more than 7 to 8 rules of Dr. E.F codd.
4. • RULE 1: THE INFORMATION RULE
– All data should be presented to the user in table form.
• RULE 2: GUARANTEED ACCESS RULE
– All data should be accessible without ambiguity. This
can be accomplished through a combination of the
table name, primary key, and column name.
• RULE 3: SYSTEMATIC TREATMENT OF NULL
VALUES
– A field should be allowed to remain empty. This
involves the support of a null value which is distinct
from a number with a value of zero. Of course, this
can't apply to primary keys. Also, most database
implementations support the concept of a not-null
field constraint that prevents null values in a specific
table column.
5. • RULE 4: DYNAMIC ON-LINE CATALOG BASED ON THE RELATIONAL MODEL
– A relational database must provide access to its structure through the
same tools that are used to access the data. This is usually
accomplished by storing the structure definition within special system
tables.
• RULE 5: COMPREHENSIVE DATA SUBLANGUAGE RULE
– The database must support at least one clearly defined language that
includes functionality for data definition, data manipulation, data
integrity, and database transaction control. All commercial relational
databases use forms of the standard SQL (Structured Query Language)
as their supported comprehensive language.
• RULE 6: VIEW UPDATING RULE
– Data can be presented to the user in different logical combinations,
called views. Each view should support the same full range of data
manipulation that direct access to a table has available. In practice,
providing update and delete access to logical views is difficult and is
not fully supported by any current database.
6. • RULE 7: HIGH-LEVEL INSERT, UPDATE, AND DELETE
– Data can be retrieved from a relational database in sets
constructed of data from multiple rows and/or multiple tables.
This rule states that insert, update, and delete operations
should be supported for any retrievable set rather than just for a
single row in a single table.
• RULE 8: PHYSICAL DATA INDEPENDENCE
– The user is isolated from the physical method of storing and
retrieving information from the database. Changes can be made
to the underlying architecture (hardware, disk storage methods)
without affecting how the user accesses it.
• RULE 9: LOGICAL DATA INDEPENDENCE
– How a user views data should not change when the logical
structure (tables structure) of the database changes. This rule is
particularly difficult to satisfy. Most databases rely on strong ties
between the user view of the data and the actual structure of
the underlying tables.
7. • RULE 10: INTEGRITY INDEPENDENCE
– The database language (like SQL) should support constraints on
user input that maintain database integrity. This rule is not fully
implemented by most major vendors. At a minimum, all
databases do Preserve two constraints through SQL.
– No component of a primary key can have a null value. (see rule
3)
– If a foreign key is defined in one table, any value in it must exist
as a primary key in another table.
• RULE 11: DISTRIBUTION INDEPENDENCE
– A user should be totally unaware of whether or not the
database is distributed (whether parts of the database exist in
multiple locations).
• RULE 12: NONSUBVERSION RULE
– There should be no way to modify the database structure other
than through the multiple row database language (like SQL).
Most databases today support administrative tools that allow
some direct manipulation of the data structure.
8. DBMS V/S RDBMS
DBMS RDBMS
In DBMS relationship between two tables
or files are maintained programmatically
In RDBMS relationship between two
tables or files can be specified at the time
of tables creation
DBMS does not support Client/Server
Architecture
Most of the RDBMS does supports
Client/Server Architecture
DBMS does not support Distributed
database.
Most of the RDBMS support Distributed
databases.
In DBMS there is limited security of data In RDBMS there are multiple levels of
security.
1. Logging in at OS level
2. Command level (i.e at RDBMS level)
3. Object level
Each table is given an extension in DBMS Many tables are grouped in one database
in RDBMS.
DBMS may satisfy less than 7 to 8 rules of
Dr. E.F codd
RDBMS usually satisfy more than 7 to 8
rules of Dr. E.F codd
9. SQL
• SQL (Structured Query Language) is a
language that provides an interface to
relational database systems.
• SQL was developed by IBM in the 1970s.
• SQL enable users to
– Create database and table structure (Data
definition)
– Perform various types of data manipulation
– Query the database to extract useful information
10. Features of SQL
1. Sql can be used by a range of users, including
those with little or no programming
experience.
2. It is a non- procedural language.
3. It reduces the amount of time required for
creating and maintaining systems.
4. It is a English like language.
11. SQL Delimiters: Delimiters are symbols or
compound symbols, which have a special meaning
within SQL and PL/SQL statements.
+ Addition
- Subtraction
* Multiplication
/ Division
=> < Relational
() Expression
; Terminator
, Item separator
. Component selector
/* */ Comment (Multi line)
12. Rules for SQL
1. SQL starts with a verb (i.e a SQL action word). Example: SELECT
statements. This verb may have additional adjectives. Example: FROM
2. Each verb is followed by number of clauses. Example : FROM, WHERE,
HAVING.
3. A space separates clauses. DROP TABLE EMP;
4. A comma (,) separates parameters without a clause
5. A ‘;’ is used to end SQL statements.
6. Statements may be split across lines but keywords may not.
7. Reserved words cannot be used as identifiers unless enclosed with
double quotes.
8. Identifiers can contain up to 30 characters and must start with an
alphabetic character.
9. Characters and data literals must be enclosed within single quotes.
10. Numeric literals can be represented by simple values such as 0.32, -34,
01991, and so on.
13. Components of SQL
1. Data Definition Language commands (DDL)
2. Data Manipulation Language commands
(DML)
3. Data Control Language commands (DCL)
14. 1. (Data Definition Language)- DDL
Commands
Objective:- To provides command for defining relation
schemas, deleting relations and modifying relation schema.
• The SQL DDL allows specification of not only a set of relations
but also information about each relation, including-
– Schema for each relation
– The domain of values associated with each attribute.
– The integrity constraints.
– The set of indices to be maintained for each relation.
– The security and authorization information for each relation.
– The physical storage structure of each relation on disk.
• Data Definition Language commands allow you to perform
these tasks:
– CREATE
– ALTER
– DROP OBJECTS
16. ALTER command
• 1. ALTER with ADD : Add new column(field/attribute)
in already created table (relation).
Syntax: Alter Table tablename ADD(columnname
datatype(size))
• 2. ALTER with MODIFY : Modify the data type, data
width of attribute/field/column of already created
relation/table/schema
Syntax: Alter Table tablename MODIFY(columnname
datatype(size));
• 3. ALTER with DROP : Drop or delete the attribute
/field/column from the existing
relation/table/schema
Syntax: Alter Table tablename DROP(columnname
datatype(size));
17. DROP Command
• DROP TABLE:
• Drop command is used to delete the
relation/table/schema from the system
Syntax: Drop table table_name;
18. DML Commands
• Objective:- To Manipulate the Operations on the
table or modify the attribute values of the
relation/table/schema.
• DML commands deal with data, either retrieving
it or modifying it to keep it up-to-date.
• DML ( Data Manipulation Language) Data
manipulation is the retrieval of information
stored in the database.
• The insertion of new information into the
database.
• The deletion of information from the database.
19. • Data Manipulation Language commands
allow you to perform these tasks:
– INSERT
– SELECT
– DELETE
– UPDATE
20. INSERT ROW
INSERT — adds new rows to a table. INSERT is used to populate a
newly created table or to add a new row (or rows) to an
already-existing table.
1. Insert single data or values (single row) into table
Syntax:
INSERT INTO tablename(columnname, columnname,
………) Values(expression, expression);
2. Inserting more then one row data into a table :
Syntax:
INSERT INTO tablename VALUES(‘&columnname’,
‘&columnname’, ‘&columnname’ ………)
21. 3. Inserting data into a table from another table:
Syntax:
INSERT INTO table_name2 SELECT column_name1,
column_name2, ……. FROM table_name1;
4. Insertion of selected data into a table from
another table:
Syntax:
INSERT INTO tablename SELECT columnname,
columnname…….. FROM tablename WHERE
columnname= expression;
22. SELECT ROW
SELECT — used to query and display data from a database. The SELECT
statement specifies which columns to include in the result set. The vast
majority of the SQL commands used in applications are SELECT
statements
• SELECT : Retrieving of data from the tables
1. Retrieve all data/values from the table
Syntax- SELECT * FROM table_name;
2. The retrieving of specific columns from a table-
Syntax- SELECT column_name, column_name, ….FROM tablename;
3. Elimination of duplicates from the select statement-
Syntax- SELECT DISTINCT columnname, columnname FROM tablename;
4. Selecting a data set from table data-
Syntax- SELECT columnname, columnname FROM tablename
WHERE searchcondition;
23. UPDATE ROW:
• UPDATE — changes an existing value in a column
or group of columns in a table
1. Update all Rows:
Syntax :
UPDATE tablename SET columnname1=
expression1, columnname2= expression2;
2. Updating Records Conditionally
Syntax :
UPDATE tablename SET columnname= expression
WHERE condition;
24. DELETE ROW:
DELETE --- A delete requisitions is expressed in much the
same way as Questioner. We can delete whole tuple (
rows) we can delete values on only particulars
attributes0
Removal of Rows
• Syntax:
DELETE FROM tablename;
Removal of specific Row(s)
• Syntax:
DELETE FROM tablename WHERE condition
25. Built-in Functions in SQL
• A function is similar to an operator in that it
manipulates data items and returns a result.
• Functions differ from operators in the format in which
they appear with their arguments.
• If you call a function with an argument of a data type
other than the data type expected by the function,
ORACLE implicitly converts the argument to the
expected data type before performing the function.
• If you call a function with a null argument, the function
automatically returns null.
• The only functions that do not follow this rule are
CONCAT, REPLACE, DUMP and NVL.
26. Types of functions
1. single row (or scalar) functions
2. group functions (or aggregate) functions
27. • These functions differ in the number of rows
upon which they act.
• A single row function returns a single result
row for every row of a queried table or view,
while a group function returns a single result
row for a group of queried rows.
28. Single Row Functions
1. Numeric Functions
– ABS: returns the absolute value of data (i.e positive
value)
Syntax- ABS(n)
SQL> select ABS(-5000) from account;
– POWER (data,y): returns the data raised to the power
of ‘y’.
Syntax- POWER(n,m)
SQL>select POWER(2,4) from dual;
Ans= 16
29. • Mod(data,y): returns the modulus of dividing
by y.
– SQL> select mod(101,2) from dual;
– Ans= (1)
• Round(data,n) : where n is the number of
decimal places to which the data is rounded
30. 2. CONVERSION FUNCTION
– TO_CHAR: The to_char function can be used to
convert a date or number to a character string
– To convert date: with to_char function, a date can
be formatted in many ways. The format must be
enclosed within single quotes. Consider, 23-AUG-
2016 as the sysdate, then
SELECT TO_CHAR(SYSDATE, ‘MONTH’) FROM DUAL;
– Will return AUGUST.
32. Date functions
• Add_months(date, count) adds count months
to date
• Last_day(date) gives last date of the last day
of the month
• Months_between(date2, date1) gives date2 –
date1 in months( can be fractional)
• Next_day(date, ‘day’): gives date of the next
day after specified date.
33. INTEGRITY CONSTRAINTS
• The primary job of a constraint is to enforce a rule in
the database. Together, the constraints in a database
maintain the integrity of the database. Maintaining
integrity is of utmost importance for a database, so
much so that we cannot trust users and applications to
enforce these rules by themselves.
• Data integrity rules fall into one of three categories:
– Entity
– Referential, and
– Domain.
34. Entity Integrity
• Entity integrity ensures each row in a table is a
uniquely identifiable entity.
• We can apply entity integrity to a table by specifying a
PRIMARY KEY constraint. For example, the ProductID
column of the Products table is a primary key for the
table.
Syntax with Example
CREATE TABLE Products_2
(
ProductID number(10) PRIMARY KEY,
ProductName varchar2 (40)
);
35. Referential Integrity
• Referential integrity ensures the relationships between
tables remain preserved as data is inserted, deleted,
and modified.
• You can apply referential integrity using a FOREIGN KEY
constraint. The ProductID column of the Order Details
table has a foreign key constraint applied referencing
the Orders table.
• The constraint prevents an Order Detail record from
using a ProductID that does not exist in the database.
Also, you cannot remove a row from the Products table
if an order detail references the ProductID of the row.
37. Domain integrity
• Domain integrity ensures the data values
inside a database follow defined rules for
values, range, and format.
• A database can enforce these rules using a
variety of techniques, including
– CHECK constraints,
– UNIQUE constraints
38. Sampling of domain integrity
constraints
• A product name cannot be NULL.
• A product name must be unique.
• The date of an order must not be in the
future.
• The product quantity in an order must be
greater than zero.
39. NULL Constraints
• Although not a constraint in the strictest definition, the decision to allow
NULL values in a column or not is a type of rule enforcement for domain
integrity.
• Using SQL you can use NULL or NOT NULL on a column definition to
explicitly set the null ability of a column.
• In the following example table, the FirstName column will accept NULL
values while LastName always requires a non NULL value.
• Primary key columns require a NOT NULL setting, and default to this
setting if not specified.
• Syntax with Example
• CREATE TABLE Employees_2
• (
• EmployeeID number(5) PRIMARY KEY,
• FirstName varchar(50) NULL
• LastName varchar(50) NOT NULL
• )
40. Unique Constraints
• A unique constraint uses an index to ensure a column (or set of columns)
contains no duplicate values.
• By creating a unique constraint, instead of just a unique index, you are
telling the database you really want to enforce a rule, and are not just
providing an index for query optimization. The database will not allow
someone to drop the index without first dropping the constraint.
• From a SQL point of view, there are three methods available to add a
unique constraint to a table. The first method is to create the constraint
inside of CREATE TABLE as a column constraint. A column constraint
applies to only a single column. The following SQL will create a unique
constraint on a new table: Products_2.
Syntax with Example
CREATE TABLE Products_2
(
ProductID int PRIMARY KEY,
ProductName nvarchar (40) Constraint IX_ProductName UNIQUE
)
41. • A different syntax allows you to create a table
constraint.
• Unlike a column constraint, a table constraint is
able to enforce a rule across multiple columns.
• A table constraint is a separate element in the
CREATE TABLE command.
Syntax with Example
CREATE TABLE Products_2
(
ProductID int PRIMARY KEY,
ProductName nvarchar (40),
CONSTRAINT IX_ProductName
UNIQUE(ProductName)
)
42. • The final way to create a constraint via SQL is to add a
constraint to an existing table using the ALTER TABLE
command, as shown in the following command:
Syntax with Example
CREATE TABLE Products_2
(
ProductID int PRIMARY KEY,
ProductName nvarchar (40)
)
ALTER TABLE Products_2
ADD CONSTRAINT IX_ProductName UNIQUE
(ProductName)
• If duplicate data values exist in the table when the ALTER
TABLE command runs, you can expect an error message
43. Check Constraints
• Check constraints contain an expression the database
will evaluate when you modify or insert a row.
• If the expression evaluates to false, the database will
not save the row.
• Building a check constraint is similar to building a
WHERE clause.
• We can use many of the same operators (>, <, <=, >=,
<>, =) in additional to BETWEEN, IN, LIKE, and NULL.
• We can also build expressions around AND and OR
operators.
44. Check constraint
• We can place the constraint after the column
definition, as shown below. Note the
constraint name is optional for unique and
check constraints.
Syntax
Columnname datatype(size) CHECK (logical expression)
45. Example: create table client_master with the following check
constraints:
• Data values being inserted into column client number must start
with the capital letter ‘C’.
• Data values being inserted into column name should be in upper
case only.
• Only allow “Bombay”, “Delhi”, “Madras” and “Calcutta” as
legitimate values for the column city.
CREATE TABLE client_master
( client_no varchar2(6) CHECK (client_no like ‘C%’),
name varchar2(20) CHECK(name=upper(name)),
city varchar2(20) CHECK(city IN (‘Bombay’, ‘Delhi’, ‘Madras’,
‘Calcutta’)),
state varchar2(20), pincode number(6), remarks varchar2(60),
bal_due number(10,2)
);
46. SQL JOINS
Joining Multiple Tables (Equi Joins)
• Sometimes we require to treat multiple tables
as though they were a single entity.
• Then a single SQL sentence can manipulate
data from all the tables.
• To achieve this, we have to join tables.
• Tables are joined on columns that have the
same data type and data width in the tables.
47. Ex: retrieve the order numbers, client names, and their
order dates from the client_master and sales_order
tables. The order dates should be displayed in
‘DD/MM/YYYY’ and sorted in ascending order
Order no Client
no
Order date
O19001 C00006 12-APR-2015
O19002 C00002 25-DEC-2015
O19003 C00001 03-OCT-2014
O19004 C00005 18-JUNE-
2015
O19005 C00004 20-AUG-
2014
O19006 C00001 12-JAN-2015
Client no Name Bal due
C00001 ASHOK 500
C00002 RAM 1000
C00003 NARESH 0
C00004 MAHESH 0
C00005 ROHIT 0
C00006 RAVI 0
C00007 MOHAN 0
SALES_ORDER
CLIENT_MASTER
48. Order no Name Order date
O19005 MAHESH 20-AUG-2014
O19003 ASHOK 03-OCT-2014
O19006 ASHOK 12-JAN-2015
O19001 RAVI 12-APR-2015
O19004 ROHIT 18-JUNE-2015
O19002 RAM 25-DEC-2015
49. • SELECT order_no, name,
to_char(order_date,’dd/mm/yyyy’) “Order Date”
FROM sales_order, client_master
WHERE
client_master.client_no=sales_order.client_no
ORDER BY to_char(order_date,’dd/mm/yyyy’);
50. 2. Retrieve the product numbers, their
description, and the total quantity ordered for
each product
• Sales_order_details(Detorder_No,
Product_No, Qty_ordered)
• Product_master(Product_no, description)
52. Product No Description Total Qty ordered
P00001 1.44 floppies 16
P00002 Monitors 4
P00003 Mouse 2
P00004 1.22 floppies 4
P00005 Keyboards 10
P00006 CD drive 19
OUTPUT
SELECT sales_order_details.product_no, description,
sum(qty_ordered) “Total qty Ordered”
FROM sales_order_details, product_master
WHERE product_master.product_no=sales_order_details.product_no
GROUP BY sales_order_details.product_no, description;
53. Joining A Table to Itself (Self Join)
• In some situations it is necessary to join a
table to itself, as we were joining two separate
tables.
• This is referred as a self join.
• In a self join, two rows from the same table
combine to form a resultant row.
• Using the table alias names these two
identical tables can be joined.
54. Retrieve the names of the employees and the
names of their respective managers from the
table employee.
55. SQL JOINS
• Join means to access rows from two or more tables.
• A join operation involves two tables and the tables must be
joined with a where clause in which the common key field
must be specified.
• TYPES OF JOINS
– INNER JOIN
– OUTER JOIN
56. INNER JOIN
• When matching records only are displayed from both the tables, it is
called INNER JOIN or Equi join.
Relation instructor1
Relation teaches1
ID course_id
10101
12121
76766
CS-101
FIN-201
BIO-101
Comp. Sci.
Finance
Music
ID dept_name
10101
12121
15151
Name
Srinivasan
Wu
Mozart
57. Select id,name,dept_name,course_id from instructor, teaches
where instructor.id = teaches.id
ID dept_name
10101
12121
Comp. Sci.
Finance
course_id
CS-101
FIN-201
name
Srinivasan
Wu
58. Outer join
• If matching records are not present in the second
file, certain names from the first file are not listed at
all.
• To retrieve these records also we have to perform an
outer join operation using the outer join operator(+).
• The data, which is not available in the second file,
will be presented as null values
Select id,name,dept_name,course_id from
instructor, teaches where instructor.id =
teaches.id (+)
59. Set operators
UNION
- All distinct rows selected by either query.
SQL> Select empid from employee UNION select empid
from transaction;
UNION ALL
- All rows selected by either query, including all
duplicates.
- SQL> Select empid from employee UNION ALL select
empid from transaction;
INTERSECT
- All distinct rows selected by both queries.
- SQL> Select empid from employee INTERSECT select
empid from transaction;
MINUS
- All distinct rows selected by the first query but
not the second.
- SQL> Select empid from employee MINUS select
empid from transaction;
60. LOCKS
• Locks are mechanism used to ensure data integrity
while allowing maximum concurrent access to data.
• The oracle engine automatically locks table data
while executing SQL statements. This type of locking
is known as implicit locking
63. Shared locks
• Shared locks are placed on resources
whenever a READ operation(select) is
performed.
• Multiple shared locks can be simultaneously
set on a resource.
64. RULES OF LOCKING
• Data being changed can not be read
• Writers wait for other writers, if they attempt
to update the same rows at the same time
65. Exclusive locks
• These locks are placed on a resource
whenever a write operation is performed.
• Only one exclusive lock can be placed on a
resource at a time.
66. • SQL> Select * from employee for update;
• SQL> Lock table employee in exclusive
mode
• SQL> Lock table employee in exclusive
mode nowait;