KKW Unit 2 Relational Data Model
KKW Unit 2 Relational Data Model
Data Types
A data type defines what type of data we are storing for particular column.
Tables
It consists of columns, and rows.
In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns
(identifiable by name) and horizontal rows, the cell being the unit where a row and column intersect.
A table is a means of displaying data or information in rows and columns.
Rows are also called a record and columns are also known as parameters, fields, or attributes.
The point of intersection between a column and a row is called a cell
Database
A database is a data structure that stores organized information.
Most databases contain multiple tables, which may each include several different fields. T
1. The Information rule: All information in an RDBMS is represented logically in just one way - by values in tables.
2. The Guaranteed Access rule: Each item of data in an RDBMS is guaranteed to be logically accessible by resorting to a
combination of table name, primary key value, and column name.
3. The Systematic Treatment of Null Values rule: Null values (distinct from an empty character string or a string of blank
characters and distinct from zero or any other number) are supported in a fully relational DBMS for representing missing
information and inapplicable information in a systematic way, independent of the data type.
4. The Dynamic Online Catalog Based o n the Relational Model rule: The database description is represented at the logical
level in the same way as ordinary data, so that authorized users can apply the same relational language to its interrogation as
they apply to the regular data.
5. The Data Language rule: A relational system may support several languages and various modes of terminal use. However,
there must be at least one language whose statements are expressible, per some well-defined syntax, as character strings and
whose ability to support all of the following is comprehensible: data definition, view definition, data manipulation, integrity
constraints, and transaction boundaries.
6. The View Updating rule: All views of the data which are theoretically updatable must be updatable in practice by the DBMS.
7. The High-level Insert, Update, and Delete rule: The database must support high level insertion, updation and deletion.
8. The Physical Data Independence rule: Application programs and terminal activities remain logically unimpaired whenever
any changes are made in either storage representations or access methods.
9. The Logical Data Independence rule: Application programs and terminal activities remain logically unimpaired when
information preserving changes of any kind that theoretically permit unimpaired are made to the base tables.
10. The Integrity Constraints rule: Integrity constraints must be definable in the RDBMS sub-language and stored in the system
catalogue and not within individual application programs.
11. The Database Distribution Independence: An RDBMS has distribution independence. Distribution independence implies
that users should not have to be aware of whether a database is distributed.
12. The Non subversion rule: If the database has any means of handling a single record at a time, that low -level language must not
be able to subvert or avoid the integrity rules which are expressed in a higher-level language that handles multiple records at a
time.
Key Concepts:
1. Primary key
– Primary key denotes a candidate key that is chosen by the database designer as the principal means of identifying items
within an entity set.
– The primary key should be chosen such that its attributes are never, or very rarely, changed.
– For example, SSN are guaranteed to never changed.
– To ensure that each record is unique in each table, we can set one field to be a Primary Key field.
– A Primary Key is a field that that will contain no duplicates and no blank values.
2. Foreign key
– A foreign key is a combination of column with a value based on the primary key values from another table.
– A foreign key constraint also known as referential constraint corresponds to a actual values of the primary key in the
another table. Foreign Keys link to data in other tables.
3. Super key
It is a set of one or more attributes that, taken collectively, to identify uniquely an item in the entity set.
For example, SSN is a superkey.
4. Candidate key
Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 2
Data Base Management System 2021
It is a minimal superkey. For example, Last name and Hire date is sufficient to distinguish among members of the customer
entity set. Then { Last name, Hire date } is a candidate key.
Example:
SQL>CREATE TABLE Student (Reg_no varchar2(10), Name char(30), DOB date, Address
varchar2(50));
Notes:
1. Table names and column names must begin with letter
2. Table names and column names can be 1 to 30 characters long
3. Table names must contain only the characters A-Z, a-z, 0-9, underscore _, $ and #
4. Table name must not be a Oracle reserve word
5. Column name should not be duplicate within a table definition
2) ALTER
Syntax :
SQL> ALTER TABLE <table_name> modify column_name data_type(size) ;
E.g.
SQL> ALTER TABLE EMP modify ( EMPID number(10);
In Above Example the Old data type size of Column EMPID number(5) after the ALTER command the
size of EMPID number (10) .
b) ADD
Add Clause of the Alter command are used to add the New column in Existing table . New
column automatically add at the end of Table.
Syntax:
SQL> ALTER TABLE <table name> ADD ( column_name data_type(size) ) ;
E.g.
SQL> ALTER TABLE EMP add ( address varchar2(20) );
3) RENAME
Rename command is used to rename the old table name to new table name
Syntax:
RENAME <OldTableName> TO <NewTableName> ;
Example:
RENAME Student TO stud_info ;
The old name table was Student now new name is the stud_info;
4) TRUNCATE
To Delete the data inside the Table and release the Storage space
Syntax:
SQL> TRUNCATE TABLE <Table_name> ;
Example:
TRUNCATE TABLE Student;
5) DROP
When Existing Object Or Table is Not Required for further use. It’s always better to eliminate it from database
With drop table structure of table is removed permanently
To Delete the existing Object or Table from the Database . The following command is used .
When we drop a table the database loses all the data in the table .
Syntax :
SQL> DROP TABLE<Table_name>;
6) Desc
Provides a decription of the specified table or view.
Syntax:
SQL> Desc <table_name>;
E.g.
SQL> desc emp;
1. INSERT:
The INSERT statement inserts rows into an existing table.
It’s Possible to Write INSERT INTO Statement in TWO forms.
1) To insert the values for all attributes in the order attributes declared in the table :
Syntax :
SQL> INSERT INTO <Table_name> Values (Value1 , Value2 , Value3 ,...,valueN);
Example:
SQL> insert into student values (12109, ‘Nirmal',‘Dey',‘Pune',789123,'c003');
2) To insert a row into a table by specifying all attributes and its value:
Syntax :
SQL> INSERT INTO <Table_name> (Column1,Column2,Column3,............, ColumnN) Values
(Value1,Value2,Value3,........, ValueN) ;
Example:
SQL> insert into student(ENAME, EID, SALARY, ADDRESS) Values(‘Amit’, 01,
4567, ’Nashik’);
3. DELETE
The DELETE statement deletes rows from a table.
syntax:
SQL> DELETE FROM <table_name> [WHERE condition];
Example
SQL> DELETE FROM STUDENT WHERE EnrollmentID= 12100;
If we include the WHERE clause, the statement deletes only rows that satisfy condition.
If we omit the WHERE clause, the statement deletes all rows from the table, but the empty table still exists.
4.SELECT.
The SELECT statement retrieves or extracts information from tables in the database.
Using the SELECT statement, we can choose the rows in a table that we want to returned from a query by specifying
values to match the rows that we want to see (or don't want to see).
We can use select statement to display all the data from table, to display particular data, to view distinct Data, to display
rows that matches particular condition.
Syntax1-
SQL> Select * from <Table Name>;
Example: SQL> Select * from emp;
It will display all the data from emp Table
Syntax2-
SQL> Select * from <Table Name> Where < Condition>;
Example: SELECT * FROM users WHERE name = 'john'
The example above retrieves all rows from the table 'users' where the 'name' column contains
the text 'john'.
Syntax3- Select column Name1, Column Name2 from <Table Name>;
Example: Select eid, ename from emp;
It will display all the eid and ename from emp Table
Syntax4- Select Distinct column Name from <Table Name>;
Example:Select Distinct ename from emp;
It will display all ename from emp Table excuding Duplicate values of Name.
It means duplicate values are displayed only ones.
Select Command is Also Called as DQL Command
1. Grant : A DBA or user can grant access permission on owned database objects to other user or roles using GRANT
command.
Syntax:
SQL> GRANT [privilege list ] ON [object] TO {user |PUBLIC | role} [WITH ADMIN | GRANT
OPTION];
3. Grant all Privileges on Emp table to user Sachin WITH GRANT OPTION
SQL > GRANT ALL ON EMP TO Sachin WITH GRANT OPTION ;
2. REVOKE: This command is used to revoke an existing privilege from a user. It can revoke a system privilege,
object privilege or a role from a user. Only DBA or a user with ADMIN OPTION can revoke system privilege.
Syntax:
SQL> REVOKE [privilege ] ON [object] FROM {USER |PUBLIC | ROLE} ;
Examples:
1. Revoke all Privileges on Emp table FROM user Sachin.
SQL > REVOKE ALL ON EMP FROM Sachin;
3. COMMIT
Commit command is transactional command used to save permanent changes to the Database .
Syntax :
SQL> Commit;
4. SAVEPOINT
Savepoint is point in a Transaction where we can rollback the transaction to certain point without rolling back the
entire transaction .
Syntax:
SQL> SAVEPOINT savepoint_name;
The above command create the savepoint among the Transaction statement .
The ROllBACK is used to undo a group of transaction .
Examples:
If we want to delete the THREE record from EMP table . So we can Create a Savepoint Before each delete , so we can rollback
to each SAVEPOINT at any time to return the appropriate data.
Consider table “EMP “
1 Nitin Nashik
2 Sachin Pune
3 Raj NashiK
4 Pooja Thane
5 minal Nashik
Savepoint created.
1 row deleted.
Savepoint created.
1 row deleted.
Savepoint created.
If we want to undo LAST TWO delete operation . Then we can ROLLBACK to SAVEPOINT upto
Rollback complete.
So only fist record is deletion took place above rollback undo to SP2;
2 Sachin Pune
3 Raj NashiK
4 Pooja Thane
5 minal Nashik
5. ROLLBACK Statement
The rollback command can be used to undo the changes done in current transaction. We can either rollback the entire
transaction or till a particular savepoint transaction can be rolled back.
If savepoint is given then rollback will be done till the savepoint.
Syntax:
SQL> rollback;
OR
SQL> rollback [to < savepoint>];
IF we delete all Record from Database , if we want all record back to the Database then we use ROLLBACK command
. Who rollback all the Transactions. If Savepoint is given then it rollback till the save point.
SQL> delete from emp;
5 rows deleted.
SQL> rollback;
Rollback complete.
SQL> select * from emp;
EMPID ENAME ADDRESS
---------- ---------- ----------
1 nitin nashik
2 sachin pune
3 raj mumbai
4 pooja thane
5 minal dhule
OperatorDescription Example
Checks if the values of two operands are equal or not, if yes then condition
= (a = b) is not true.
becomes true.
Checks if the values of two operands are equal or not, if values are not equal
!= (a != b) is true.
then condition becomes true.
Checks if the values of two operands are equal or not, if values are not equal
<> (a <> b) is true.
then condition becomes true.
Checks if the value of left operand is greater than the value of right operand, if
> (a > b) is not true.
yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand, if
< (a < b) is true.
yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of right
>= (a >= b) is not true.
operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of right
<= (a <= b) is true.
operand, if yes then condition becomes true.
Checks if the value of left operand is not less than the value of right operand,
!< (a !< b) is false.
if yes then condition becomes true.
Checks if the value of left operand is not greater than the value of right
!> (a !> b) is true.
operand, if yes then condition becomes true.
The BETWEEN operator is used to search for values that are within a set of
BETWEEN
values, given the minimum value and the maximum value.
The IN operator is used to compare a value to a list of literal values that have
IN
been specified.
The LIKE operator is used to compare a value to similar values using wildcard
LIKE
operators.
IS NULL The NULL operator is used to compare a value with a NULL value.
Sample Example:
Consider "Customers" table:
CustomerIDCustomerName ContactName City PostalCode
Note: The "%" sign is used to define wildcards (missing letters) both before and after the pattern.
2. The following SQL statement selects all customers with a City ending with the letter "s":
SELECT * FROM Customers WHERE City LIKE '%s';
3. The following SQL statement selects all customers with a Country containing the pattern "and":
SELECT * FROM Customers WHERE Country LIKE '%and%';
Using the NOT keyword allows you to select records that does NOT match the pattern.
The following SQL statement selects all customers with a Country NOT containing the pattern "and":
SELECT * FROM Customers WHERE Country NOT LIKE '%and%';
1) I/O Constraints
a ) Primary Key constraint:
It is use to avoid redundant/duplicate value entry within the row of specified column in table. It restricts null values
too.
Syntax:
SQL> Create Table Table_Name (Column_Name1 Data_Type (Size) Constraint <Constraint_Name> Primary
Key ,Column_Name2 Data_Type (size));
Example:
Sql> Create Table Emp (Id Number (5) Constraint pk1 primary Key , Name char(10));
b) Unique Constraint:
The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY
constraints both provide a guarantee for uniqueness for a column or set of columns.
Syntax:
Create Table Table_Name (Column_Name1 Data_Type, Column_Name2 Data_Type Constraint Constraint_Name
Unique);
Example:
Example:
SQL> Create table dept( dept_name char(10), dept_no number(10), eid number(10), constraint fk1 foreign
key(eid), refernces emp(eid));
a) NULL
-By default, a column can hold NULL values.
- Null means value for particular column is not known, or it is missing
-Syntax- Create table Table_name ( Column_name Datatype(size) , Column_name Datatype(size)NULL);
Example: SQL> create table sample (rno number(10) null ,name varchar2(10));
b) NOT NULL:
- By default all columns in tables allows null values.
-When a NOT NULL constraint is enforced on column or set of columns it will not allow null values
-Syntax: sql> create table <table_name> (column_name data_type(size), column_name data_type(size) not null);
-Example: sql>create table student (roll_no number (5), name varchar2 (20) not null);
c) CHECK:
-The constraint defines a condition that each row must satisfy. A single column can have multiple check
condition.
- Syntax:-SQL> create table <table_name> (column_name1 data_type(size),..., column_name n data_type(size)constraint
constraint_name check <condition>);
- Example:
SQL> create table emp (id number(5), name varchar2(10), sal number(10) constraint chk_sal check (sal>15000));
2.9 Normalization
If a database design is not perfect, it may contain anomalies, which are like a bad dream for any database administrator.
Managing a database with anomalies is next to impossible.
Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange
situations. For example, when we try to update one data item having its copies scattered over several places, a few
instances get updated properly while a few others are left with old values. Such instances leave the database in an
inconsistent state.
Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is
also saved somewhere else.
Insert anomalies − We tried to insert data in a record that does not exist at all.
Normalization is a method to remove all these anomalies and bring the database to a consistent state
Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.
Consider Student_Project relation that the prime key attributes are Stu_ID and Proj_ID.
According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and not on any
of the prime key attribute individually.
But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently.
This is called partial dependency, which is not allowed in Second Normal Form.
We broke the relation in two as depicted in the above picture. So there exists no partial dependency.
Now the relation is in 1NF And there is no partial dependencies so we can say above relations are in 2NF.
We find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute.
We find that City can be identified by Stu_ID as well as Zip itself.
Neither Zip is a superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists
transitive dependency
To bring this relation into third normal form, we break the relation into two relations as follows