Unit 2 subjective questions Relational query language
INT306 — Database Management Systems 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
What is Data Definition Language (DDL)? Explain its primary commands with their syntax.
Model answer
Data Definition Language (DDL) is a subset of SQL used to define, modify, and manage the structural components of a database, such as tables, schemas, and views. DDL commands auto-commit, meaning their changes are permanently saved in the database immediately.
Primary DDL Commands:
- CREATE: Used to build a new database or table.
Syntax:CREATE TABLE table_name (column1 datatype, column2 datatype); - ALTER: Used to modify the structure of an existing table (e.g., adding, dropping, or modifying columns).
Syntax:ALTER TABLE table_name ADD column_name datatype; - DROP: Completely removes an existing database or table from the system, including its structure and data.
Syntax:DROP TABLE table_name; - TRUNCATE: Removes all records from a table, but leaves the table's structure (schema) intact for future data insertion.
Syntax:TRUNCATE TABLE table_name;
- CREATE: Used to build a new database or table.
-
Question 2 of 20
Differentiate between the
DROPandTRUNCATEcommands in SQL.Model answer
Both
DROPandTRUNCATEare DDL commands, but they serve different purposes:- Purpose:
TRUNCATEdeletes all rows from a table but keeps the table structure intact.DROPremoves the table entirely, including its structure, data, privileges, and indexes. - Speed:
TRUNCATEis faster thanDROP(andDELETE) because it deallocates the data pages instead of logging individual row deletions. - Space Recovery:
TRUNCATEresets the table's identity column and reclaims the storage space.DROPfrees up the space entirely back to the database. - Reversibility: Neither command can be rolled back in most standard SQL databases once executed, as DDL operations auto-commit.
- Syntax:
TRUNCATE TABLE table_name;DROP TABLE table_name;
- Purpose:
-
Question 3 of 20
Explain the
ALTER TABLEcommand and discuss how it can be used to add, modify, and drop columns.Model answer
The
ALTER TABLEcommand is a DDL command used to change the structure of an existing table without dropping and recreating it.1. Adding a Column:
You can add a new column to an existing table using theADDclause.
Syntax:ALTER TABLE table_name ADD column_name datatype;2. Modifying a Column:
You can change the data type or size of an existing column using theMODIFY(orALTER COLUMNin some SQL dialects) clause.
Syntax:ALTER TABLE table_name MODIFY column_name new_datatype;3. Dropping a Column:
You can remove an existing column from a table using theDROP COLUMNclause.
Syntax:ALTER TABLE table_name DROP COLUMN column_name; -
Question 4 of 20
Define Data Manipulation Language (DML). Distinguish between procedural and non-procedural DML.
Model answer
Data Manipulation Language (DML) is a subset of SQL used for managing and manipulating data within existing schema objects. DML allows users to access, insert, modify, or delete data.
Types of DML:
1. Procedural DML:
- The user must specify exactly what data is needed and how to get it.
- It involves writing a sequence of operations (code) to retrieve the data.
- Typically used in traditional programming languages accessing databases through APIs.
2. Non-Procedural (Declarative) DML:
- The user only needs to specify what data is needed without specifying how to retrieve it.
- The Database Management System (DBMS) query optimizer figures out the most efficient execution plan.
- SQL is a prime example of a non-procedural DML (e.g., using
SELECTstatements).
-
Question 5 of 20
Describe the core DML commands (
INSERT,UPDATE,DELETE) with examples.Model answer
The core DML commands are used to manipulate data within tables:
1. INSERT:
Adds one or more new rows to a table.- Syntax:
INSERT INTO table_name (col1, col2) VALUES (val1, val2); - Example:
INSERT INTO Employees (ID, Name) VALUES (101, 'Alice');
2. UPDATE:
Modifies existing data in a table. AWHEREclause is crucial to avoid updating all rows.- Syntax:
UPDATE table_name SET col1 = val1 WHERE condition; - Example:
UPDATE Employees SET Name = 'Alice Smith' WHERE ID = 101;
3. DELETE:
Removes existing rows from a table. LikeUPDATE, it should usually include aWHEREclause.- Syntax:
DELETE FROM table_name WHERE condition; - Example:
DELETE FROM Employees WHERE ID = 101;
- Syntax:
-
-
Question 6 of 20
Compare and contrast the
DELETEandTRUNCATEcommands in SQL.Model answer
While both
DELETEandTRUNCATEremove data from a table, they operate very differently:Feature DELETETRUNCATELanguage Type DML (Data Manipulation Language) DDL (Data Definition Language) Filtering Can use a WHEREclause to filter rows.Cannot use a WHEREclause; removes all rows.Logging Logs each row deletion individually (slower). Logs the deallocation of data pages (much faster). Rollback Can be rolled back if used within a transaction. Cannot be rolled back (auto-commits in most DBMS). Triggers Fires DELETEtriggers.Does not fire DELETEtriggers.Identity Reset Does not reset identity/auto-increment counters. Resets the identity/auto-increment counter to its seed. -
Question 7 of 20
What is Data Control Language (DCL)? Explain its two main commands.
Model answer
Data Control Language (DCL) is used to control access to data within the database. It allows database administrators to implement security by granting or revoking privileges to users or roles.
Main DCL Commands:
1. GRANT:
Provides specific privileges to a user or role, allowing them to perform specified operations (likeSELECT,INSERT,EXECUTE).- Syntax:
GRANT privilege_name ON object_name TO user_name; - Example:
GRANT SELECT, INSERT ON Employees TO user_john;
2. REVOKE:
Removes previously granted privileges from a user or role, restricting their access.- Syntax:
REVOKE privilege_name ON object_name FROM user_name; - Example:
REVOKE INSERT ON Employees FROM user_john;
- Syntax:
-
Question 8 of 20
Discuss Transaction Control Language (TCL) and explain its primary commands:
COMMIT,ROLLBACK, andSAVEPOINT.Model answer
Transaction Control Language (TCL) commands are used to manage transactions in the database. A transaction is a logical unit of work comprising one or more DML operations. TCL ensures the ACID properties (Atomicity, Consistency, Isolation, Durability) are maintained.
Primary TCL Commands:
1. COMMIT:
Permanently saves all changes made during the current transaction. Once committed, changes cannot be rolled back.- Syntax:
COMMIT;
2. ROLLBACK:
Undoes all changes made since the beginning of the transaction or since a specific savepoint, restoring the database to its previous consistent state.- Syntax:
ROLLBACK;
3. SAVEPOINT:
Creates a specific marker within a transaction. It allows a partial rollback. Instead of rolling back the entire transaction, you can roll back to a specific savepoint.- Syntax:
SAVEPOINT savepoint_name;
ROLLBACK TO savepoint_name;
- Syntax:
-
Question 9 of 20
Explain the concept of database integrity. What are the three main types of integrity constraints?
Model answer
Database Integrity refers to the accuracy, consistency, and reliability of data stored in the database over its entire lifecycle. Integrity constraints are rules enforced on data columns to prevent invalid data entry.
Three Main Types of Integrity Constraints:
1. Domain Integrity:
Ensures that all values in a column fall within a defined set of valid values (domain). This is implemented using Data Types,CHECKconstraints, andDEFAULTconstraints.2. Entity Integrity:
Ensures that each row in a table is uniquely identifiable. It dictates that a primary key must exist and that the primary key column(s) cannot containNULLvalues. Let be a relation and be its primary key; then .3. Referential Integrity:
Ensures consistency between two associated tables. It requires that a foreign key value must either match an existing primary key value in the referenced table or beNULL. -
Question 10 of 20
Define Referential Integrity and explain how it is enforced in SQL using Foreign Keys.
Model answer
Referential Integrity is a database concept that ensures the relationships between tables remain consistent. It dictates that a foreign key in a child table must reference a valid, existing primary key (or unique key) in the parent table.
Enforcement in SQL:
Referential integrity is enforced using the FOREIGN KEY constraint.- When a record is inserted into the child table, the DBMS checks if the foreign key value exists in the parent table.
- If a user tries to delete or update a record in the parent table that is referenced by the child table, the DBMS prevents it unless specific actions are defined.
Cascading Actions:
To handle updates or deletions in the parent table, SQL provides cascading rules:ON DELETE CASCADE: If a parent record is deleted, all referencing child records are also deleted.ON DELETE SET NULL: If a parent record is deleted, the referencing child records' foreign key is set toNULL.
-
Question 11 of 20
Explain the
CHECKandDEFAULTconstraints with SQL syntax examples.Model answer
1. CHECK Constraint:
TheCHECKconstraint is used to limit the value range that can be placed in a column. It ensures that all values in a column satisfy a specific condition or boolean expression.- Syntax:
CREATE TABLE Persons (Age INT CHECK (Age >= 18)); - Explanation: This ensures that no person under the age of 18 can be added to the
Personstable.
2. DEFAULT Constraint:
TheDEFAULTconstraint provides a default value for a column when no value is specified during anINSERToperation. It ensures the column does not accidentally becomeNULLif a standard fallback value exists.- Syntax:
CREATE TABLE Orders (OrderDate DATE DEFAULT CURRENT_DATE); - Explanation: If an order is inserted without specifying the
OrderDate, the database automatically assigns the current date.
- Syntax:
-
Question 12 of 20
What is the difference between the
UNIQUEandNOT NULLconstraints? Can they be used together?Model answer
NOT NULL Constraint:
- Ensures that a column cannot have a
NULLvalue. - It forces a field to always contain a value, meaning you cannot insert a new record or update a record without adding a value to this field.
UNIQUE Constraint:
- Ensures that all values in a column (or a set of columns) are distinct from one another.
- No two rows can have the same value for that specific column.
- Standard SQL allows a
UNIQUEcolumn to containNULLvalues (and usually multipleNULLs are allowed sinceNULL != NULL).
Using them together:
Yes, they can be used together. A column defined asUNIQUE NOT NULLrequires that every row has a value and that every value is different. APRIMARY KEYinherently applies bothUNIQUEandNOT NULLconstraints. - Ensures that a column cannot have a
-
Question 13 of 20
Define and differentiate between Super Key, Candidate Key, and Primary Key in a relational database.
Model answer
Let be a relational schema. Keys are sets of attributes used to uniquely identify tuples in .
1. Super Key:
A Super Key is a set of one or more attributes that can uniquely identify a row in a table. It may contain extraneous attributes. Mathematically, if is a super key, no two distinct tuples can have .2. Candidate Key:
A Candidate Key is a minimal Super Key. It is a Super Key with no redundant attributes. If any attribute is removed from a Candidate Key, it loses its unique identification property. A table can have multiple candidate keys.3. Primary Key:
A Primary Key is a specific Candidate Key chosen by the database designer to identify tuples in a relation uniquely. There can be only one Primary Key per table. It must satisfy Entity Integrity (cannot beNULL).Hierarchy: Every Primary Key is a Candidate Key, and every Candidate Key is a Super Key. The reverse is not true.
-
Question 14 of 20
What is a Foreign Key? Explain its significance with an example.
Model answer
Foreign Key:
A Foreign Key is a column or a set of columns in one table that refers to the Primary Key (or Unique Key) in another table. The table containing the foreign key is the child table, and the table containing the referenced key is the parent table.Significance:
- Enforces Referential Integrity: It prevents actions that would destroy links between tables (e.g., deleting a parent record when child records still reference it).
- Establishes Relationships: It is the fundamental mechanism for linking tables together in a relational database (e.g., one-to-many relationships).
Example:
Consider two tables:Departments(DeptID, DeptName)andEmployees(EmpID, EmpName, DeptID).DeptIDis the Primary Key inDepartments.DeptIDin theEmployeestable is a Foreign Key referencingDepartments(DeptID). This ensures every employee belongs to a valid department.
-
Question 15 of 20
Differentiate between a Primary Key and a Unique Key constraint.
Model answer
Both
PRIMARY KEYandUNIQUEconstraints guarantee uniqueness for a column or set of columns, but they have key differences:Feature Primary Key Unique Key Purpose To uniquely identify each record in a table. To ensure specific columns do not have duplicate values. NULL Values Does not allow NULLvalues.Allows NULLvalues (usually multiple, depending on the RDBMS).Number per Table Only one Primary Key is allowed per table. Multiple Unique Keys are allowed per table. Clustered Index By default, creates a Clustered Index on the column. By default, creates a Non-Clustered Index on the column. -
Question 16 of 20
Explain the concepts of Alternate Key and Composite Key.
Model answer
1. Alternate Key:
When a table has multiple Candidate Keys, the database administrator selects one to be the Primary Key. The remaining candidate keys, which were not selected as the primary key, are known as Alternate Keys (or Secondary Keys). They still uniquely identify rows but are not the primary means of doing so.
Example: If a table hasEmployeeID,Email, andSSNas candidate keys. IfEmployeeIDis chosen as the Primary Key, thenEmailandSSNbecome Alternate Keys.2. Composite Key:
A Composite Key (or Compound Key) is a primary key that consists of two or more attributes (columns) that uniquely identify an entity occurrence. Individually, the attributes might not be unique, but combined, they guarantee uniqueness.
Example: In anEnrollmenttable,StudentIDalone is not unique, andCourseIDalone is not unique. However, the combination of(StudentID, CourseID)uniquely identifies a specific student's enrollment in a specific course. -
Question 17 of 20
Describe the basic structure of an SQL query using
SELECT,FROM, andWHERE. Explain the logical order of execution.Model answer
Basic SQL Query Structure:
The most common SQL statement is theSELECTstatement, which retrieves data from one or more tables.- SELECT: Specifies the columns to be returned.
- FROM: Specifies the table(s) from which to retrieve the data.
- WHERE: Specifies the conditions that the records must meet to be included in the result set.
Syntax:
SELECT column1, column2 FROM table_name WHERE condition;Logical Order of Execution:
While the query is written starting withSELECT, the database engine processes it in a different order:- FROM: The database first identifies the working dataset (the table or joined tables).
- WHERE: It then filters the rows based on the conditions specified. Rows evaluating to FALSE or UNKNOWN are discarded.
- SELECT: Finally, it evaluates the
SELECTlist to determine which columns (and expressions) to output for the filtered rows.
-
Question 18 of 20
Discuss the five basic aggregate functions in SQL with their purposes.
Model answer
Aggregate functions perform a calculation on a set of values and return a single scalar value. They are frequently used with the
GROUP BYclause. The five basic SQL aggregate functions are:- COUNT(): Returns the number of rows that match a specified criterion.
COUNT(*)counts all rows, whileCOUNT(column_name)counts non-NULL values in that column. - SUM(): Returns the total sum of a numeric column.
- AVG(): Returns the average value of a numeric column. It ignores
NULLvalues in the calculation. - MIN(): Returns the smallest (minimum) value in the selected column.
- MAX(): Returns the largest (maximum) value in the selected column.
Example:
SELECT COUNT(EmpID), AVG(Salary) FROM Employees; - COUNT(): Returns the number of rows that match a specified criterion.
-
Question 19 of 20
Explain the use of
GROUP BYandHAVINGclauses in SQL with a practical example.Model answer
GROUP BY Clause:
TheGROUP BYstatement groups rows that have the same values in specified columns into summary rows. It is often used with aggregate functions (COUNT,MAX,MIN,SUM,AVG) to group the result-set by one or more columns.HAVING Clause:
TheHAVINGclause was added to SQL because theWHEREkeyword cannot be used with aggregate functions.HAVINGfilters the results of theGROUP BYclause.Practical Example:
Suppose we have a tableSales(Region, Amount).
We want to find regions where the total sales amount exceeds 10,000.SQLSELECT Region, SUM(Amount) as TotalSales FROM Sales GROUP BY Region HAVING SUM(Amount) > 10000; *Explanation:* The query first groups the sales by `Region`, calculates the `SUM(Amount)` for each region, and finally, the `HAVING` clause filters out the regions where the `TotalSales` is 10,000 or less. -
Question 20 of 20
What are SQL aliases? Explain column aliases and table aliases with syntax.
Model answer
SQL Aliases are temporary names assigned to tables or columns for the duration of a specific query. They make column names more readable or abbreviate long table names, especially in complex joins.
1. Column Alias:
Used to rename a column in the query output for better readability.- Syntax:
SELECT column_name AS alias_name FROM table_name; - Example:
SELECT Emp_First_Name AS "First Name" FROM Employees;(Quotes are used if the alias contains spaces).
2. Table Alias:
Used to give a table a short nickname, which makes queries involving joins or self-referencing much easier to write and read.- Syntax:
SELECT t.column_name FROM table_name AS t; - Example:
SELECT e.Name, d.DeptName FROM Employees e JOIN Departments d ON e.DeptID = d.DeptID;(Here, 'e' and 'd' are table aliases).
- Syntax:
That's unit 2
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 2 of INT306 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 2 of INT306 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.