DBMS QB IA2 Ans
DBMS QB IA2 Ans
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
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.'
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
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
1. BOOLEAN or BOOL:
o Stores true or false values.
o Example: TRUE, FALSE
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.
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.
SELECT employee_id,
(SELECT department_name
FROM departments
WHERE departments.department_id = employees.department_id) AS
department_name
FROM employees;
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()
This query returns the total number of rows (employees) in the employees table.
Example 2: SUM()
This query sums up the salary column for all rows in the employees table.
Example 3: AVG()
This query calculates the average value of the salary column for all employees.
This query returns the highest and lowest values in the salary column.
This query groups the rows by department_id and then calculates the total salary for each
department.
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;
These queries retrieve the specified data from the COMPANY database based on the
conditions provided.
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
This command deletes the employees table from the database, including all its data and
structure.
This command deletes the company database along with all its tables, views, and other
objects.
This command deletes the index named idx_employee_name on the employees table.
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.
This command adds a new column email of type VARCHAR(255) to the employees table.
This command removes the email column from the employees table.
Example 3: Modify a Column
This command changes the data type of the salary column to DECIMAL(10, 2) in the
employees table.
This command adds a foreign key constraint fk_department to the employees table,
referencing the department_id column in the departments table.
This command removes the foreign key constraint fk_department from the employees
table.
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;
4. Calculate the FinalIA (average of best two test marks) and update the
corresponding table for all students.
UPDATE IAMARKS
SET FinalIA = (
SELECT ROUND((GREATEST(Test1, Test2, Test3) +
LEAST(GREATEST(Test1, Test2), GREATEST(Test1, Test3),
GREATEST(Test2, Test3))) / 2.0, 2)
)
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:
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:
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:
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:
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:
The DEFAULT constraint provides a default value for a column when no value is specified for
that column.
Example:
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.
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.
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.
If we update Alice's record but forget to update Carol's record, we end up with inconsistent
data:
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
1 Alice 101
2 Bob 102
Departments Table
DepartmentID DepartmentName
101 Sales
102 HR
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.
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}.
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
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
Example:
6. Partial Dependency
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:
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:
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.
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.
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.
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.
Students Table:
StudentID StudentName
1 Alice
2 Bob
Courses Table:
1. It is in 2NF.
2. All the attributes are functionally dependent only on the primary key. This means
there are no transitive dependencies.
3NF Conversion: Create another table for instructors to eliminate transitive dependencies.
Courses Table:
Instructors Table:
Instructor InstructorPhone
Dr. Smith 123-456-7890
Dr. Johnson 987-654-3210
Dr. Brown 555-555-5555
Summary
The query to list the names of managers who have at least one dependent would look like
this:
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.
The query to retrieve the department number, the number of employees in the department,
and their average salary would look like this:
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
Example: If we have X={A,B} and Y={A} since {A}⊆{A,B}, it follows that {A,B}→{A}.
2. Augmentation
3. Transitivity
Derived Rules
4. Union
5. Decomposition
Definition: If X→YZ, then X→Y and X→Z.
6. Pseudotransitivity
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:
Example:
Example:
3. DISTINCT Keyword
Example:
4. WHERE Clause
The WHERE clause is used to filter records that meet a certain condition.
Example:
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:
Retrieve employees who are either 'Managers' or work in the 'Sales' department:
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:
7. LIMIT Clause
Example:
8. LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
Examples:
Example:
The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates.
Example:
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:
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:
The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.
Example:
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.
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.
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:
3. Select All Unique Records: If you want to select all unique records considering all
columns, you can use DISTINCT with *.
SELECT DISTINCT *
FROM Employee;
This query will return all unique rows from the Employee table, considering every
column in the table.
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:
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.
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.
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.
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.
Guideline: Use foreign keys to maintain referential integrity between related tables.
Example: In an Employees table, use DeptID as a foreign key to reference the primary key in
a Departments table.
Example: Decompose a table with employee and department information into two tables:
Employees and Departments.
Example: If queries frequently need to join multiple tables, consider denormalizing parts of
the schema to reduce join operations.
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:
Consider a table Employee with columns EmpID, EmpName, Salary, and ManagerID:
In this example:
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;
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.
4. Indexes: Some database systems handle indexing of null values differently, which can
impact performance.