CH-2 Relational Data Model
CH-2 Relational Data Model
Key Concepts
Q. Describe primary key and candidate key. (2M)
Q. Describe following keys: (1) Primary key (ii) Foreign key. (4M)
Definition:
A key is an attribute or set of attributes that uniquely identifies any record (or tuple) from the table.
Purpose:
• Keys are very important part of Relational database.
• Key is used to uniquely identify any record or row of data from the table.
• It is also used to establish and identify relationships between tables.
1. Super Key
A super key is a combination of all possible attributes that can uniquely identify the rows (or
tuple) in the given relation.
Super key is a superset of a candidate key.
A table can have many super keys
A super key may have additional attribute that are not needed for unique identity
Super Keys:
{Emp_ld} {Emp Id, Aadhar_No} {Emp_Id, Aadhar_No, Email_Id} {Aadhar_No}
{Aadhar_No, Email_Id} {Emp_Id, Name} {Email_id} {Emp_ld, Email_Id} {Emp_id, Name,
Dep_Id}
{Emp_Id, Name, Aaadhar_No, Email_Id, Dept_Id}
2. Candidate Key
A candidate key is an attribute or set of an attribute which can uniquely identify a tuple.
A candidate key is a minimal super key; or a Super key with no redundant attributes.
o It is called a minimal super key because we select a candidate key from a set of super key
such that selected candidate key is the minimum attribute required to uniquely identify the
table
Candidate keys are defined as distinct set of attributes from which primary key can be selected.
Candidate keys are not allowed to have NULL values.
Candidate Keys
1. {Emp_ld}
2. {Aadhar_No}
3. {Email_Id}
3. Primary Key
• Primary key is a key that uniquely identify each record in a table.
• A primary key is one of the candidate key chosen by the database designer to uniquely identify the tuple in the
relation
– The value of primary key can never be NULL.
– The value of primary key must always be unique (not duplicate).
– The values of primary key can never be changed i.e. no updation is possible.
– The value of primary key must be assigned when inserting a record.
– A relation is allowed to have only one primary key.
• Primary Key
1. {Emp_ld}
4. Alternate Keys
• Out of all candidate keys, only one gets selected as primary key, remaining keys are known as alternate
keys.
• In the Employee table
o Emp_ld is best suited for the primary key.
o Rest of the attributes like Aadhar_No, Email_Id are considered as a alternate keys.
o Alternate Keys
1. {Aadhar_No}
2. {Email_Id}
5. Foreign keys
A Foreign Key is:
o A key used to link two tables together.
o An attribute (or set of attributes) in one table that refers to the Primary Key in another table.
• The purpose of the foreign key is
o To ensure (or maintain) referential integrity of the data.
Key Points
Foreign key references the primary key of the table.
Foreign key can take only those values which are present in the primary key of the referenced relation.
Foreign key may have a name other than that of a primary key.
Foreign key can take the NULL value.
There is no restriction on a foreign key to be unique.
In fact, foreign key is not unique most of the time.
Referenced relation may also be called as the master table or primary table.
Referencing relation may also be called as the foreign table.
6. Composite Key
A key that has more than one attributes is known as composite key. It is also known as compound key.
Composite Key:
o {Cust_ld, Product Code}
Definition of Normalization
In the Relational Database Design, the process of organizing data to minimizing redundancy is known as
Normalization
Introduction
• Normalization is a process of organizing the data in database to avoid data redundancy, insertion
anomaly, update anomaly & deletion anomaly.
• It is the process of efficiently organizing data in a database.
• There are two goals of the normalization process:
1. Eliminating redundant data.
2. Reduce the data anomalies.
• There are three types of anomalies that occur when the database is not normalized.
– Insert Anomalies
– Delete Anomalies
– Update Anomalies
Two employees (John & Smith) are having two mobile numbers so the
company stored them in the same field as you can see in the table above.
This table is not in 1NF as the rule says “each attribute of a table must have atomic (single)
values”, the Emp_mobile values for employees John & smith violates that rule.
To make the table complies with 1NF we should have the data like this:
The table is in 1 NF because each attribute has atomic values. However, it is not in 2NF
because non-prime attribute Teacher_age is dependent on Teacher_id alone which is a
proper subsetof candidate key. This violates the rule for 2NF.
• To make the table complies with 2NF we can break it in two tables like this:
What is SQL?
- SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data
stored in a relational database.
- SQL is Declarative language i.e. a non-procedural language.
Characteristics of SQL
Q. Write characteristics of SOL (4 M)
• SQL is an ANSI and ISO standard computer language for creating and manipulating databases.
• SQL allows the user to create, update, delete, and retrieve data from a database.
• The tokens and syntax of SQL are oriented from English common speech to keep the access barrier as
small as possible. Hence it is very simple and easy to learn.
• All the keywords of SQL can be expressed in any combination of upper and lower case characters. It
makes no difference whether UPDATE, update, Update, UpDate ie. the keywords are case insensitive
• SQL is a declarative language, not a procedural one.
• SQL is very powerful language.
1. CREATE
- CREATE statement is used to create database schema and to define the type and structure of the
data to be stored in the database.
- CREATE statement can be used for
o Creating a Database,
o Creating a Table, etc.
I. Creating a DATABASE:
CREATE DATABASE statement is used to create a database in RDBMS.
Syntax: CREATE DATABASE database_name;
Example: CREATE DATABASE my_db;
Syntax:
Note:
DESC (or DESCRIBE) statement: To describe the details of the table structure
Syntax: DESC Table_name;
Example: DESC Emp;
Creating new table having specific fields but all the records from existing table.
Syntax: Create table table_name
as select from existing_table_name
where condition
Example: Create table newstudent3
as select from student
where marks >80;
The newly created table will be structure wise same as of existing table, but it will contain records of only those
students who got marks above 80.
Output:
roll_no stud name bdate marks
101 Kunal 12-02-2000 90
103 Radhika 05-04-2000 85
2. ALTER: -
– The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
– The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
3. DROP: -
– The DROP TABLE statement is used to drop an existing table in a database.
Syntax:- DROP TABLE table_name;
Example:- DROP TABLE Student;
4. TRUNCATE: -
– The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
Syntax: - TRUNCATE TABLE table_name;
Example:- TRUNCATE TABLE Student;
5. RENAME:-
– To change the name of the table
Syntax:- RENAME <old_table_name> To < new_table_name>;
Example:- RENAME student TO stud_data;
Q.How to apply NOT NULL constraint at the time of table creation? Give syntax. ( 2 M)
Q. Explain NOT NULL constraints suitable example(4M)
Q. Explain NOT NULL and CHECK constraints(4M)
1). Not Null: By default all columns in tables allows null values. When a NOT NULL constraint is
enforcedon column or set of columns it will not allow null values.
Syntax for NOT NULL
SQL> Create Table Table_name (column_name Data_type, Column_name Data_type Not Null);
Example:
SQL> Create Table Student (Roll_no Number (5), Name Varchar2 (20) Not Null);
After table creation not NULL can be added as:
SQL> Alter table EMP modify empname varchar2 (20) not Null;
2). CHECK: The constraint defines a condition that each row must satisfy. A single column can have
multiplecheck condition.
Syntax:-
SQL> Create Table Table_name (Column_name1 Data_type, Column_name2 Data_type
ConstraintConstraint_name Check <Condition>);
Example:
SQL> Create Table EMP (Id Number (5), Name Varchar2 (10), Sal Number (10) Constraint
Chk_salCheck (Sal>15000));
After table creation Check constraint can be added as:
SQL> Alter table EMP add constraint chk_emp check (salary>15000);
3) DEFAULT: When a user does not provide a value to the colme while inserting the records in the table,
the DEFAULT constraint provides a default value to that column.
Example
We can set DEFAULT Constraint by assigning the value 10000 to the column exam fees in student
table. So that, if user doesn't give any value for that column, it takes the default value as 10000.
2. 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 setof
columns.
Syntax:
Create Table Table_name (Column_name1 Data_type, Column_name2 Data_type
Constraint Constraint_name Unique);
Example:
Create Table Persons (p_id Number Constraint P_uk Unique, Firstname Varchar2 (20), City
Varchar2
(20) );
After table creation unique can be added as:
SQL> Alter table EMP add constraint ph_uk unique (phoneno);
INSERT
– The INSERT INTO statement of SQL is used to insert a new row in a table.
– There are two ways of using INSERT INTO statement for inserting rows:
1) Only values:
First method is to specify only the value of data to be inserted without the column names.
Syntax: INSERT INTO VALUES (value1,value2, ......... );
Example: insert into student values(1,"manjusha",10);
– The inserted values must match the table structure exactly in the number of attributes and the data type
of each attribute.
– Character type values are always enclosed in single quotes or double quotes, Number values are
never in quotes, date values are often (but not always) in the format ‘yyyy-mm-dd’ (for example, ‘2006-
11- 30’ )
UPDATE
- The UPDATE statement in SQL is used to update the data of an existing table in database.
- We can update single columns as well as multiple columns using UPDATE statement as per our
requirement.
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2,... WHERE condition;
table_name: name of the table
column1: name of first , second, third column....
value1: new value for first, second, third column....
condition: condition to select the rows for which the values of columns needs to be
updated.
NOTE: In the Update statement, WHERE clause identifies the rows that get affected. If you do not include
the WHERE clause, column values for all the rows get affected.
For Example: To update the location of an employee, the sql update query would be like,
UPDATE employee
SET location ='Mysore'
WHERE id = 101;
To change the salaries of all the employees, the query would be,
UPDATE employee
SET salary = salary + (salary * 0.2);
DELETE
- The DELETE Statement in SQL is used to delete existing records from a table. We can delete a
single record or multiple records depending on the condition we specify in the WHERE clause
Syntax:
DELETE FROM table_name WHERE some_condition;
table_name: name of the table
some_condition: condition to choose particular record.
– We can delete single as well as multiple records depending on the condition we provide in
WHERE clause.
NOTE: The WHERE clause in the sql delete command is optional and it identifies the rows in the column
that gets deleted. If you do not include the WHERE clause all the rows in the table is deleted, so be careful
while writing a DELETE query without WHERE clause.
Example
To delete an employee with id 100 from the employee table, the sql delete query would be like,
DELETE FROM employee WHERE id = 100;
To delete all the rows from the employee table, the query would be like,
DELETE FROM employee;
• Data Control Language provides database administrators with the ability to grant
users database permissions, revoke permissions previously granted.
• Two types of DCL commands are:
1. Grant
2. Revoke.
1. Grant:-
• To allow specified users to perform specified tasks
• SQL GRANT is a command used to provide access or privileges on the database objects to the
users.
Syntax:-
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
Where,
• Privilege_name is the access right or privilege granted to the user. Some of the access
rights are ALL, EXECUTE, SELECT, ALTER, DELETE, INSERT, and UPDATE.
• Object_name is the name of a database object like TABLE, VIEW, STORED PROC and
SEQUENCE.
• User_name is the name of the user to whom an access right is being granted.
• PUBLIC is used to grant access rights to all users.
• ROLES are a set of privileges grouped together.
• WITH GRANT OPTION - allows a user to grant access rights to other users.
Example:-
• a). GRANT SELECT ON employee TO user1 (This command grants a SELECT permission on
employee table to user1.)
• b). Grant all privileges on student table to user Prakash.
SQL> GRANT All ON student TO Prakash
2. Revoke:-
• The revoke command removes user access rights or privileges to the database objects.
Syntax:-
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
Example:-
a) REVOKE SELECT ON employee FROM user1; (This command will revoke a SELECT
privilege on employee table) from user1.
b) Revoke delete privilege on student table from Prakash.
SQL>REVOKE Delete ON student FROM Prakash.
• A Transaction begins with the first executable SQL statement after a Commit, Rollback or
Connection made to the Oracle engine.
• All changes made to an Oracle table data via a transaction are made or undo at one instance.
• SQL Transaction Control Language commands are used for managing changes affecting the data.
• These commands are COMMIT, ROLLBACK and SAVEPOINT.
1. COMMIT:-
• Commit command is used to permanently save any transaction into database.
• The COMMIT command is used to save changes invoked by a transaction to the database.
• The COMMIT command saves all transactions to the database since the last
COMMIT command.
• The syntax for COMMIT command is as follows:
• SQL> COMMIT;
2. ROLLBACK:-
• This command restores the database to last committed state.
• The ROLLBACK command is used to undo transactions that have not already been saved to
the database.
• The ROLLBACK command can only be used to undo transactions since the last COMMIT
or ROLLBACK command was issued.
• We can either rollback the entire transaction or till a particular save point transaction can
be rolled back.
• The syntax for ROLLBACK is: ROLLBACK TO SAVEPOINT_NAME; OR
ROLLBACK;
• Example:- ROLLBACK TO sv1; OR ROLLBACK;
3. SAVEPOINT:-
• Savepoint command is used to temporarily save a transaction so that you can rollback to
that point whenever necessary.
• Syntax:
SAVEPOINT <Save_Point_Name>
• Example:-
SAVEPOINT A;
2. Let’s use some SQL queries on the above table and see the results.
SQL> INSERT into student values (5,'Rahul');
SQL> commit;
SQL> UPDATE student set name='abhijit' where id='5';
SQL> savepoint A;
SQL> INSERT into student values (6,'Chris');
SQL> savepoint B;
SQL> INSERT into student values (7,'Bravo');
SQL> savepoint C;
SQL> SELECT * from Student;
SQL> rollback to B;
SQL> SELECT * from Student;
ID NAME
1 abhi
2 adam
4 alex
5 abhijit
SELECT expressions
FROM TABLES
WHERE conditions;
For example:
SELECT FirstName
FROM Student
WHERE RollNo > 15;
SELECT DISTINCT
Inside a table, a column often contains many duplicate values; and sometimes you only
want to list the different (distinct) values.
The distinct keyword is used to return only distinct (different) values.
Syntax: - SELECT DISTINCT column1, column2 ...FROM table_name;
Example:- SELECT DISTINCT Country FROM Customers;
2 UK 2 UK
3 India 4 Canada
4 Canada
After DISTINCT keyword it produce
5 UK
the following output table.
WHERE Clause
The
WHERE clause is used to filter records.
The WHERE clause is used to extract only those records that fulfill a specified condition.
Syntax
: - SELECT column1, column2... FROM table_name WHERE condition;
Example:- SELECT * FROM Customers WHERE CustomerID=1;
+ (addition) Addition is performed through the use of SELECT SALARY + BONUS FROM
the plus (+) symbol. EMP;
- (subtraction) Subtraction is performed using the minus SELECT SALARY - BONUS FROM
(-) symbol. EMP;
* (multiplication) Multiplication is performed by using the SELECT SALARY * 10 FROM EMP;
asterisk (*) symbol.
/ (division) Division is performed through the use of SELECT SALARY / 10 FROM EMP;
the ―/‖ symbol.
Comparison Operators:-
= Checks if the values of two operands are equal or not, if yes (a = b) is not true.
then condition becomes true.
!= Checks if the values of two operands are equal or not, if (a != b) is true.
values are not equal then condition becomes true.
<> Checks if the values of two operands are equal or not, if (a <> b) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value (a > b) is not true.
of right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (a < b) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (a >= b) is not true.
the value of right operand, if yes then condition becomes
true.
<= Checks if the value of left operand is less than or equal to (a <= b) is true.
the value of right operand, if yes then condition becomes
true.
!< Checks if the value of left operand is not less than the value (a !< b) is false.
of right operand, if yes then condition becomes true.
!> Checks if the value of left operand is not greater than the (a !> b) is true.
value of right operand, if yes then condition becomes true.
Logical Operators:
AND The AND operator allows the existence of SQL> Select *from Persons Where
multiple conditions in an SQL statement's FirstName = ’Vikas’ AND LastName
WHERE clause. =’Jain’;
OR The OR operator is used to combine multiple SQL> Select *from Persons Where
conditions in an SQL statement's WHERE FirstName = ’Vikas’ OR LastName
clause. =’Jain’;
NOT The NOT operator reverses the meaning of the SQL> Select FirstName, LastName
logical operator with which it is used. E.g.: from Persons Where NOT
NOT EXISTS, NOT BETWEEN, NOT IN, etc. Games=’football’;
This is a negate operator.
Q. List the SQL operations and explain range searching operations between and pattern matching
operator ‘like’ with example.(4 M)
List of operators : 2M, between operator : 1M, Like operator : 1M
Types of SQL operators :
1) SQL Arithmetic Operators
2) SQL Comparison Operators
3) SQL Logical Operators
Arithmetic operators are used to perform arithmetic operations on numbers. They are +,-,*, / and %.
Comparison operators are used in between two variables to compare their values. They are <,>,<=,>=,=,!=or
<>,!< and !>.'
Logical operators are used for the Boolean results in sql queries for comparison of values from the attributes of
the tables. Eg: Any, Exists, All, Like, Between, In etc.
Between operator:
The BETWEEN operator is used to search for values that are within a set of values, given the minimum
value and the maximum value inclusive of both the limits.
Eg: select * from emp where salary between 40000 and 50000; This will results in rows from emp table
where salary falls in the range of 40000 to 50000.
Like operator :
The LIKE operator is used to compare a value to similar values using wildcard operators.
It uses two wild characters as ‘%’ and ‘_’
where ‘%’ represents all characters of the pattern and ‘_’ represents one single character from pattern.
Eg : Select ename from emp where ename like ‘S%’;
This will return all employee names starting with ‘S’.
Select ename from emp where ename like ‘_a%;
This will return all employee names whose second character is ‘a’.
SET Operator:-
Set operators combine the results of two component queries into a single result. Queries
containing set operators are called as compound queries. Set operators in SQL are
representedwith following special keywords as: Union, Union all, intersect & minus.
1. Union:-
The UNION operator is used to combine the result-set of two or more SELECT statements.
i. Each SELECT statement within UNION must have the same number of columns
ii. The columns must also have similar data types
iii. The columns in each SELECT statement must also be in the same order
Customers Suppliers
C_ID C_Name City Country S_ID S_Name City Country
1 Alex Pune India 1 Alice Shaman China
2 Bob Mumbai India 2 Bob Mumbai India
3 Zach Berlin Germany 3 Joe Berlin Germany
Output
Country
China
Germany
India
2. Union All: - The following SQL statement selects all values (duplicate values also)
from Table.
3. Intersect: - The SQL Intersect operator takes the results of two queries & returns only rows that
appear in both result sets.
Sales2
Sales1 Output Table
Person Amount
Person Amount Person Amount
Joe 2000
Joe 1000 Alex 2000
Alex 2000
Alex 2000
Zach 35000
Bob 5000
4. Minus: - The SQL MINUS query returns all rows in the first SQL
SELECT statement that are not returned in the second SQL SELECT statement.
Ans:
Q. Consider following database and solve queries emp (empno, ename, ph, sal, dept no, comm)( 4 M)
(i)Change employee name 'Rahul' to 'Ramesh'.
(ii) Give increment of 20 % in salary to all employees. (Refer section 2.19)
Ans:
(i) Update emp set ename = 'Ramesh' where ename = 'Rahul';
(ii) Update emp set sal=sal*0.2;
Ans:
(i) Select * from employee where Dept_location = 'Mumbai
(ii) Update employee set sal = 70000 where designation = ‘project leader';
(iii) Select * from employee where emp_name like '_A%";
(iv) Select * from employee where Dept location in("Mumbai”, "Chennai”);
Q. Given
Employee (EMP ID,FIRST NAME. LAST_NAME, SALARY, JOINING DATE,DEPARTMENT) (4 Marks)
Write SQL queries for
Get FIRST NAME, LAST NAME from employee table.
• Get unique DEPARTMENT from employee table.
• Get FIRST_NAME from employee table using alias name "Employee Name”
• Get FIRST NAME from employee table after removing white spaces from left side.
Ans:
(i) Select first_name, last_name from employee;
Q. Consider the structure for book table as Book_master (book_id, book_name, subcode, author,no_of_copies,
price). 4 Marks
Write SQL queries for the following:
(i) Display total number of books for subject 'DBM'.
(ii) Get authorwise list of all books,
(iii) Display all books whose prices are between Rs. 200 and Rs. 500.
Ans:
(i) Select count(*) from Book_master where book name='DBM';
(ii) Select count * from Book_master order by author;
(iii) Select count * from Book_master where price between 200 and 500;
Emp (Empno, Ename, job, mgr, joindate, salary, comm, deptno, loc).
(1) Write a query to find list of employees whose salary is not less 5000.
(2) Write a query to find list of employees whose job title is either "Manager" or "Analyst".
(3) Change the location of deptno 40 from Chandrapur.
(4) Display the Ename and salary of employees who earn more than Rs. 50,000 and are in deptno 10 or 30.
Ans:
(i) Select * from emp where salary NOT <5000
(ii) Select * from emp where job in ('Manager' or 'Analyst');
(iii) Update emp set loc = 'Pune' where deptno = 40 and loc = 'Chandrapur'
(iv) Select ename, salary from emp where salary > 50000 and deptno in(10,30);