Unit-2 DBMS
Unit-2 DBMS
CONTENT OF UNIT- 2
• Relational data Model and Language
• Relational data model concepts
• integrity constraints:
entity integrity
referential integrity
Keys constraints
Domain constraints
• Relational algebra
• Introduction to SQL
• Characteristics of SQL
• Advantage of SQL
• SQL data types and literals
• Types of SQL commands
• SQL operators and their procedure
• Tables
• views
• Queries
• Aggregate functions
• Insert
• update and delete operations
• Joins
• Unions, Intersection, Minus
Relational Model: The Relational Model
What is the Relational Model?
The relational model represents how data is stored in Relational Databases. A relational
database consists of a collection of tables, each of which is assigned a unique name.
Consider a relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE, and
AGE shown in the table.
Table Student
ROLL_NO NAME ADDRESS PHONE AGE
1 RAM DELHI 9455123451 18
4 SURESH DELHI 18
Important Terminologies
Attribute:
Attributes are the properties that define an entity. e.g.; ROLL_NO, NAME, ADDRESS
Relation Schema:
A relation schema defines the structure of the relation and represents the name of the relation with
its attributes. e.g.; STUDENT (ROLL_NO, NAME, ADDRESS, PHONE, and AGE) is the relation schema
for STUDENT. If a schema has more than 1 relation, it is called Relational Schema.
Tuple: Each row in the relation is known as a tuple. The above relation contains 4 tuples, one of
which is shown as:
1 RAM DELHI 9455123451 18
Customers Table
customer_id name email
1 John Doe john.doe@example.com
2 Jane Smith jane.smith@example.com
order_id
order_id customer_id product quantity
101 1 Laptop 1
102 2 Smartphone 2
Constraints in dbms
What are the Constraints in DBMS?
• Constraints in DBMS (Database Management Systems) are rules
or conditions that are applied to the data within a database to
ensure data integrity, consistency, and adherence to business
rules.
• They define limitations and requirements that the data must
meet, thereby preventing the entry of invalid or inconsistent data.
• Constraints serve as a set of predefined rules that govern the
behavior and relationships of the data in a database, helping to
maintain its accuracy and reliability.
• The purpose of constraints is to enforce data quality and prevent
data inconsistencies, thereby enhancing the overall data integrity
and reliability of the database.
• Constraints define boundaries for data values, relationships
between entities, uniqueness requirements, and more.
• By enforcing constraints, DBMS can ensure that the data conforms
to predefined standards and business rules, making the database
Types of Constraints in DBMS
• In relational databases, there are mainly 5
types of constraints in DBMS called relational
constraints.
They are as follows:
• Domain Constraints in DBMS
• Key Constraints in DBMS
• Entity Integrity Constraints in DBMS
• Referential Integrity Constraints in DBMS
• Tuple Uniqueness Constraints in DBMS
Domain Constraints in DBMS
• The domain means a range of values. In
mathematics, the concept of Domain means the
allowed values for a function.
• Similarly, in DBMS, the Domain Constraint specifies
the domain or set of values.
• This is a constraint applied to attributes, not tuples.
This means that it defines what values are allowed
to be kept inside a particular column (attribute) for
a table.
• The domain constraint specifies that the value of an
attribute must be an atomic value in its own
domain.
• Domain constraint defines the domain or set of values for an attribute.
• It specifies that the value taken by the attribute must be the atomic
value from its domain. Example- Consider the following Student table-
STU_ID Name Age
S001 Akshay 20
S002 Abhishek 21
S003 Shashank 20
S004 Rahul A
• Here, value ‘A’ is not allowed since only integer values can be taken by
the age attribute.
Consider the following example table.
Student ID Student Name Marks (in %)
1 Guneet 90
2 Ahan 92
3 Yash 87
4 Lavish 90
5 Ashish 79
1 Guneet 90
2 Ahan 92
3 Yash 87
4 Lavish A
5 Ashish 79
• Now, in the table above, the tuple with Student ID = 4 and name =
“Lavish” has marks = A.
• This is not an integer or float value. So, the domain constraint is
violated here.
Tuple Uniqueness Constraint- Tuple
Uniqueness constraint specifies that all the tuples must be
necessarily unique in any relation.
• Consider the following Student table-
STU_ID Name Age
S001 Akshay 20
S002 Abhishek 21
S003 Shashank 20
S004 Rahul 20
• This relation satisfies the tuple uniqueness constraint since here all the
tuples are unique.
STU_ID Name Age
S001 Akshay 20
S001 Akshay 20
S003 Shashank 20
S004 Rahul 20
• This relation does not satisfy the tuple uniqueness constraint since
here all the tuples are not unique.
Key Constraint
• All the values of primary key must be unique.
• The value of primary key must not be null.
• Consider the following Student table
• This relation does not satisfy the key constraint as here all the values of
primary key are not unique.
Entity Integrity Constraints
• Entity integrity constraint specifies that no attribute of primary key must
contain a null value in any relation.
• This is because the presence of null value in the primary key violates the
uniqueness property.
• Example- Consider the following Student table
STU_ID Name Age
S001 Akshay 20
S002 Abhishek 21
S003 Shashank 20
Rahul 20
The relation ‘Student’ does not satisfy the referential integrity constraint.
This is because in relation ‘Department’, no value of primary key specifies department no. 14.
Relational Algebra
Relational Algebra
• Relational algebra is a procedural query language.
• It gives a step by step process to obtain the result of the query.
• It uses operators to perform queries.
• Relational Operators always work on one or more relational tables.
• Relational Operators always produce another relational table.
QUE- Write down the relational algebra for the employee table.
• Display EmpID with Name of all employee.
• Display Name and Salary of all employee.
• Display the Name of all employee. Employee
• Display the Name of all departments. EmpID Name Dept Salary
101 NILESH SALES 10000
Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 9
104 Meet CE 9
• Example :Display the detail of students belongs to either “CI”
or “ME” Branch.
Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 9
(Student)
σ
Answer : Branch=‘CI’ V Branch=‘ME’
Output
RollNo Name Branch SPI
102 Mitesh ME 9
103 Nilesh CI 9
Example: Display the detail of students whose SPI between
7 and 9.
Example
Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 9
STudent
RollNo
Employee Name Branch SPI
101 EmpID NameRaj Dept Salary CE 6
102 Meet ME 8
103 Harsh EE 7
104 Punit CE 9
Combined Projection & Selection Operation
Output-2
RollNo Name Branch
102 Mitesh ME
• Example Display Name, Branch and SPI of
students whose SPI is more than 8
Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 7 Answer :∏ Name, Branch, SPI
Step-1 σSPI>8 (Student) (
σSPI>8 (Student))
Output-
Output-1 2
RollNo Name Branch SPI Name Branch SPI
Mitesh ME 9
102 Mitesh ME 9
Nilesh CI 9
103 Nilesh CI 9
Que- Display Name of students along with their Branch who belong to either
“ME” Branch or “CI” Branch. Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 7
Student Result
RNo Name Branch RNo SPI
101 Raju CE 101 8
102 Mitesh ME 102 9
If both relations have some attribute with the same name, it can be
distinguished by combing relation-name.attribute-name.
EXAMPLE: Perform Cross Product between Student and Result with colums Rno.,
name, branch and Rno., SPI, BL
Student Result
RNo Name Branch Sem RNo SPI BL Rank
101 Raju CE 3 101 8 1 2
102 Mitesh ME 5 102 9 0 1
Output
• It displays all the tuples/records which are common from both relations
Answer(Customer) ∩ (Employee
Customer Employee
Name Name Output
Raju Meet Name
Meet
Suresh Suresh
Suresh
Meet Manoj
• Example: Display Name of person who are employee as well as customer.
Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000
Output
Name
Suresh
Minus/ Set difference Operators
• Example Display Name of person who are
customer but not employee
Customer Employee
ID Name Balance ID Name Dept Salary Output
1 Raju 10000 2 Suresh CE 8000 Name
2 Suresh 20000 3 Manoj ME 9000 Raju
Exercise :What is the output of following relational algebra for the below
mentioned tables:
Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000
High Performance:
SQL can handle large databases with millions of rows of data and complex queries efficiently.
Flexibility:
SQL can be used to query data from multiple tables using joins, subqueries, and unions, providing flexibility in data retrieval.
Data Integrity:
SQL supports integrity constraints such as primary keys, foreign keys, and unique constraints to maintain data accuracy and consistency.
Portability:
SQL is standardized by ANSI and ISO, making SQL code portable across different relational database management systems (RDBMS) with
minimal changes.
Security:
SQL provides robust security features, including user authentication, access control, and permissions to protect sensitive data.
Scalability:
SQL databases can scale vertically and horizontally to handle increasing data loads and user requests.
Data Manipulation:
SQL allows for efficient data manipulation operations such as inserting, updating, deleting, and merging data.
Transaction Control:
SQL supports transactions, ensuring that a series of operations are executed reliably and maintaining database consistency.
Built-in Functions:
SQL includes a wide range of built-in functions for mathematical calculations, string operations, date and time manipulation, and more.
Data Standardization:
SQL provides a standardized way to interact with databases, ensuring consistency in data management across different systems.
Ease of Use:
SQL is relatively easy to learn and use, even for users with little programming experience, due to its declarative nature and straightforward
syntax.
SQL data types and literals
1. Numeric Data Types:
A. INTEGER: 32 bit
Stores whole numbers without fractions.
Example: INTEGER, INT.
C. DECIMAL(p, s):
Stores fixed-point numbers with precision p and scale s.
Example: DECIMAL(10, 2).
D. NUMERIC(p, s):
E. FLOAT(p):
F. REAL:
A. CHAR(n):
Fixed-length character string of length n.
Example: CHAR(10).
B. VARCHAR(n):
Variable-length character string with a maximum length
of n.
Example: VARCHAR(255).
C. TEXT:
Variable-length character string with an unspecified
length.
Example: TEXT.
3. Date and Time Data Types:
A. DATE:
Stores date values (year, month, day).
Example: DATE.
B. TIME:
Stores time of day values (hour, minute, second).
Example: TIME.
C. TIMESTAMP:
Stores date and time values.
Example: TIMESTAMP.
D. INTERVAL:
Stores a time span.
Example: INTERVAL.
4. Binary Data Types:
A. BINARY:
Fixed-length binary data.
Example: BINARY(100).
B. VARBINARY:
Variable-length binary data with a maximum length.
Example: VARBINARY(255).
UPDATE Employees
SET Salary = 75000
WHERE EmployeeID = 1;
• Arithmetic operator
• Comparison operator
• Logical operator
• Bitwise Operators
• Compound Operators
SQL Arithmetic operator-
Arithmetic operator in SQL are used to perform mathematical operations on
numeric values in queries. Some common arithmetic operators are
Operator Description
The addition is used to perform an addition operation on the data
+ values.
Code- SELECT 10 + 5;
This operator is used for the subtraction of the data values.
–
Code- SELECT 10 - 5;
This operator works with the ‘ALL’ keyword and it calculates division
/ operations.
Code- SELECT 10 / 5;
This operator is used for multiplying data values.
*
Code- SELECT 10 * 5;
• SELECT 5 + 3; -- Result: 8
• SELECT 5 - 3; -- Result: 2
• SELECT 5 * 3; -- Result: 15
• SELECT 6 / 3; -- Result: 2
• SELECT 7 % 3; -- Result: 1
• Ex- find out the total salary of employee, like –
salary+TA+DA
SQL Comparison Operators- in SQL are used to
compare one expression’s value to other expressions. SQL
supports different types of comparison operator, which are
described below:
Operator Description
= Equal to.
> Greater than.
< Less than.
>= Greater than equal to.
<= Less than equal to.
<>, != Not equal to.
Examples of Comparison Operators-
Operator Description
| Bitwise OR operator
Bitwise XOR (exclusive OR) operator when both are different then
^ result 1 otherwise 0
ANY compares a value to each value in a list of results from a query and evaluates to true
ANY
if the result of an inner query contains at least one row.
The SQL BETWEEN operator tests an expression against a range. The range consists of a
BETWEEN
beginning, followed by an AND keyword and an end expression.
The IN operator checks a value within a set of values separated by commas and retrieves
IN
the rows from the table that match.
The EXISTS checks the existence of a result of a subquery. The EXISTS subquery tests
EXISTS whether a subquery fetches at least one row. When no data is returned then this operator
returns ‘FALSE’.
SOME operator evaluates the condition between the outer and inner tables and evaluates
SOME
to true if the final result returns any one row. If not, then it evaluates to false.
UNIQUE The UNIQUE operator searches every unique row of a specified table.
Example of Special Operators-
• SELECT * FROM employees WHERE salary BETWEEN
40000 AND 60000;
• Count()
• Sum()
• Avg()
• Min()
• Max()
1: Counting Employees by Department
– SELECT department_id, COUNT(*) AS employee_count
– FROM employees
– GROUP BY department_id;
2: Summing Salaries by Department
– SELECT department_id, SUM(salary) AS total_salary
– FROM employees
– GROUP BY department_id;
3: Finding the Average Salary by Job Title
– SELECT job_title, AVG(salary) AS average_salary
– FROM employees
– GROUP BY job_title;
4: Finding the Minimum and Maximum Salaries
by Department
– SELECT department_id, MIN(salary) AS min_salary,
MAX(salary) AS max_salary
– FROM employees
– GROUP BY department_id;
5: Concatenating Employee Names by
Department
– SELECT department_id, GROUP_CONCAT(name) AS
employee_names
– FROM employees
– GROUP BY department_id;
Joins in SQL
An INNER JOIN returns records that have matching values in both tables.
A LEFT JOIN (or LEFT OUTER JOIN) returns all records from the left
table (Employees), and the matched records from the right table
(Departments). The result is NULL from the right side if there is no match.
A RIGHT JOIN (or RIGHT OUTER JOIN) returns all records from the right table
(Departments), and the matched records from the left table (Employees). The result
is NULL from the left side when there is no match.
A FULL JOIN (or FULL OUTER JOIN) returns all records when there is a match in
either left (Employees) or right (Departments) table records. The result is NULL from the
side where there is no match.