0% found this document useful (0 votes)
7 views26 pages

CH-2 Relational Data Model

Chapter 2 covers the fundamentals of the Relational Data Model, including key concepts such as tables, records, and normalization. It discusses E.F. Codd's rules for RDBMS, types of keys, and the introduction of SQL commands. Additionally, it explains normalization, its goals, and the advantages of organizing data to minimize redundancy and anomalies.

Uploaded by

sanketr.co
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views26 pages

CH-2 Relational Data Model

Chapter 2 covers the fundamentals of the Relational Data Model, including key concepts such as tables, records, and normalization. It discusses E.F. Codd's rules for RDBMS, types of keys, and the introduction of SQL commands. Additionally, it explains normalization, its goals, and the advantages of organizing data to minimize redundancy and anomalies.

Uploaded by

sanketr.co
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

CHAPTER 2

RELATIONAL DATA MODEL


Marks – 18
2.1 Fundamentals of RDBMS –Record , field, Data type, Table and Database
2.2 Concept of RDBMS, E.F Codd’s Rule for RDBMS ,
Key Concepts-Candidate Key, Primary Key, Foreign Key
2.3 Normalization: Normalization Concepts, Need of Normalization,
Types of Normalization -1NF, 2NF, 3NF
2.4 Introduction to SQL
2.5 DDL Command
2.6 DML Command
2.7 DCL Command
2.8 DQL Command
2.10 SQL Operator

2.1 Introduction to Relational Model


• The Relational Model was proposed by E.F. Codd for IBM in 1970 to model data in the form of
relations or tables.
• The relational model of data is based on the concept of relations
• Relational Model represents the database as a collection of tables.
• A table is a database object that stores data in form of rows and columns.
• Each row in the table represents collection of related data value.

What is Relational Model?


Q. Define relational model. (2 Marks)
Relational Model is collectively combination of data structures, storage and retrieval operations and
integrity constraints.

Q. Write characteristics of relational model. (4 Marks)


 A Relational Database Management System (RDBMS) is based on the relational data model.
 In relational model tables are used to represent both data and the relationship among those data so a
relational database consists of a collection of tables.
 Each table is assigned a unique name.
 A table consists of fixed number of Columns. Each column within a table has a unique name.
 A table also contains variable number of rows or records containing data values.
 A table represents an entity set or relationship set.
 Columns of a table represent attributes.
 A row in a table represents individual entities or relationships or in other words a row contains data
values related to particular entity

2.2 Concepts of RDBMS


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.
 Current popular RDBMS include:
o DB2 & Informix Dynamic Server - from IBM
o Oracle & Rdb - from Oracle
o SQL Server & MS Access from Microsoft

Basic Concepts of Relational Model


Q. Define table and field. (2M Each definition 1M)
Q. Explain Records, Fields, tables and Database (4M)
Table/Relation - In Relational database, a table is a collection of data elements organized in terms of rows
and columns. A table is also considered as convenient representation of relations. Table is the simplest form of
data storage.
Record/Tuple - A single entry in a table is called a Record or Row. A Record in a table represents set of
related data.
Field/Attribute - A table consists of several records(row), each record can be broken into several smaller
entities known as Fields.
Column - In Relational table, a column is a set of value of a particular type. The term Attribute is also
used to represent a column. For example, in Employee table, Name is a column that represents names of
employee.
Database - Database is considered as collection of tables.
Domain: A domain is the set of allowable values for one or more attributes.
Schema: A relation schema represents the name of the relation with its attributes.
Relation instance (State): Relation instance is a finite set of tuples. Relation instances never have duplicate
tuples.
Degree: The total number of columns or attributes in the relation
Cardinality: Total number of rows present in the Table.
Relation key: Every row has one or multiple attributes, that can uniquely identify the row in the relation, which is
called relation key (Primary key).
Tuple Variable: it is the data stored in a record of the table.

Properties of Relational Model


 Each Relation has unique name
 Each tuple/Row is unique: No duplicate row
 Entries in any column have the same domain.
 Each attribute/column has a unique name
 Order of the columns or rows is irrelevant i.e relations are unordered
 Each cell of relation contains exactly one value i.e. attribute values are required to be atomic

E.F. Codd’s rules


Q. State any two E.F. Codd’s rule for RDBMS.( 2 M)
Q. List first four codd rules(4 M)
( ½ M for each rule , ½ M each proper statement )
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
4. The Dynamic Online Catalog Based on 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 database.
5. The Comprehensive Data Sublanguage rule: A relational system may support several languages and
various modes of terminal for data definition, view definition, data manipulation etc.
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 capability of handling a base relation or a derived
relation as a single database to perform all DML operations.
8. The Physical Data Independence rule: Application programs and terminal activities remain logically
unchanged 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
unchanged when information preserving changes of any kind are made to the base tables.
10. The Integrity Independence 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 Distribution Independence rule: An RDBMS has distribution independence. Distribution
independence implies that users should not have to be aware of whether a database is distributed.
12. The No subversion rule: If the database has any means of handling a single record at a time that low-
level language must not be able avoid the integrity rules which are expressed in a higher-level language
that handles multiple records at a time.

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.

Types of keys in DBMS


1. Super Key
2. Candidate Key
3. Primary Key
4. Alternate Key
5. Foreign Key
6. Composite Key

Emp_id Name Aadhar No Email_Id Dept_ld


01 Aman 775762540011 [email protected] 1
02 Neha 876834788522 [email protected] 2
03 Neha 996677898677 [email protected] 2
04 Vimal 796454638800 [email protected] 3

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.

Cust_ld Order_Id Product Code Product Count


C01 001 P111 5
C02 012 P111 8
C02 012 P222 6
C01 001 P333 9

 Composite Key:
o {Cust_ld, Product Code}

2.3 Normalization (IMP)


Q. State and explain 3NF with example.(4 M)
(Explanation 2M Any example 2M)
Q. Define normalization and explain it's two goals.( 2 M)
Q. Explain normalization with example.(4 M)
Q. Explain need of normalization and state 3NF(4M)
Q. What is meant by database normalization?(2M)
Q. List advantages of Normalization.

Advantages of the normalization.


o More efficient data structure.
o Avoid redundant fields or columns.
o More flexible data structure i.e. we should be able to add new rows and data values easily
o Better understanding of data.
o Ensures that distinct tables exist when necessary.

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

Types of Normal Forms


• Levels of normalization based on the amount of redundancy in the database.
• Various levels of normalization are:
– First Normal Form (1NF)
– Second Normal Form (2NF)
– Third Normal Form (3NF)

1. First Normal Form (1NF)


Q. State and explain 1NF and 2NF with example(4M)
 A database table is said to be in 1NF if it contains no repeating fields/columns.
 The process of converting the UNF (Un-normalized table) table into 1NF.
 The requirements to satisfy the 1st NF:
a. Each table has a primary key: minimal set of attributes which can uniquely identify a record
b. The values in each column of a table are atomic (No multi-value attributes allowed).
c. There are no repeating groups: two columns do not store similar information in the same table.
 As per the rule of first normal form, an attribute (column) of a table cannot hold multiple
values. It should hold only atomic values.
 Example: Suppose a company wants to store the names and contact details of its employees. It
createsa table that looks like this:

Emp_id Emp_name Emp_address Emp_mobile


101 Herschel New Delhi 8912312390
102 John Kanpur 8812121212
9900012222
103 Ron Chennai 7778881212
104 Smith Bangalore 9990000123
8123450987

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:

Emp_id Emp_name Emp_address Emp_mobile


101 Herschel New Delhi 8912312390
102 John Kanpur 8812121212
102 John Kanpur 9900012222
103 Ron Chennai 7778881212
104 Smith Bangalore 9990000123
104 Smith Bangalore 8123450987

2. Second Normal Form (2NF)


Q.Explain 2nd Normal form with suitable example.(3M)
 A table is said to be in 2NF if both the following conditions hold:
1. Table is in 1NF (First normal form)
2. Every non-prime attribute should be fully functionally dependent on prime key attribute.
• Prime attribute − an attribute, which is a part of the prime-key, is known as a prime
attribute.
• Non-prime attribute − an attribute, which is not a part of the prime-key, is said to
be a non-prime attribute.
 Example: Suppose a school wants to store the data of teachers and the subjects they teach. They
create a table that looks like this:

Teacher_id Subject Teacher_age


111 Maths 38
Candidate Keys:
111 Physics 38 {Teacher_id,
222 Biology 38 Subject} Non-
333 Physics 40 prime attribute:
333 Chemistry 40 Teacher_age

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:

Teacher_details Table: Teacher_subject table:

Teacher_id Teacher_age Teacher_id Subject


111 38
111 Maths
222 38
111 Physics
333 40
222 Biology
333 Physics
333 Chemistry

3. Third Normal Form (3NF)


Q. Explain 3NF with example.(4M)
• A table design is said to be in 3NF if both the following conditions:
o Table must be in 2NF
o Transitive functional dependency of non-prime attribute on any super key should be removed.
o It means there is no transitive functional dependency. (Transitive functional dependency can be
explained with the relationship link between three tables. If table A is functionally dependent on B,
and B is functionally dependent on C then C is transitively dependent on A).
• Example: Suppose a company wants to store the complete address of each employee, they create a
table named Employee_details that looks like this:
Emp_id Emp_name Emp_zip Emp_state Emp_city Emp_district

1001 John 282005 UP Agra Dayal Bagh


1002 Ajeet 222008 TN Chennai M-City
1006 Lora 282007 TN Chennai Urrapakkam
1101 Lilly 292008 UP Pauri Bhagwan
1201 Steve 222999 MP Gwalior Ratan

Here, Emp_state, Emp_city & Emp_district dependent on Emp_zip. And, Emp_zip


is dependent on Emp_id that makes non-prime attributes (Emp_state, Emp_city
& Emp_district) transitively dependent on super key (Emp_id). This violates the
rule of 3NF.
• To make this table complies with 3NF we have to break the table into two tables to remove the
transitive dependency:
Employee Table Employee_zip Table

Emp_id Emp_name Emp_zip Emp_zip Emp_state Emp_city Emp_district


1001 John 282005 282005 UP Agra Dayal Bagh
1002 Ajeet 222008 222008 TN Chennai M-City
1006 Lora 282007 282007 TN Chennai Urrapakkam
1101 Lilly 292008 292008 UK Pauri Bhagwan
1201 Steve 222999 222999 MP Gwalior Ratan

2.4 Introduction to Structured Query Language


History of SQL
– Dr. E.F. Codd published a paper on Relational Model ("A Relational Model Data from Large Shared
Data Banks") in 1970.
– IBM implemented the SQL language, originally called SEQUEL (Structured English Query Languag) as
part of the System R project in the early 1970s.
o SEQUEL is renamed/shortened to SQL (Structured Query Language)
– SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987.

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.

What are advantages of SQL ?


• High speed: Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.
• No coding needed: In the standard SQL, it is very easy to manage the database system. It doesn't
require a substantial amount of code to manage the database system.
• Well defined standards: Long established are used by the SQL databases that are being used by ISO
and ANSI.
• Portability: SQL can be used in laptop, PCs, server and even some mobile phones.
• Interactive language: SQL is a domain language used to communicate with the database. It is also
used to receive answers to the complex questions in seconds.
• Multiple data view: Using the SQL language, the users can make different views of the database
structure.
SQL DATA TYPES
Q. Explain datatypes in SQL(2M)
– Each column in a database table is required to have a name and a data type.
– The data type is a guideline for SQL to understand what type of data is expected inside of each column, and
it also identifies how SQL will interact with the stored data.
1. Numerical Data types
2. Character/String Data Types
3. Date Data Type
4. Binary Data Types
SQL Numeric Data Types
Datatype From To
smallint -32,768 32,767
int -2,147,483,648 2,147,483,647
bigint -9,223,372,036, 854,775,808 9,223,372,036, 854,775,807
decimal -10^38 +1 10^38 -1
numeric -10^38 +1 10^38 -1
float -1.79E + 308 1.79E + 308
real -3.40E + 38 3.40E + 38

SQL Character and String Data Types


Datatype Description
CHAR Fixed length with a maximum length of 8,000 characters
Variable-length storage with a maximum length of 8,000
VARCHAR
characters
TEXT Variable-length storage with maximum size of 2GB data

SQL Date and Time Data Types


Datatype Description
DATE Stores date in the format YYYY-MM-DD
TIME Stores time in the format HH:MI:SS
Stores date and time information in the format YYYY-MM-DD
DATETIME
HH:MI:SS
Stores year in 2 digits or 4 digit format. Range 1901 to 2155 in 4-
YEAR
digit format. Range 70 to 69, representing 1970 to 2069.

SQL Binary Data Types


Datatype Description
BINARY Fixed length with a maximum length of 8,000 bytes

RULES FOR SQL


 SQL statement starts with an action verb. For example, SELECT statement.
 Each verb may be followed by number of clauses. For example, WHERE
 A space separates key-words and clauses. For example, DROP TABLE employee
 A comma ‘,’ separates parameters without a clause.
 A semicolon ‘;’ is used to end SQL statement.
 Statements may be split across lines, but keywords cannot be split.
 Select * from student where en_no=111; Select * from student where en_n0=111;
 Numeric constants can be represented by simple values, such as 125.5, or in scientific notation, such as
1.255E2.
 Character and Date constants must be enclosed within single quotes, such as, ’hello world’ ,’01-APR-2013’
 Single line comments at prefixed with a ‘—’ (double hyphen) symbol. Multi-line comments are enclosed
between /* and */.

COMPONENTS of SQL/ SQL Sub-languages / Types of SQL Commands


Q. Explain various database Languages (4M)
Q. Write short note on DDL, DML and DCL (4M)
The commands provided by SQL can be categorized into four components as below.
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Control Language (DCL)
4. Data Control Language(DCL)
5. Transaction Control Language (TCL)
6. DQL (Data Query Language).

2.5 DDL (Data Definition Language) Commands


– Data Definition Language (DDL) commands are used to define the structure and schema of the database.
– Date Definition Language (DDL) is used for creating and modifying the database objects such as tables,
indices, views and users.
– All the command of DDL are auto-committed that means it permanently save all the changes in the database.
o CREATE- to create new table or database
o ALTER- to alter the structure of table
o DROP- to delete a table from database
o TRUNCATE - to delete all records from table
o RENAME - to rename a table

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;

II. Creating a TABLE:


– CREATE TABLE statement is used to create a new table in a database.
– It specifies column names of the table, its data types (e.g. varchar, integer, date, etc.) and can also specify
integrity constraints (e.g. Primary key, foreign key, not null, unique).

Syntax:

CREATE TABLE table_name


( column_namel datatype,
column_name2 datatype,
--- --- ---
column_namen datatype,
(Integrity Constraints)
);
Example: Create table
CREATE TABLE student
(
roll_no integer(3),
stud_name varchar(20),
bdate date,
marks integer(3)
);
Roll_no Stud_name bdate marks

Note:
DESC (or DESCRIBE) statement: To describe the details of the table structure
Syntax: DESC Table_name;
Example: DESC Emp;

III. Creating New Table from Existing TABLE:


AS SELECT clause is used to create table from existing table. It can be considered as copy of existing
table. While creating such table, we have option whether to take all records, fields from existing table or
not. We can copy just structure of the existing table also. The different ways of coping table are as given
below:
Creating new table same as of existing table.
Syntax: Create table table_name
as select from existing_table_names
Example:
Create table newstudent
as select * from student:
Output: The newly created table will be
newstudent
roll_no stud name bdate marks
101 Kunal 12-02-2000 90
102 Jay 07-08-1999 68
103 Radhika 05-04-2000 85
104 Sagar 13-02-2000 70
105 Supriya 11-08-1999 72

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.

 To ADD a column in a table, use the following syntax:


Syntax: - ALTER TABLE table_name ADD column_name Data_type;
Example: - ALTER TABLE student ADD grade varchar(2);

 To MODIFY a column in a table, use the following syntax


Syntax: - ALTER TABLE table_name MODIFY COLUMN column_name datatype;
Example: - ALTER TABLE student MODIFY COLUMN roll_no varchar(5);

 To DROP a column in a table, use the following syntax


Syntax: - ALTER TABLE table_name DROP COLUMN column_name;
Example: - ALTER TABLE student DROP COLUMN grade;

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. Explain difference between delete and truncate command with example. (4 M)


(2 M for proper explanation of each command) or (any 4 differences)
2.6 DATA INTEGRITY CONSTRINTS
– Integrity Constraints: - It is a mechanism used to prevent invalid data entry into the table.
– “A constraint is a rule that restricts the values that may be present in the database.”
– The data stored in database should be valid, correct and consistent.

Types of Integrity Constraints


1. Domain Integrity Constraints
2. Entity Integrity Constraints
3. Referential Integrity Constraints

1. Domain Integrity Constraints

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. Entity Integrity Constraints:

1. Primary Key constraint:


It is use to avoid redundant / duplicate value entry within the row of specifiedcolumn in table. It
restricts null values too.
 Syntax:
Create Table Table_name (Column_name1 Data_type, Column_name2 Data_type
Constraint Constraint_name Primary Key);
 Example:
SQL> Create Table Emp (Id Number (5) constraint Id_pk Primary Key, Name Varchar2 (10),
SalNumber (10));
 After table creation primary key can be added as:
SQL> Alter table EMP add constraint pk_emp Primary Key (empid);

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);

3. Referential Integrity Constraint:


Q. Explain foreign key and ON DELETE CASCADE with suitable example.(4M)
• It used to establish a parent child relationships between two tables.
• A value of foreign key is derived from the primary key.
• Primary key is defined in a parent table & foreign key is defined in child table.
 Syntax:
Create Table Table_name (Column_name1 Data_type (size) References Parent_table_name
(PrimaryKey attribute), Column_name2 Data_type);
 Example:
Create Table Product (EmpId Number (5) References Emp (EmpId), ProdName varchar2 (10));
 After table creation the foreign key can be added as:
SQL> Alter table product add constraint fk_prod foreign key (EmpId) references Emp (EmpId);

2.7 DML (Data Manipulation Language) Commands


Data Manipulation Language (DML) commands are used for accessing and manipulating the data stored in
the database.
1. INSERT - to insert a new row into a table
2. UPDATE - to update existing row in a table
3. DELETE-to delete a row from a table

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’ )

2) Column names and values both:


In the second method we will specify both the columns which we want to fill and their corresponding values
as shown below:
Syntax: INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..);
table_name: name of the table.
column1: name of first column, second column …
value1, value2, value3 : value of first column, second column,… for the new record
Example:
INSERT INTO student (rollno, name, address, marks) VALUES ( 1,”meena”,”pune”,90);

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;

Q. Enlist DML commands.(2M)


Insert - used to insert new row into table
Delete- used to delete a row from the table
Update – used to modify data in the table.
Select – used to view data from a table.

Q. Write syntax of insert command. Demonstrate with suitable example. (4 M)


Q. List DML(2 M)
Q. List Four DDL commands with syntax.(2M,W-18)
Ans:
DDL commands :-
1. Create
Syntax : create table <table_name>(Column_name1 datatype1, column_name2
Datatype2,…Column_nameN DatatypeN);
2. Drop
Syntax: drop table <table_name>;
3. Desc
Syntax: describe <table_name>; OR
Desc <table_name>
4. Truncate
Syntax: truncate table <table_name>;
5. Alter
Syntax: Alter table <table_name> add Column_name Datatype (size);

2.8 DCL (Data Control Language) Commands

• 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.

2.9 TCL (Transaction Control Language) Commands

• 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;

Example of Commit, Savepoint and Rollback

1. Following is the Student table,


ID NAME
1 Abhi
2 Adam
4 Alex

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;

3. The resultant table will look like,


ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris
7 bravo
4. Now rollback to savepoint B

SQL> rollback to B;
SQL> SELECT * from Student;

5. The resultant table will look like


ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris
6. Now rollback to savepoint B
SQL> rollback to A;
SQL> SELECT * from Student;

7. The resultant table will look like

ID NAME
1 abhi
2 adam
4 alex
5 abhijit

2.10 DQL (Data Query Language) Commands


 It is a component of SQL that allows data retrieval from database.
 It provides command like SELECT .
 This command is a heart of SQL and it allows data retrieval in different ways.
o SELECT-to retrieve data from the database
This command helps you to select the attribute based on the condition described by the WHERE clause.
Syntax:

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;

“Customers” Table “Customers” Table


Sr. No. Country Sr. No. Country
1 India 1 India

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;

2.11 SQL Operators


Arithmetic Operators (Q. List and explain any 4 arithmetic operators in SQL with example.)
 Arithmetic operators are used to perform mathematical functions in SQL—the same as in
most other languages. There are four conventional operators for mathematical functions:
+ (addition)
- (subtraction)
* (multiplication
) / (division)

Operator Description Example

+ (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:-

Operator Description Example

= 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.

Example 1. SQL> SELECT * from customers where salary >15000;


SQL> Select *from customers where PersonID=15;

Logical Operators:

Operator Description Example

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.

Other Comparison Operators:-

Operator Description Example


LIKE The LIKE operator is used to compare a value SQL> Select FristName From Persons
to similar values using wildcard operators. Where FirstName LIKE ‘_i%’;
IN The IN operator is used to compare a value is SQL> Select FristName From Student
equal to any one of specified set of values. Where subject IN (‘Maths’, ‘Science’);
BETWEEN The BETWEEN operator is used to search for SQL> Select FristName From Student
…..AND values that are within a set of values, given the Where age BETWEEN 10 AND 15 ;
minimum value AND the maximum value.
IS NULL The NULL operator is used to compare a value SQL> Select FristName From Student
with a NULL value. Where games IS NULL;

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
representedwith 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

 Syntax:- SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;
 Example 1 :- SELECT *FROM Sales1 UNION SELECT * FROM Sales2 ;

Sales1 Sales2 Output Table

Person Amount Person Amount Person Amount

Joe 1000 Joe 2000 Joe 1000

Alex 2000 Alex 2000 Alex 2000

Bob 5000 Zach 35000 Bob 5000


Joe 2000
Zach 35000

 Example 2.:- SELECT Country FROM Customers


 UNION
SELECT Country FROM Suppliers ORDER BY Country;
 Consider Two table like “Customers” & “Suppliers”

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.

  Syntax:- SELECT column_name(s) FROM table1


 UNION ALL
 SELECT column_name(s) FROM table2;
 Example 1:- SELECT * FROM Sales1 UNION ALL SELECT * FROM Sales2 ;



Sales1 Sales2 Output Table


Person Amount Person Amount Person Amount
Joe 1000 Joe 2000 Joe 1000
Alex 2000 Alex 2000 Alex 2000
Bob 5000 Zach 35000 Bob 5000
Joe 2000
Alex 2000
Zach 35000

3. Intersect: - The SQL Intersect operator takes the results of two queries & returns only rows that
appear in both result sets.

  Syntax:- SELECT column_name(s) FROM table1


 INTERSECT
 SELECT column_name(s) FROM table2;
  Example 1:- SELECT * FROM Sales1
 INTERSECT
SELECT * FROM Sales2;

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.

 Syntax:- SELECT column_name(s) FROM table1


MINUS
SELECT column_name(s) FROM table2
SEL
  Example 1:- SELECT * FROM Sales1
 MINUS
SELECT * FROM Sales2;

Sales1 Sales2 Output Table Output Table


Person Amount Person Amount Sales1 - Sales2 Sales2 – Sales1
Joe 1000 Joe 2000 Person Amount Person Amount
Alex 2000 Alex 2000 Joe 1000 Joe 2000
Bob 5000 Zach 35000 Bob 5000 Zach 35000
Q. Consider the table (6 M)
Student (name, marks, dept, age, place, phone, birthdate). Write SQL query for following.
i)To list students having place as ‘Pune’ or ‘Jalgaon’
ii)To list students having same department(dept) as that of ‘Rachana’
iii) To change marks of ‘Rahul’ from 81 to 96.
iv) To list student name and marks from ‘Computer’ dept.
v) To list student name who have marks less than 40.
vi)To list students who are not from ‘Mumbai;
(Each Correct Query : 1M)
Ans:
i)select name from Student where place= ‘Pune’ or place=’Jalgaon’; (OR)
select name from Students where place in(‘Pune’,‘Jalgaon’);
ii)select name from Student where dept=(select dept from student where name=’Rachana’);
iii)update Student set marks=96 where name= ‘Rahul’;
v)select name,marks from Student where dept=‘Computer’;
iv)select name from Student where marks<40;
v)select * from Student where place != ‘Mumbai’;

Q. Consider the following schema. (4 Marks)


STUDENT (Name, Mark, Age, Place, Phone, Birthdate)
Write SQL queries for following:
(i) To list name of student who do not have phone number.
(ii) To list student from Nashik and Pune.
(iii) To change mark of Monika to 88 instead of 80.
(iv) To list the student from Amit's age group.

Ans:

(i) Select * from STUDENT where phone is NULL;


(ii) Select * from STUDENT where city in("Nashik', 'Pune');
(iii) Update STUDENT set marks = 88 where name = 'Monika';
(iv) Select * from emp where age = (select age from emp where name='Amit');

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;

Q. Consider following schema


Employee (emp_no, emp_name, designation, salary, Dept_location) (4M)
Solve following queries:
(i) list all Managers in Mumbai location
(ii) set salary of all 'project leaders' to 70000
(iii) list employees with having alphabet 'A' as second letter in their name.
(iv) display details of those employees who work in Mumbai or Chennai.

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;

(ii) Select unique(department) from employee;

(iii) Select first name "Employee Name" from employee;

(iv) Select Itrim(first_name) from employee;

Q. Consider the following database:

Employee (emp_id, emp_name, emp_city, emp_addr, emp_dept, join_date)

Solve the following query:


(i) Display the names of employees in capital letters.
(ii) Display the emp_id of employee who live in city Pune and Mumbai.
(i) Display the details of employees whose joining date is after '01-Apr.-1997'.
(iv) Display the total number of employees whose department number is '10'.
Ans:
(i) Select ucase(emp_name) from employee;
(ii) Select emp_id from employee where emp_city in('Pune',"'Mumbai');
(iii) Select * from employee where join_date> '01-Apr.-1997';
(iv) Select count(*) from employee where deptno = 10;

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;

Q. Consider the following database schema: 4 Marks

Emp (Empno, Ename, job, mgr, joindate, salary, comm, deptno, loc).

Write the SQL queries for the following:

(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);

You might also like