0% found this document useful (0 votes)
22 views27 pages

DBMS Unit-2

It is data base management

Uploaded by

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

DBMS Unit-2

It is data base management

Uploaded by

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

Unit-2

Comparison Operators
A comparison (or relational) operator is a mathematical symbol which is used to compare two
values
Comparison operators are used in conditions that compares one expression with another.
Table: MATHS
SID SNAME SMARKS

101 Rahul 50

102 Ram 95

103 Harish 68

104 Santosh 79

105 Aarush 93

106 Aakash 76

he following table describes different types of comparison operators -


Operator Description Operates on

= Equal to. Any compatible data types

> Greater than. Any compatible data types

< Less than. Any compatible data types

>= Greater than equal to. Any compatible data types

<= Less than equal to. Any compatible data types

<> Not equal to. Any compatible data types


Demonstration of various Comparison Operators in SQL:
 Equal to (=) Operator: It returns the rows/tuples which have the value of the attribute
equal to the given value.
Query:
SELECT * FROM MATHS WHERE MARKS=50;

 Greater than (>) Operator: It returns the rows/tuples which have the value of the attribute
greater than the given value.
Query:
SELECT * FROM MATHS WHERE MARKS>60;

 Less than (<) Operator: It returns the rows/tuples which have the value of the attribute
lesser than the given value.
Query:
SELECT * FROM MATHS WHERE MARKS<40;

 Greater than or equal to (>=) Operator: It returns the rows/tuples which have the value
of the attribute greater or equal to the given value.
Query:
SELECT * FROM MATHS WHERE MARKS>=80;

 Less than or equal to (<=) Operator: It returns the rows/tuples which have the value of
the attribute lesser or equal to the given value.
Query:
SELECT * FROM MATHS WHERE MARKS<=30;

 Not equal to (<>) Operator: It returns the rows/tuples which have the value of the
attribute not equal to the given value.
Query:
SELECT * FROM MATHS WHERE MARKS<>70;

Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o Integrity constraints ensure that the data insertion, updating, and other processes have to
be performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the database.
Types of Integrity Constraint
1. Domain constraints
o Domain constraints can be defined as the definition of a valid set of values for an
attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc. The
value of the attribute must be available in the corresponding domain.
Example:

2. Entity integrity constraints


o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
o A table can contain a null value other than the primary key field.
Example:

3. Referential Integrity Constraints


o A referential integrity constraint is specified between two tables.
o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.
Example:

4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o An entity set can have multiple keys, but out of which one key will be the primary key. A
primary key can contain a unique and null value in the relational table.

Example:

OUTER JOIN
o In the outer JOIN, all the content from both the tables is integrated together.
o Even though the records from both the tables are matched or not, the matching and non-
matching records from both the tables will be considered an output of the outer join in
SQL.
o There are three different types of outer join in SQL:
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join

o 1. Left Outer Join: The left join operation returns all record from left table and
matching records from the right table. On a matching element not found in right table,
NULL is represented in that case.

o Syntax :
o SELECT column_name(s)
o FROM table1
o LEFT JOIN Table2
o ON Table1.Column_Name=table2.column_name;

o SELECT Customers.customer_id, Customers.first_name, Orders.amount


o FROM Customers
o LEFT JOIN Orders
o ON Customers.customer_id = Orders.customer;
o 2. Right Outer Join: The right join operation returns all record from right table and
matching records from the left table. On a matching element not found in left table,
NULL is represented in that case.

o
o Syntax :
o SELECT column_name(s)
o FROM table1
o RIGHT JOIN table2
o ON table1.column_name = table2.column_name;

SELECT Customers.customer_id, Customers.first_name, Orders.amount


FROM Customers
RIGHT JOIN Orders
ON Customers.customer_id = Orders.customer;
o 3. Full Outer Join: The full outer Join keyword returns all records when there is a
match in left or right table records.
o
o Syntax:
o SELECT column_name
o FROM table1
o FULL OUTER JOIN table2
o ON table1.columnName = table2.columnName
o WHERE condition;

SELECT Customers.customer_id, Customers.first_name, Orders.amount


FROM Customers
FULL OUTER JOIN Orders
ON Customers.customer_id = Orders.customer;
SQL Aggregate Functions
o SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
o It is also used to summarize the data.
Types of SQL Aggregation Function
o Now let us understand each Aggregate function with a example:
o Id Name Salary
o -----------------------
o 1 A 80
o 2 B 40
o 3 C 60
o 4 D 70
o 5 E 60
o 6 F Null
o

1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
o
o
o Count(*): Returns total number of records .i.e 6.
Count(salary): Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null values over the column
salary .i.e 4
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
sum(salary): Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Avg():

Avg(salary) = Sum(salary) / count(salary) = 310/5


Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250

4. MAX Function
MAX function is used to find the maximum value of a certain column. This function determines
the largest value of all selected values of a column
Max(salary): Maximum value in the salary i.e., 80.

5. MIN Function
MIN function is used to find the minimum value of a certain column. This function determines
the smallest value of all selected values of a column.
Min(salary): Minimum value in the salary column except NULL i.e., 40.

Logical operators or Logical Connectives


SQL logical operators are used to test for the truth of the condition. A logical operator like
the Comparison operator returns a boolean value of TRUE, FALSE, or UNKNOWN.
Given below is the list of logical operators available in SQL.

Operator Meaning

AND TRUE if both Boolean expressions are TRUE.

IN TRUE if the operand is equal to one of a list of expressions.

NOT Reverses the value of any other Boolean operator.

OR TRUE if either Boolean expression is TRUE.

LIKE TRUE if the operand matches a pattern.

BETWEEN TRUE if the operand is within a range.


ALL TRUE if all of a set of comparisons are TRUE.

ANY TRUE if any one of a set of comparisons is TRUE.

EXISTS TRUE if a subquery contains any rows.

SOME TRUE if some of a set of comparisons are TRUE.

Consider employee table

AND Operator
Query :
SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country = 'India';

IN Operator
Query:
SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');
NOT Operator
Query:
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';

OR Operator
Query:
SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country = 'India';

LIKE Operator
Query:
SELECT * FROM employee WHERE emp_city LIKE 'P%';
BETWEEN Operator
Query:
SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;

ALL Operator
Query:
SELECT * FROM employee WHERE emp_id = ALL
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');

ANY Operator
Query:
SELECT * FROM employee WHERE emp_id = ANY
(SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');

EXISTS Operator
Query:
SELECT emp_name FROM employee WHERE EXISTS
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');

SOME Operator
Query:
SELECT * FROM employee WHERE emp_id < SOME
(SELECT emp_id FROM employee WHERE emp_city = 'Patna');

Trigger and active data bases


A trigger is a stored procedure in database which automatically invokes whenever a special
event in the database occurs. For example, a trigger can be invoked when a row is inserted into
a specified table or when certain table columns are being updated.

Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]

Example:
Given Student Report Database, in which student marks assessment is recorded. In such
schema, create a trigger so that the total and percentage of specified marks is automatically
inserted whenever a record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used.
Suppose the database Schema –
mysql> desc Student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| sid | int(4) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
| subj1 | int(2) | YES | | NULL | |
| subj2 | int(2) | YES | | NULL | |
| subj3 | int(2) | YES | | NULL | |
| total | int(3) | YES | | NULL | |
| per | int(3) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)

SQL Trigger to problem statement.


create trigger stud_marks
before INSERT
on
Student
for each row
set Student.total = Student.subj1 + Student.subj2 + Student.subj3, Student.per = Student.total *
100 / 150;

Above SQL statement will create a trigger in the student database in which whenever subjects
marks are entered, before inserting this data into the database, trigger will compute those two
values and insert with the entered values. i.e.
mysql> insert into Student values(0, "ABCDE", 20, 20, 20, 0, 0);
Query OK, 1 row affected (0.09 sec)

mysql> select * from Student;

+-----+-------+-------+-------+-------+-------+------+
| sid | name | subj1 | subj2 | subj3 | total | per |
+-----+-------+-------+-------+-------+-------+------+
| 100 | ABCDE | 20 | 20 | 20 | 60 | 40 |
+-----+-------+-------+-------+-------+-------+------+
1 row in set (0.00 sec)
In this way trigger can be creates and executed in the databases.

Keys in SQL
o Keys play an important role in the relational database.
o It 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:
1. Primary key
o It is the first key used to identify one and only one instance of an entity uniquely. An
entity can contain multiple keys, as we saw in the PERSON table. The key which is most
suitable from those lists becomes a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for each employee.
In the EMPLOYEE table, we can even select License_Number and Passport_Number as
primary keys since they are also unique.
o For each entity, the primary key selection is based on requirements and developers.

2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
o Except for the primary key, the remaining attributes are considered a candidate key. The
candidate keys are as strong as the primary key.
For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of the
attributes, like SSN, Passport_Number, License_Number, etc., are considered a candidate key.
3. Super Key
Super key is an attribute set that can uniquely identify a tuple. A super key is a superset of a
candidate key.

For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the


name of two employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this
combination can also be a key.
The super key would be EMPLOYEE-ID (EMPLOYEE_ID, EMPLOYEE-NAME), etc.
4. Foreign key
o Foreign keys are the column of the table used to point to the primary key of another table.
o Every employee works in a specific department in a company, and employee and
department are two different entities. So we can't store the department's information in
the employee table. That's why we link these two tables through the primary key of one
table.
o We add the primary key of the DEPARTMENT table, Department_Id, as a new attribute
in the EMPLOYEE table.
o In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are
related.

5. Alternate key
There may be one or more attributes or a combination of attributes that uniquely identify each
tuple in a relation. These attributes or combinations of the attributes are called the candidate
keys. One key is chosen as the primary key from these candidate keys, and the remaining
candidate key, if it exists, is termed the alternate key. In other words, the total number of the
alternate keys is the total number of candidate keys minus the primary key. The alternate key
may or may not exist. If there is only one candidate key in a relation, it does not have an alternate
key.
For example, employee relation has two attributes, Employee_Id and PAN_No, that act as
candidate keys. In this relation, Employee_Id is chosen as the primary key, so the other candidate
key, PAN_No, acts as the Alternate key.

6. Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite key.
This key is also known as Concatenated Key.

For example, in employee relations, we assume that an employee may be assigned multiple
roles, and an employee may work on multiple projects simultaneously. So the primary key will
be composed of all three attributes, namely Emp_ID, Emp_role, and Proj_ID in combination. So
these attributes act as a composite key since the primary key comprises more than one attribute.

1. CREATE TABLE STUDENT_DETAIL (


2. Roll_no int NOT NULL PRIMARY KEY,
3. Name varchar (200) NOT NULL,
4. Marks int NOT NULL
5. } ;
Views in SQL
1. Views in SQL are kind of virtual tables.
2. A view also has rows and columns as they are in a real table in the database.
3. We can create a view by selecting fields from one or more tables present in the
database.
4. A View can either have all the rows of a table or specific rows based on certain
condition

We can create View using CREATE VIEW statement. A View can be created from a single
table or multiple tables.

Syntax:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows

StudentDetails

Examples:

Creating View from a single table:

SQL>CREATE VIEW DetailsView AS


SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
SQL>SELECT * FROM DetailsView;
Output:

What is MySQL?
 MySQL is a relational database management system
 MySQL is open-source
 MySQL is free
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, scalable, and easy to use
 MySQL is cross-platform
 MySQL is compliant with the ANSI SQL standard
 MySQL was first released in 1995
 MySQL is developed, distributed, and supported by Oracle Corporation

Nested query
A nested query is a query that has another query embedded within it. The
embedded query is called a sub query.
A sub query typically appears within the WHERE clause of a query. It can
sometimes appear in the FROM clause or HAVING clause.
1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );

Example

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY


1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

Destroying /altering tables


SQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example: ALTER TABLE Customers


ADD Email varchar(255);

ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax

ALTER TABLE table_name


DROP COLUMN column_name;

Example
ALTER TABLE Customers
DROP COLUMN Email;

ALTER TABLE - MODIFY COLUMN

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

Example

ALTER TABLE Customers


MODIFY COLUMN Email varchar(100);

TRUNCATE: Used to delete all the rows from the table


Syntax:
TRUNCATE TABLE Table_Name;
TRUNCATE TABLE customers;

RENAME: Used to change the name of a table


RENAME TABLE Old_Table_Name TO New_Table_Name;
Example:
RENAME TABLE Customers to Customers12;

DROP: Used to drop or delete entire table


Syntax:
DROP TABLE Table_Name;
Example:
DROP TABLE Customers12;

Enforcing Integrity Constraints


There are several ways to enforce integrity constraints in a DBMS:
 Declarative referential integrity: This method involves specifying the integrity
constraints at the time of database design and allowing the DBMS to enforce them
automatically.
 Triggers: A trigger is a special type of stored procedure that is executed automatically by
the DBMS when certain events occur (such as inserting, updating, or deleting data).
Triggers can be used to enforce integrity constraints by checking for and rejecting invalid
data.
 Stored procedures: A stored procedure is a pre-defined set of SQL statements that can
be executed as a single unit. Stored procedures can be used to enforce integrity
constraints by performing checks on the data before it is inserted, updated, or deleted.
 Application-level code: Integrity constraints can also be enforced at the application level
by writing code to check for and reject invalid data before it is entered into the database.
It is important to carefully consider the appropriate method for enforcing integrity constraints in
a DBMS in order to ensure the accuracy and consistency of the data.

NULL VALUE
The term NULL in SQL is used to specify that a data value does not exist in the
database. It is not the same as an empty string or a value of zero, and it signifies the
absence of a value or the unknown value of a data field.

Syntax
The basic syntax of NULL while creating a table.

SQL> CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Importance of NULL Value


 It is important to understand that a NULL value differs from a zero value.
 A NULL value is used to represent a missing value, but it usually has one of three
different interpretations:
 The value unknown (value exists but is not known)
 Value not available (exists but is purposely withheld)
 Attribute not applicable (undefined for this tuple)

You might also like