0% found this document useful (0 votes)
32 views29 pages

DBMS QB IA2 Ans

Good knowledge will be gained by this Mzmmzmzmzmz

Uploaded by

Lakshmi pathi
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)
32 views29 pages

DBMS QB IA2 Ans

Good knowledge will be gained by this Mzmmzmzmzmz

Uploaded by

Lakshmi pathi
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/ 29

MOD3

1.List and explain different datatypes in SQL

Numeric Data Types

1. INT or INTEGER:
o Stores whole numbers without fractions. The range can vary depending on the
implementation (e.g., INT in MySQL can store values from -2,147,483,648 to
2,147,483,647).
o Example: 42, -23
2. SMALLINT:
o Similar to INT but for smaller ranges. Typically used to save space when the
range of values is known to be small.
o Example: 32000, -32000
3. BIGINT:
o Used for large integers that exceed the range of INT.
o Example: 9223372036854775807, -9223372036854775808
4. DECIMAL(p, s) or NUMERIC(p, s):
o Stores fixed-point numbers. p specifies the precision (total number of digits),
and s specifies the scale (number of digits to the right of the decimal point).
o Example: 123.45 (with p=5 and s=2)
5. FLOAT and REAL:
o Stores floating-point numbers. These are approximate-number data types,
which means they do not store exact values for many numbers.
o Example: 3.14159
6. DOUBLE:
o Similar to FLOAT but can store larger and more precise numbers.
o Example: 1.7976931348623157E+308

Character String Data Types

1. CHAR(n):
o Fixed-length character string. The length n specifies the number of characters.
o Example: 'SQL ' (with n=7)
2. VARCHAR(n) or VARCHAR2(n):
o Variable-length character string. The length n specifies the maximum number
of characters.
o Example: 'SQL' (with n=50)
3. TEXT:
o Used to store large variable-length character strings. Some databases do not
have a limit on the number of characters.
o Example: 'This is a long text string.'

Binary Data Types

1. BINARY(n):
o Fixed-length binary data. The length n specifies the number of bytes.
o Example: 01010101 (with n=8)
2. VARBINARY(n):
o Variable-length binary data. The length n specifies the maximum number of
bytes.
o Example: 01101000 (with n=16)
3. BLOB (Binary Large Object):
o Used to store large binary data, such as images or files.
o Example: 0100101010111110000101010101

Date and Time Data Types

1. DATE:
o Stores date values (year, month, and day).
o Example: 2023-06-12
2. TIME:
o Stores time values (hours, minutes, seconds).
o Example: 14:30:00
3. DATETIME:
o Stores both date and time values.
o Example: 2023-06-12 14:30:00
4. TIMESTAMP:
o Stores both date and time values, typically including a time zone.
o Example: 2023-06-12 14:30:00.123456
5. YEAR:
o Stores year values. Used in some databases like MySQL.
o Example: 2023

Boolean Data Type

1. BOOLEAN or BOOL:
o Stores true or false values.
o Example: TRUE, FALSE

Other Data Types

1. ENUM:
o Stores a list of predefined values. Each column can have one value from the
list.
o Example: ENUM('small', 'medium', 'large')
2. SET:
o Similar to ENUM, but a column can have multiple values from the predefined
list.
o Example: SET('a', 'b', 'c')
3. UUID:
o Stores universally unique identifiers.
o Example: 550e8400-e29b-41d4-a716-446655440000
4. JSON:
o Stores JSON-formatted data.
o Example: {"key1": "value1", "key2": "value2"}
5. XML:
o Stores XML-formatted data.
o Example: <note><to>User</to><from>GPT</from></note>

Understanding these data types and their appropriate use is crucial for designing efficient and
effective database schemas.

2.Explain the following constructs used in SQL with example:


(i)Nested queries ii)Aggregate functions

Nested queries, also known as subqueries, are queries placed inside another query. They can
be used in various parts of an SQL statement, including the SELECT, FROM, WHERE, and
HAVING clauses. Subqueries can help break down complex queries into simpler parts and
can be correlated or non-correlated.

Example 1: Subquery in the SELECT Clause

SELECT employee_id,
(SELECT department_name
FROM departments
WHERE departments.department_id = employees.department_id) AS
department_name
FROM employees;

(ii) Aggregate Functions

Aggregate functions perform calculations on multiple rows of a single column and return a
single value. They are often used with the GROUP BY clause to group rows that have the
same values in specified columns.

Example 1: COUNT()

Count the number of employees in the employees table:

SELECT COUNT(*) AS total_employees


FROM employees;

This query returns the total number of rows (employees) in the employees table.

Example 2: SUM()

Calculate the total salary of all employees:

SELECT SUM(salary) AS total_salary


FROM employees;

This query sums up the salary column for all rows in the employees table.
Example 3: AVG()

Find the average salary of employees:

SELECT AVG(salary) AS average_salary


FROM employees;

This query calculates the average value of the salary column for all employees.

Example 4: MAX() and MIN()

Find the highest and lowest salaries:


A
SELECT MAX(salary) AS highest_salary, MIN(salary) AS lowest_salary
FROM employees;

This query returns the highest and lowest values in the salary column.

Example 5: GROUP BY with Aggregate Functions

Find the total salary for each department:

SELECT department_id, SUM(salary) AS total_salary


FROM employees
GROUP BY department_id;

This query groups the rows by department_id and then calculates the total salary for each
department.

3.Consider the following COMPANY database


EMP(FName,Minit, Lname,SSN, Bdate,Address,Sex,Salary,SuperSSN,Dno)
DEPT(DNum,Dname,MgrSSN,Dno) DEPT_LOC(Dnum,Dlocation)
DEPENDENT(ESSN,Dep_name,Sex,Bdate) WORKS_ON(ESSN,Pno,Hours)
PROJECT(Pname,Pnumber,Plocation,Dnum)
a. Retrieve the birthdate and address of the employee whose name is 'John B. Smith'.
b. Retrieve the name and address of all employees who work for the 'Research'
department.
c. For each employee, retrieve the employee's name, and the name of his or her
immediate supervisor.
d. Retrieve all employees whose address is in B’lore.
Show the resulting salaries if every employee working on the 'ProductX' project is given a 10
percent raise.

a. Retrieve the birthdate and address of the employee whose name is 'John B.
Smith'.
SELECT Bdate, Address
FROM EMP
WHERE FName = 'John' AND Minit = 'B' AND Lname = 'Smith';

b. Retrieve the name and address of all employees who work for the
'Research' department.
SELECT E.FName, E.Minit, E.Lname, E.Address
FROM EMP E
JOIN DEPT D ON E.Dno = D.Dnum
WHERE D.Dname = 'Research';

c. For each employee, retrieve the employee's name, and the name of his or
her immediate supervisor.
SELECT E1.FName AS EmployeeFirstName, E1.Minit AS EmployeeMinit, E1.Lname
AS EmployeeLastName,
E2.FName AS SupervisorFirstName, E2.Minit AS SupervisorMinit,
E2.Lname AS SupervisorLastName
FROM EMP E1
LEFT JOIN EMP E2 ON E1.SuperSSN = E2.SSN;

d. Retrieve all employees whose address is in B’lore.


SELECT FName, Minit, Lname, Address
FROM EMP
WHERE Address LIKE '%B’lore%';

Show the resulting salaries if every employee working on the 'ProductX'


project is given a 10 percent raise.
SELECT E.FName, E.Minit, E.Lname, E.Salary,
E.Salary * 1.10 AS NewSalary
FROM EMP E
JOIN WORKS_ON W ON E.SSN = W.ESSN
JOIN PROJECT P ON W.Pno = P.Pnumber
WHERE P.Pname = 'ProductX';

These queries retrieve the specified data from the COMPANY database based on the
conditions provided.

4. Explain the following constructs used in SQL with example:


(i)DROP Command ii)ALTER TABLE Command

(i) DROP Command

The DROP command is used to delete objects from the database. The most common use of the
DROP command is to remove tables, but it can also be used to delete other database objects
such as databases, indexes, views, and triggers.
Example 1: Drop a Table

DROP TABLE employees;

This command deletes the employees table from the database, including all its data and
structure.

Example 2: Drop a Database

DROP DATABASE company;

This command deletes the company database along with all its tables, views, and other
objects.

Example 3: Drop an Index

DROP INDEX idx_employee_name ON employees;

This command deletes the index named idx_employee_name on the employees table.

Example 4: Drop a View

DROP VIEW employee_view;

This command deletes the view named employee_view.

Example 5: Drop a Trigger

DROP TRIGGER trg_update_salary;

This command deletes the trigger named trg_update_salary.

(ii) ALTER TABLE Command

The ALTER TABLE command is used to modify an existing table structure. It can be used to
add, delete, or modify columns, and to add or drop constraints.

Example 1: Add a Column

ALTER TABLE employees


ADD COLUMN email VARCHAR(255);

This command adds a new column email of type VARCHAR(255) to the employees table.

Example 2: Drop a Column

ALTER TABLE employees


DROP COLUMN email;

This command removes the email column from the employees table.
Example 3: Modify a Column

ALTER TABLE employees


MODIFY COLUMN salary DECIMAL(10, 2);

This command changes the data type of the salary column to DECIMAL(10, 2) in the
employees table.

Example 4: Add a Constraint

ALTER TABLE employees


ADD CONSTRAINT fk_department
FOREIGN KEY (department_id) REFERENCES departments(department_id);

This command adds a foreign key constraint fk_department to the employees table,
referencing the department_id column in the departments table.

Example 5: Drop a Constraint

ALTER TABLE employees


DROP CONSTRAINT fk_department;

This command removes the foreign key constraint fk_department from the employees
table.

5.Consider the schema for College Database:

STUDENT (USN, SName, Address, Phone, Gender)


SEMSEC (SSID, Sem, Sec)
CLASS (USN, SSID)
SUBJECT (Subcode, Title, Sem, Credits)
IAMARKS (USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)
Make use of SQL queries to
List all the student details studying in fourth semester ‘C’ section.
Compute the total number of male and female students in each semester and in each section.
Create a view of Test1 marks of student USN ‘1BI15CS101’ in all subjects.
Calculate the FinalIA (average of best two test marks) and update the corresponding table for
all students.

1. List all the student details studying in fourth semester ‘C’ section.
SELECT S.*
FROM STUDENT S
JOIN CLASS C ON S.USN = C.USN
JOIN SEMSEC SS ON C.SSID = SS.SSID
WHERE SS.Sem = 4 AND SS.Sec = 'C';

2. Compute the total number of male and female students in each semester
and in each section.
SELECT SS.Sem, SS.Sec, S.Gender, COUNT(*) AS Total
FROM STUDENT S
JOIN CLASS C ON S.USN = C.USN
JOIN SEMSEC SS ON C.SSID = SS.SSID
GROUP BY SS.Sem, SS.Sec, S.Gender
ORDER BY SS.Sem, SS.Sec, S.Gender;

3. Create a view of Test1 marks of student USN ‘1BI15CS101’ in all subjects.


CREATE VIEW Test1Marks_1BI15CS101 AS
SELECT I.USN, I.Subcode, I.Test1
FROM IAMARKS I
WHERE I.USN = '1BI15CS101';

4. Calculate the FinalIA (average of best two test marks) and update the
corresponding table for all students.

First, calculate the FinalIA:

UPDATE IAMARKS
SET FinalIA = (
SELECT ROUND((GREATEST(Test1, Test2, Test3) +
LEAST(GREATEST(Test1, Test2), GREATEST(Test1, Test3),
GREATEST(Test2, Test3))) / 2.0, 2)
)

5.Write about the constraints in SQL.

1. NOT NULL Constraint

The NOT NULL constraint ensures that a column cannot have a NULL value. This constraint is
useful when you need to make sure that a particular field always contains a value.

Example:

CREATE TABLE STUDENT (


USN VARCHAR(10) NOT NULL,
SName VARCHAR(50) NOT NULL,
Address VARCHAR(255),
Phone VARCHAR(15),
Gender CHAR(1)
);
2. UNIQUE Constraint

The UNIQUE constraint ensures that all the values in a column are different. It prevents
duplicate values in a column or a combination of columns.
Example:

CREATE TABLE SUBJECT (


Subcode VARCHAR(10) UNIQUE,
Title VARCHAR(100),
Sem INT,
Credits INT
);
3. PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table. A primary key column
must contain unique values and cannot contain NULL values. Each table can have only one
primary key, which can consist of single or multiple columns (composite key).

Example:

CREATE TABLE SEMSEC (


SSID INT PRIMARY KEY,
Sem INT,
Sec CHAR(1)
);
4. FOREIGN KEY Constraint

The FOREIGN KEY constraint is a key used to link two tables together. It ensures the
referential integrity of the data in one table to match values in another table. The foreign key
in the child table points to the primary key in the parent table.

Example:

CREATE TABLE CLASS (


USN VARCHAR(10),
SSID INT,
FOREIGN KEY (USN) REFERENCES STUDENT(USN),
FOREIGN KEY (SSID) REFERENCES SEMSEC(SSID)
);
5. CHECK Constraint

The CHECK constraint ensures that all values in a column satisfy a specific condition. It can be
used to enforce domain integrity by limiting the values that can be placed in a column.

Example:

CREATE TABLE IAMARKS (


USN VARCHAR(10),
Subcode VARCHAR(10),
SSID INT,
Test1 INT CHECK (Test1 BETWEEN 0 AND 100),
Test2 INT CHECK (Test2 BETWEEN 0 AND 100),
Test3 INT CHECK (Test3 BETWEEN 0 AND 100),
FinalIA INT
);
6. DEFAULT Constraint

The DEFAULT constraint provides a default value for a column when no value is specified for
that column.

Example:

CREATE TABLE STUDENT (


USN VARCHAR(10) NOT NULL,
SName VARCHAR(50) NOT NULL,
Address VARCHAR(255),
Phone VARCHAR(15),
Gender CHAR(1),
EnrollmentDate DATE DEFAULT CURRENT_DATE
);

MOD4
1. Explain insertion, deletion and updation anomalies. Why are they considered bad?
Illustrate with example

1. Insertion Anomalies

Definition: An insertion anomaly occurs when certain attributes cannot be inserted into the
database without the presence of other attributes.

Why it's bad: This can prevent the addition of new data and lead to incomplete records. It
forces unnecessary dependencies between data entries.

Example: Suppose we have a table Employee with the following columns: EmployeeID,
EmployeeName, DepartmentID, and DepartmentName.

EmployeeID EmployeeName DepartmentID DepartmentName

1 Alice 101 Sales

2 Bob 102 HR

If a new department needs to be added but no employee has been assigned to it yet, we
cannot add just the DepartmentID and DepartmentName without leaving the EmployeeID
and EmployeeName columns empty, which is not allowed if they are defined as NOT NULL.

2. Deletion Anomalies

Definition: A deletion anomaly occurs when deleting a record results in the loss of other
valuable data that should be retained.

Why it's bad: It can lead to unintentional loss of data, causing data integrity issues.
Example: Using the same Employee table, if we delete the record of an employee who is the
only one associated with a particular department, we also lose the information about that
department.

EmployeeID EmployeeName DepartmentID DepartmentName

1 Alice 101 Sales

2 Bob 102 HR

If Bob leaves the company and we delete his record, we lose the information that department
HR exists unless there are other employees associated with it.

3. Updation Anomalies

Definition: An updation anomaly occurs when one or more instances of duplicated data are
updated, but not all instances are updated consistently.

Why it's bad: This leads to inconsistent data within the database, which can result in
inaccurate and unreliable information.

Example: In the same Employee table, if the DepartmentName for DepartmentID 101
changes from "Sales" to "Marketing," every record associated with DepartmentID 101 needs
to be updated.

EmployeeID EmployeeName DepartmentID DepartmentName

1 Alice 101 Sales

3 Carol 101 Sales

If we update Alice's record but forget to update Carol's record, we end up with inconsistent
data:

EmployeeID EmployeeName DepartmentID DepartmentName

1 Alice 101 Marketing

3 Carol 101 Sales

Normalization to Prevent Anomalies

Normalization is the process of organizing a database to reduce redundancy and improve data
integrity. By applying normalization techniques (such as creating separate tables for
Employees and Departments), we can avoid these anomalies.
Example of Normalized Tables:

Employees Table

EmployeeID EmployeeName DepartmentID

1 Alice 101

2 Bob 102

Departments Table

DepartmentID DepartmentName

101 Sales

102 HR

2.Explain different types Functional Dependencies.

A functional dependency, denoted by X→, between two sets of attributes X and Y in a relation RRR,
indicates that if two tuples (rows) of R have the same values for attributes in X, they must also have
the same values for attributes in Y. Here, X is called the determinant, and Y is the dependent.

1. Trivial Functional Dependency

Definition: A functional dependency is trivial if the right-hand side (RHS) is a subset of the
left-hand side (LHS).

Example:

• {A,B}→A
• {A,B}→B

In these cases, A and B are trivially dependent on the set {A, B}.

2. Non-Trivial Functional Dependency

Definition: A functional dependency is non-trivial if the RHS is not a subset of the LHS.

Example:

• A→B
• {A,B}→C

Here, B is not a part of A, and C is not a part of {A, B}, making these dependencies
non-trivial.
3. Completely Non-Trivial Functional Dependency

Definition: A functional dependency is completely non-trivial if the LHS and RHS have no
attributes in common.

Example:

• A→BA
• {A,C}→D

Here, A has no common attributes with B, and {A, C} has no common attributes with D.

4. Multivalued Dependency

Definition: A multivalued dependency exists when one attribute in a table uniquely


determines another attribute, but not necessarily the other way around, and this dependency is
represented by two sets of attributes.

Example:

• A↠B

If we have a table with attributes A,B,A, B,A,B, and CCC, A↠B means that for each value of
A, there is a set of values for B that is independent of C.

5. Transitive Dependency

Definition: A transitive dependency exists when a non-prime attribute depends on another


non-prime attribute indirectly through other non-prime attributes.

Example:

• A→BA and B→CB implies A→C

In a table with attributes A, B, and C, if A determines B and B determines C, then A


indirectly determines C.

6. Partial Dependency

Definition: A partial dependency occurs when a non-prime attribute is functionally


dependent on part of a candidate key.

Example:

• Consider a table with attributes {A, B, C} where {A, B} is a candidate key. If A→C,
then C is partially dependent on the candidate key {A, B}.

7. Full Dependency
Definition: A full dependency exists when a non-prime attribute is functionally dependent on
the entire candidate key, not just part of it.

Example:

• In a table with attributes {A, B, C} where {A, B} is a candidate key, if {A,B}→C,


then C is fully dependent on the candidate key {A, B}.

8. Join Dependency

Definition: A join dependency exists when a table can be decomposed into multiple tables,
and the original table can be recreated by joining these tables without any loss of information.

Example:

• If a table R(A,B,C)R(A, B, C)R(A,B,C) can be decomposed into R1(A,B)R1(A,


B)R1(A,B) and R2(B,C)R2(B, C)R2(B,C) such that joining R1R1R1 and R2R2R2 on
B gives back R(A,B,C)R(A, B, C)R(A,B,C), then RRR has a join dependency.

9. Equivalence Dependency

Definition: An equivalence dependency exists when two sets of attributes determine each
other.

Example:

• If A→BA and B→AB, then A and B are equivalently dependent on each other.

3.Find the closure of A,B,C,D given R(A,B,C,D)FD : {A->B,B->D,C->B}

4.Explain 1NF,2NF,3NF with example

First Normal Form (1NF)

A table is in the first normal form if:

1. All the values in the columns are atomic (indivisible).


2. Each column contains only one value per row.
3. All entries in a column are of the same data type.
4. Each column has a unique name.
5. The order in which data is stored does not matter.

Example: Consider a table that stores information about students and their courses:
StudentID StudentName Courses
1 Alice Math, Science
2 Bob History

This table is not in 1NF because the Courses column contains multiple values.

1NF Conversion: Split the Courses column so that each cell contains only one value.

StudentID StudentName Course


1 Alice Math
1 Alice Science
2 Bob History

Now, each column contains only atomic values.

Second Normal Form (2NF)

A table is in the second normal form if:

1. It is in 1NF.
2. All non-key attributes are fully functionally dependent on the primary key. This
means that there are no partial dependencies of any column on the primary key.

Example: Consider the table in 1NF:

StudentID StudentName Course Instructor


1 Alice Math Dr. Smith
1 Alice Science Dr. Johnson
2 Bob History Dr. Brown

Assume StudentID and Course together form the primary key. The StudentName attribute is
partially dependent on StudentID only, not on the combination of StudentID and Course.

2NF Conversion: Create separate tables to eliminate partial dependencies.

Students Table:

StudentID StudentName
1 Alice
2 Bob

Courses Table:

StudentID Course Instructor


1 Math Dr. Smith
StudentID Course Instructor
1 Science Dr. Johnson
2 History Dr. Brown

Third Normal Form (3NF)

A table is in the third normal form if:

1. It is in 2NF.
2. All the attributes are functionally dependent only on the primary key. This means
there are no transitive dependencies.

Example: Consider the Courses table from 2NF:

StudentID Course Instructor InstructorPhone


1 Math Dr. Smith 123-456-7890
1 Science Dr. Johnson 987-654-3210
2 History Dr. Brown 555-555-5555

Here, InstructorPhone is dependent on Instructor, not directly on the primary key


(StudentID and Course).

3NF Conversion: Create another table for instructors to eliminate transitive dependencies.

Courses Table:

StudentID Course Instructor


1 Math Dr. Smith
1 Science Dr. Johnson
2 History Dr. Brown

Instructors Table:

Instructor InstructorPhone
Dr. Smith 123-456-7890
Dr. Johnson 987-654-3210
Dr. Brown 555-555-5555

Summary

• 1NF: Eliminate repeating groups; ensure atomicity.


• 2NF: Remove partial dependencies; ensure full functional dependency on the primary
key.
• 3NF: Remove transitive dependencies; ensure non-key attributes depend only on the
primary key.
5.For the above given company database in Qn 2a
a. List the names of managers who have at least one dependent.
b. For each department, retrieve the department number, the number of employees in the
department, and their average salary.
a. List the names of managers who have at least one dependent.

Assuming we have the following schema:

• Employee: (Emp_ID, emp_name, Salary, Dept_ID, Manager_ID)


• Dependent: (Dep_ID, Emp_ID, Dependent_name, Relationship)

The query to list the names of managers who have at least one dependent would look like
this:

SELECT DISTINCT E.emp_name AS ManagerName


FROM Employee E
JOIN Dependent D ON E.Emp_ID = D.Emp_ID
WHERE E.Emp_ID IN (SELECT Manager_ID FROM Employee);

This query joins the Employee and Dependent tables, ensuring that the Emp_ID in the
Employee table matches the Emp_ID in the Dependent table and that the Emp_ID is also a
manager.

b. For each department, retrieve the department number, the number of employees in the
department, and their average salary.

Assuming we have the following schema:

• Employee: (Emp_ID, emp_name, Salary, Dept_ID, Manager_ID)


• Department: (Dept_ID, Dept_Name)

The query to retrieve the department number, the number of employees in the department,
and their average salary would look like this:

SELECT Dept_ID, COUNT(Emp_ID) AS NumberOfEmployees, AVG(Salary) AS


AverageSalary
FROM Employee
GROUP BY Dept_ID;

6.State and explain Armstrong Axioms/INFERENCE RULES

Armstrong's Axioms, also known as inference rules, are a set of rules used to infer all the
functional dependencies on a relational database. These axioms provide a complete and
sound basis for reasoning about functional dependencies. They are named after William W.
Armstrong, who introduced them in 1974. The axioms are essential for understanding how
functional dependencies can be derived and manipulated in database design.
Armstrong's Axioms

1. Reflexivity
2. Augmentation
3. Transitivity

In addition to these primary axioms, there are additional rules (sometimes considered
extensions or derived rules) that can be derived from these three axioms:

4. Union
5. Decomposition
6. Pseudotransitivity

1. Reflexivity

Definition: If Y is a subset of X, then X functionally determines Y.

Notation: If Y⊆X, then X→Y.

Example: If we have X={A,B} and Y={A} since {A}⊆{A,B}, it follows that {A,B}→{A}.

2. Augmentation

Definition: If X→Y , then XZ→YZ for any Z.

Notation: If X→Y, then XZ→YZ.

Example: If {A}→{B}then {A,C}→{B,C}

3. Transitivity

Definition: If X→Y and Y→Z, then X→Z.

Notation: If X→Y and Y→Z, then X→Z.

Example: If {A}→{B} and {B}→{C} then {A}→{C}

Derived Rules

4. Union

Definition: If X→Y and X→Z, then X→YZ.

Notation: If X→Y and X→Z, then X→YZ.

Example: If {A}→{B} and {A}→{C} then {A}→{B,C}

5. Decomposition
Definition: If X→YZ, then X→Y and X→Z.

Notation: If X→YZ, then X→Y and X→Z.

Example: If {A}→{B,C} , then {A}→{B}and {A}→{C}

6. Pseudotransitivity

Definition: If X→Y and WY→ZW, then WX→ZW.

Notation: If X→Y and WY→ZW, then WX→ZW.

Example: If {A}→{B} and {B,C}→{D}then {A,C}→{D}

Importance of Armstrong's Axioms

Armstrong's Axioms are fundamental for:

1. Deriving Functional Dependencies: They provide a systematic way to infer all


possible functional dependencies from a given set of dependencies.
2. Database Design and Normalization: They help in understanding and ensuring the
proper structure of databases, facilitating the normalization process.
3. Maintaining Data Integrity: They ensure that the inferred dependencies maintain the
consistency and integrity of the data within the database.

7.Discuss about the basic SQL Retrieval Queries with examples

SQL (Structured Query Language) is used to communicate with databases. It is the standard
language for relational database management systems. SQL statements are used to perform
tasks such as update data on a database or retrieve data from a database. Here are some basic
SQL retrieval queries with examples:

1. SELECT Statement

The SELECT statement is used to query the database and retrieve data from one or more
tables. The simplest form of a SELECT statement is:

SELECT column1, column2, ...


FROM table_name;

Example:

Retrieve the FirstName and LastName from the Employees table:

SELECT FirstName, LastName


FROM Employees;

2. SELECT * (All Columns)


To select all columns from a table, you can use the * wildcard character:

SELECT * FROM table_name;

Example:

Retrieve all columns from the Employees table:

SELECT * FROM Employees;

3. DISTINCT Keyword

The DISTINCT keyword is used to return only distinct (different) values.

Example:

Retrieve distinct job titles from the Employees table:

SELECT DISTINCT JobTitle


FROM Employees;

4. WHERE Clause

The WHERE clause is used to filter records that meet a certain condition.

Example:

Retrieve employees with the job title 'Manager':

SELECT FirstName, LastName


FROM Employees
WHERE JobTitle = 'Manager';

5. AND, OR, and NOT Operators

These operators are used to filter records based on more than one condition.

Examples:

Retrieve employees who are 'Managers' and work in the 'Sales' department:

SELECT FirstName, LastName


FROM Employees
WHERE JobTitle = 'Manager' AND Department = 'Sales';

Retrieve employees who are either 'Managers' or work in the 'Sales' department:

SELECT FirstName, LastName


FROM Employees
WHERE JobTitle = 'Manager' OR Department = 'Sales';

Retrieve employees who are not 'Managers':


SELECT FirstName, LastName
FROM Employees
WHERE NOT JobTitle = 'Manager';

6. ORDER BY Clause

The ORDER BY clause is used to sort the result-set in ascending or descending order. The
default order is ascending.

Examples:

Retrieve employees ordered by LastName in ascending order:

SELECT FirstName, LastName


FROM Employees
ORDER BY LastName ASC;

Retrieve employees ordered by LastName in descending order:

SELECT FirstName, LastName


FROM Employees
ORDER BY LastName DESC;

7. LIMIT Clause

The LIMIT clause is used to specify the number of records to return.

Example:

Retrieve the first 10 employees:

SELECT FirstName, LastName


FROM Employees
LIMIT 10;

8. LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

Examples:

Retrieve employees whose LastName starts with 'S':

SELECT FirstName, LastName


FROM Employees
WHERE LastName LIKE 'S%';

Retrieve employees whose FirstName ends with 'a':

SELECT FirstName, LastName


FROM Employees
WHERE FirstName LIKE '%a';
9. IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

Example:

Retrieve employees who work in the 'HR' or 'IT' departments:

SELECT FirstName, LastName


FROM Employees
WHERE Department IN ('HR', 'IT');

10. BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates.

Example:

Retrieve employees who were hired between '2020-01-01' and '2021-01-01':

SELECT FirstName, LastName, HireDate


FROM Employees
WHERE HireDate BETWEEN '2020-01-01' AND '2021-01-01';

11. Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value.
Common aggregate functions include COUNT, SUM, AVG, MAX, and MIN.

Examples:

Count the number of employees:

SELECT COUNT(*) AS NumberOfEmployees


FROM Employees;

Calculate the average salary of employees:

SELECT AVG(Salary) AS AverageSalary


FROM Employees;

Find the highest salary:

SELECT MAX(Salary) AS HighestSalary


FROM Employees;

12. GROUP BY Clause

The GROUP BY clause is used to group rows that have the same values into summary rows,
like "find the number of employees in each department".
Example:

Retrieve the number of employees in each department:

SELECT Department, COUNT(*) AS NumberOfEmployees


FROM Employees
GROUP BY Department;

13. HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.

Example:

Retrieve departments with more than 5 employees:

SELECT Department, COUNT(*) AS NumberOfEmployees


FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;

These are some of the basic SQL retrieval queries. They form the foundation of querying in
SQL, and mastering these will help you effectively interact with relational databases.

8.Consider the schema for Employee Database:


Employee (Emp_ID, emp_name, Salary, Dept_ID, Manager ID).
How to select unique records from a table?

Selecting Unique Records

1. Select Unique Records Based on a Single Column: If you want to select unique
values of a single column, you can use DISTINCT with that column.

Example: Retrieve unique department IDs from the Employee table:

SELECT DISTINCT Dept_ID


FROM Employee;

This query will return a list of unique Dept_ID values from the Employee table.

2. Select Unique Records Based on Multiple Columns: If you want to select unique
combinations of multiple columns, you can use DISTINCT with those columns.

Example: Retrieve unique combinations of emp_name and Salary from the Employee
table:

SELECT DISTINCT emp_name, Salary


FROM Employee;
This query will return unique combinations of emp_name and Salary, eliminating any
duplicate rows where both emp_name and Salary are the same.

3. Select All Unique Records: If you want to select all unique records considering all
columns, you can use DISTINCT with *.

Example: Retrieve all unique records from the Employee table:

SELECT DISTINCT *
FROM Employee;

This query will return all unique rows from the Employee table, considering every
column in the table.

9. Write about Informal design guidelines for relation schema.

Informal design guidelines for relation schema help ensure that the database is well-
structured, efficient, and easy to maintain. These guidelines address common issues such as
data redundancy, update anomalies, and integrity constraints. Here are some key informal
design guidelines for relation schemas:

1. Avoid Repetition and Redundancy

Guideline: Eliminate redundant data by ensuring that each piece of information is stored only
once.

Explanation: Redundant data can lead to inconsistencies and anomalies during insert,
update, and delete operations.

Example: Instead of storing the department name along with every employee record, store it
once in a separate Departments table.

2. Ensure Atomicity of Attributes

Guideline: Each attribute should represent a single atomic value, meaning that attributes
should be indivisible.

Explanation: This ensures that each attribute contains a single value, which simplifies
querying and updates.

Example: Instead of having a FullName attribute, use separate FirstName and LastName
attributes.

3. Use Meaningful Attribute Names

Guideline: Choose descriptive and meaningful names for attributes.

Explanation: This makes the schema easier to understand and maintain.


Example: Use EmployeeID instead of EID, or DateOfBirth instead of DOB.

4. Choose Appropriate Data Types

Guideline: Select data types that accurately represent the nature of the data and support
necessary operations.

Explanation: Using appropriate data types ensures data integrity and can improve
performance.

Example: Use DATE type for dates, VARCHAR for variable-length strings, and INT for integers.

5. Avoid Null Values

Guideline: Design schemas in such a way that null values are minimized.

Explanation: Null values can lead to complications in data interpretation and querying.
Where possible, use default values or restructure the schema to avoid nulls.

Example: Instead of allowing null in ManagerID, use a separate table to indicate which
employees are managers.

6. Ensure Referential Integrity

Guideline: Use foreign keys to maintain referential integrity between related tables.

Explanation: Referential integrity ensures that relationships between tables remain


consistent, preventing orphan records.

Example: In an Employees table, use DeptID as a foreign key to reference the primary key in
a Departments table.

7. Normalize to Reduce Update Anomalies

Guideline: Apply normalization principles to eliminate update anomalies by decomposing


tables appropriately.

Explanation: Normalization reduces redundancy and dependency, ensuring data consistency


and integrity.

Example: Decompose a table with employee and department information into two tables:
Employees and Departments.

8. Optimize for Performance

Guideline: Balance normalization with performance considerations by selectively


denormalizing if necessary.
Explanation: While normalization reduces redundancy, it can sometimes lead to complex
queries. Denormalization can improve performance for certain read-heavy operations.

Example: If queries frequently need to join multiple tables, consider denormalizing parts of
the schema to reduce join operations.

9. Ensure Logical Design

Guideline: Design the schema logically based on real-world entities and relationships.

Explanation: A logical design that closely mirrors the real-world scenario ensures that the
database is intuitive and easier to use.

Example: Create tables for Employees, Departments, and Projects if these are distinct
entities in the real world.

Example Scenario

Consider a simple employee database with the following informal design guidelines applied:

1. Avoid Repetition and Redundancy:


o Employees: EmpID, EmpName, DeptID, Salary
o Departments: DeptID, DeptName
2. Ensure Atomicity of Attributes:
o Employees: EmpID, FirstName, LastName, DeptID, Salary
o Departments: DeptID, DeptName
3. Use Meaningful Attribute Names:
o Use EmployeeID, FirstName, LastName, DepartmentID, DepartmentName.
4. Choose Appropriate Data Types:
o EmployeeID (INT), FirstName (VARCHAR), LastName (VARCHAR),
DepartmentID (INT), Salary (DECIMAL).
5. Avoid Null Values:
o Ensure DeptID is always filled by making it a required field.
6. Ensure Referential Integrity:
o DepartmentID in Employees references DepartmentID in Departments.
7. Normalize to Reduce Update Anomalies:
o Separate tables for Employees and Departments to avoid redundancy.
8. Optimize for Performance:
o If queries frequently need to know both employee and department details,
ensure proper indexing.
9. Ensure Logical Design:
o Tables clearly represent employees and departments as distinct entities.

Example SQL Schema


CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(100) NOT NULL
);
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
FirstName VARCHAR(100) NOT NULL,
LastName VARCHAR(100) NOT NULL,
DeptID INT,
Salary DECIMAL(10, 2),
FOREIGN KEY (DeptID) REFERENCES Departments(DeptID)
);

11.State and explain Null values in tuples

Null Values in Tuples

Null values in tuples (rows) in a relational database represent missing or unknown


information. They are used when the value of an attribute is either not applicable or unknown
at the time of data entry. Nulls can be a source of complexity in database operations because
they don't behave like regular values. Understanding how nulls work and how to handle them
is crucial for database design and querying.

Characteristics of Null Values

1. Representation: A null value is represented by the keyword NULL.


2. Data Type Compatibility: Null can be used in any column, regardless of its data type
(integer, varchar, date, etc.).
3. Three-Valued Logic: Null introduces three-valued logic (true, false, unknown) in
SQL, affecting conditions and comparisons.

Reasons for Null Values

1. Missing Information: The value is unknown at the time of data entry.


2. Inapplicable Information: The attribute does not apply to the row.
3. Optional Information: The attribute is optional and can be left blank.

Examples of Null Values

Consider a table Employee with columns EmpID, EmpName, Salary, and ManagerID:

EmpID EmpName Salary ManagerID


1 Alice 50000 NULL
2 Bob 60000 1
3 Carol NULL 2
4 Dave 70000 1

In this example:

• Alice has no manager (ManagerID is NULL).


• Carol's salary is unknown (Salary is NULL).

Handling Null Values in SQL


1. Comparisons Involving Null:
o NULL is not equal to any value, including another NULL.
o To check for NULL, use the IS NULL or IS NOT NULL operators.

SELECT * FROM Employee WHERE ManagerID IS NULL;

2. Null in Arithmetic and String Operations:


o Any arithmetic or string operation involving NULL results in NULL.

SELECT EmpName, Salary * 1.1 AS NewSalary FROM Employee;


-- Rows with NULL Salary will result in NULL NewSalary

3. Null in Aggregate Functions:


o Aggregate functions (SUM, AVG, COUNT, etc.) typically ignore NULL values.

SELECT AVG(Salary) FROM Employee;


-- Only considers rows where Salary is not NULL

4. Using COALESCE to Handle Nulls:


o The COALESCE function returns the first non-null value in its list of arguments.

SELECT EmpID, COALESCE(Salary, 0) AS Salary FROM Employee;


-- Replaces NULL Salary with 0

5. Conditional Expressions:
o Use CASE statements to handle null values conditionally.

SELECT EmpName,
CASE
WHEN Salary IS NULL THEN 'Unknown'
ELSE Salary
END AS Salary
FROM Employee;

Impact of Null Values on Database Operations

1. Select Queries: Special attention is needed when writing conditions involving null
values.
2. Insert/Update Operations: Need to handle nulls appropriately based on business
rules and constraints.
3. Joins: Null values can affect join operations, especially when using inner joins.

SELECT e.EmpName, m.EmpName AS ManagerName


FROM Employee e
LEFT JOIN Employee m ON e.ManagerID = m.EmpID;
-- Left join will include employees with NULL ManagerID

4. Indexes: Some database systems handle indexing of null values differently, which can
impact performance.

Best Practices for Handling Null Values


1. Design with Intent: Clearly define when null values are allowed and ensure they
represent meaningful absence of data.
2. Default Values: Use default values to avoid nulls when appropriate.
3. Documentation: Document the meaning of null values in each column for better
understanding and maintenance.
4. Consistent Handling: Ensure consistent handling of null values in application logic
and SQL queries.

You might also like