Unit 5: SQL Server For Backend Development - Subjective Questions
INT402 — Modern Web Programming Tools And Techniques • Practice Questions with Detailed Answers
20 questions
Define a database. Explain the major characteristics and advantages of using a database management system.
A database is an organized collection of related data stored electronically so that it can be efficiently accessed, managed, updated, and analyzed. A Database Management System (DBMS) is software that enables users and applications to interact with databases.
Major characteristics of a database:
- Structured storage: Data is organized into tables, records, and fields.
- Data relationships: Related data can be connected using keys.
- Controlled redundancy: Unnecessary duplication of data is minimized.
- Data integrity: Rules ensure that stored data remains accurate and consistent.
- Concurrent access: Multiple users can access the database simultaneously.
- Security: Access can be controlled through users, roles, and permissions.
Advantages of a DBMS:
- Reduces data duplication and inconsistency.
- Supports fast searching, sorting, and reporting.
- Provides backup and recovery facilities.
- Enforces integrity through constraints.
- Supports transaction management.
- Allows centralized administration and secure data sharing.
What is Microsoft SQL Server? Describe its important features and its role in backend web development.
Microsoft SQL Server is a relational database management system developed by Microsoft. It stores data in related tables and uses Transact-SQL (T-SQL) for defining, retrieving, manipulating, and controlling data.
Important features:
- Relational data storage: Organizes data into tables containing rows and columns.
- T-SQL support: Extends standard SQL with variables, conditions, loops, functions, and error handling.
- Transaction management: Supports reliable transactions using the ACID properties.
- Security: Provides authentication, authorization, encryption, roles, and permissions.
- Backup and recovery: Protects data against system failure or accidental loss.
- Stored procedures and views: Supports reusable database objects.
- Performance tools: Includes indexing, query optimization, and monitoring facilities.
Role in backend development:
A backend application connects to SQL Server to perform operations such as user registration, login verification, order processing, inventory management, and report generation. The application sends SQL commands or calls stored procedures, and SQL Server securely stores and processes the required data.
Explain different types of databases. Distinguish relational databases from non-relational databases.
Databases can be classified according to their data model and method of storage.
Major types of databases:
- Relational database: Stores data in tables connected through keys. Examples include SQL Server, MySQL, and PostgreSQL.
- Hierarchical database: Organizes data in a tree-like parent-child structure.
- Network database: Allows a record to have multiple parent and child records.
- Object-oriented database: Stores data as objects containing attributes and methods.
- Document database: Stores semi-structured documents, commonly in JSON-like form.
- Key-value database: Stores each value against a unique key.
- Graph database: Represents data using nodes, edges, and properties.
- Distributed database: Stores data across multiple computers or locations.
Relational versus non-relational databases:
| Basis | Relational database | Non-relational database |
|---|---|---|
| Structure | Tables with rows and columns | Documents, graphs, key-value pairs, or other models |
| Schema | Usually fixed and predefined | Often flexible or dynamic |
| Relationships | Implemented using primary and foreign keys | Embedded data or model-specific links |
| Query language | Primarily SQL | Depends on the database system |
| Consistency | Commonly emphasizes strong consistency | May favor scalability and availability |
| Best suited for | Structured and transaction-oriented data | Large-scale, flexible, or rapidly changing data |
SQL Server is primarily a relational database management system.
Classify SQL commands into DDL, DML, DQL, DCL, and TCL. Give suitable examples of each category.
SQL commands are classified according to the operations they perform.
-
Data Definition Language (DDL): Defines or changes database structures.
- Commands:
CREATE,ALTER,DROP, andTRUNCATE - Example:
CREATE TABLE Student (StudentId INT, Name VARCHAR(50));
- Commands:
-
Data Manipulation Language (DML): Inserts, modifies, or removes table data.
- Commands:
INSERT,UPDATE,DELETE, andMERGE - Example:
UPDATE Student SET Name = 'Aman' WHERE StudentId = 1;
- Commands:
-
Data Query Language (DQL): Retrieves data from one or more tables.
- Command:
SELECT - Example:
SELECT * FROM Student;
- Command:
-
Data Control Language (DCL): Controls database permissions.
- Commands:
GRANT,REVOKE, andDENY - Example:
GRANT SELECT ON Student TO AppUser;
- Commands:
-
Transaction Control Language (TCL): Manages transactions.
- Commands:
BEGIN TRANSACTION,COMMIT,ROLLBACK, andSAVE TRANSACTION - Example:
BEGIN TRANSACTION; UPDATE Account SET Balance = Balance - 500 WHERE AccountId = 1; COMMIT;
- Commands:
DDL changes the structure, DML changes the data, DQL reads data, DCL manages access, and TCL controls transaction boundaries.
Describe the structure of a SQL Server table. Write SQL statements to create and alter a table named Employee.
A SQL Server table stores related data in a row-and-column format.
- A column represents an attribute and has a name, data type, and optional constraints.
- A row represents one complete record.
- A primary key uniquely identifies every row.
- A foreign key establishes a relationship with another table.
- A NULL value represents missing or unknown data.
Creating the table:
CREATE TABLE Employee
(
EmployeeId INT PRIMARY KEY,
EmployeeName VARCHAR(100) NOT NULL,
Email VARCHAR(150) UNIQUE,
Salary DECIMAL(10, 2) CHECK (Salary >= 0),
JoinDate DATE DEFAULT GETDATE()
);Adding a column:
ALTER TABLE Employee
ADD DepartmentId INT;Changing a column definition:
ALTER TABLE Employee
ALTER COLUMN EmployeeName VARCHAR(150) NOT NULL;Removing a column:
ALTER TABLE Employee
DROP COLUMN DepartmentId;CREATE TABLE creates the structure, while ALTER TABLE modifies an existing table without recreating it.
Explain commonly used SQL Server data types. Why is selecting an appropriate data type important?
A data type specifies the kind of value a column can store, its storage requirements, and the operations that can be performed on it.
Common SQL Server data types:
- Integer types:
TINYINT,SMALLINT,INT, andBIGINT - Exact numeric types:
DECIMAL(p, s)andNUMERIC(p, s) - Approximate numeric types:
FLOATandREAL - Character types:
CHAR,VARCHAR,NCHAR, andNVARCHAR - Date and time types:
DATE,TIME,DATETIME,DATETIME2, andSMALLDATETIME - Logical type:
BIT - Binary types:
BINARY,VARBINARY, andVARBINARY(MAX) - Identifier type:
UNIQUEIDENTIFIER
In DECIMAL(p, s), represents the total number of digits and represents the number of digits after the decimal point. For example, DECIMAL(10, 2) can store monetary values with two decimal places.
Importance of appropriate data types:
- Saves storage space.
- Improves query and index performance.
- Prevents invalid values from being stored.
- Avoids unnecessary type conversions.
- Preserves numeric precision.
- Makes the database design easier to understand and maintain.
Explain the INSERT, UPDATE, and DELETE data manipulation commands with syntax and examples.
The INSERT, UPDATE, and DELETE commands are DML commands used to modify table data.
1. INSERT: Adds new rows to a table.
INSERT INTO Employee (EmployeeId, EmployeeName, Email, Salary)
VALUES (1, 'Neha Sharma', 'neha@example.com', 45000);Multiple rows can also be inserted in one statement.
2. UPDATE: Modifies existing rows.
UPDATE Employee
SET Salary = 50000
WHERE EmployeeId = 1;The WHERE clause is important because omitting it updates every row in the table.
3. DELETE: Removes rows from a table.
DELETE FROM Employee
WHERE EmployeeId = 1;Omitting the WHERE clause deletes every row but retains the table structure.
Important precautions:
- Test the condition with a
SELECTstatement before anUPDATEorDELETE. - Use transactions for critical modifications.
- Specify column names in
INSERTstatements. - Ensure that foreign-key relationships are considered before deleting rows.
Differentiate among the SQL Server DELETE, TRUNCATE, and DROP commands.
DELETE, TRUNCATE, and DROP all remove database information, but they operate differently.
| Basis | DELETE |
TRUNCATE |
DROP |
|---|---|---|---|
| Category | DML | DDL | DDL |
| Removes | Selected or all rows | All rows | Entire object |
WHERE support |
Yes | No | No |
| Table structure | Preserved | Preserved | Removed |
| Identity value | Usually not reset | Usually reset | Object no longer exists |
| Logging | Logs row deletions | Uses minimal page deallocation logging | Logs object deallocation |
| Delete triggers | Can fire | Do not fire | Not applicable as row deletion |
Examples:
DELETE FROM Employee WHERE EmployeeId = 10;TRUNCATE TABLE Employee;DROP TABLE Employee;Use DELETE when specific rows must be removed, TRUNCATE when all rows must be removed efficiently, and DROP when the table itself is no longer required.
What are constraints in SQL Server? Explain the major types of constraints with examples.
Constraints are rules applied to table columns to maintain the accuracy, validity, and consistency of data.
Major constraints:
- PRIMARY KEY: Uniquely identifies each row and does not allow
NULLvalues. - FOREIGN KEY: Ensures that a value refers to an existing row in another table.
- UNIQUE: Prevents duplicate values in a column or column combination.
- NOT NULL: Requires a value to be supplied.
- CHECK: Accepts only values satisfying a condition.
- DEFAULT: Supplies a value when none is specified.
Example:
CREATE TABLE Department
(
DepartmentId INT PRIMARY KEY,
DepartmentName VARCHAR(100) UNIQUE NOT NULL
);
CREATE TABLE Employee
(
EmployeeId INT PRIMARY KEY,
EmployeeName VARCHAR(100) NOT NULL,
Email VARCHAR(150) UNIQUE,
Salary DECIMAL(10, 2) CHECK (Salary >= 0),
Status VARCHAR(20) DEFAULT 'Active',
DepartmentId INT,
CONSTRAINT FK_Employee_Department
FOREIGN KEY (DepartmentId)
REFERENCES Department(DepartmentId)
);These constraints prevent duplicate identifiers, invalid salaries, missing required names, and references to nonexistent departments.
Distinguish between primary key, unique key, and foreign key constraints in SQL Server.
Primary, unique, and foreign keys serve different purposes in relational database design.
| Feature | Primary key | Unique key | Foreign key |
|---|---|---|---|
| Main purpose | Uniquely identifies each row | Prevents duplicate values | Establishes a relationship between tables |
| Duplicate values | Not allowed | Not allowed | May be repeated |
NULL values |
Not allowed | Generally allows a NULL value in SQL Server |
Allowed unless combined with NOT NULL |
| Number per table | Only one primary-key constraint | Multiple unique constraints are possible | Multiple foreign keys are possible |
| Reference | Is normally referenced by foreign keys | Can also be referenced when eligible | References a primary or unique candidate key |
Example:
CREATE TABLE Department
(
DepartmentId INT PRIMARY KEY,
DepartmentCode VARCHAR(10) UNIQUE
);
CREATE TABLE Employee
(
EmployeeId INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE,
DepartmentId INT,
FOREIGN KEY (DepartmentId)
REFERENCES Department(DepartmentId)
);Here, EmployeeId identifies an employee, Email must be unique, and DepartmentId links the employee to a valid department.
Explain the purpose and logical use of the SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY clauses.
SQL clauses specify the source, filtering, grouping, and presentation of query results.
SELECT: Specifies the columns or expressions to return.FROM: Identifies the source tables or views.WHERE: Filters individual rows before grouping.GROUP BY: Combines rows having the same grouping values.HAVING: Filters groups after aggregation.ORDER BY: Sorts the final result.
Example:
SELECT DepartmentId,
COUNT(*) AS EmployeeCount,
AVG(Salary) AS AverageSalary
FROM Employee
WHERE Status = 'Active'
GROUP BY DepartmentId
HAVING COUNT(*) >= 5
ORDER BY AverageSalary DESC;This query first reads Employee, filters active employees, groups them by department, keeps departments having at least five employees, and sorts the result by average salary.
A useful logical processing order is:
FROMWHEREGROUP BYHAVINGSELECTORDER BY
Thus, WHERE filters rows, whereas HAVING filters aggregated groups.
Describe SQL operators used in SQL Server, including arithmetic, comparison, logical, and special operators.
SQL operators are symbols or keywords used to perform calculations, comparisons, and filtering.
1. Arithmetic operators:
+addition-subtraction*multiplication/division%remainder
Example: SELECT Salary, Salary * 12 AS AnnualSalary FROM Employee;
2. Comparison operators:
=equal to<>or!=not equal to>greater than<less than>=greater than or equal to<=less than or equal to
Example: SELECT * FROM Employee WHERE Salary >= 50000;
3. Logical operators:
AND: All conditions must be true.OR: At least one condition must be true.NOT: Reverses a condition.
Example: WHERE DepartmentId = 2 AND Salary > 40000
4. Special operators:
BETWEEN: Tests an inclusive range.IN: Tests membership in a list or subquery.LIKE: Performs pattern matching.IS NULL: Checks for aNULLvalue.EXISTS: Tests whether a subquery returns any rows.
Example: WHERE Salary BETWEEN 30000 AND 60000
Parentheses should be used in complex expressions to make operator precedence explicit.
Explain pattern matching and NULL handling using LIKE, wildcard characters, IS NULL, and IS NOT NULL.
The LIKE operator performs pattern-based searching on character data.
Common SQL Server wildcard characters:
%matches zero or more characters._matches exactly one character.[abc]matches one character from the specified set.[a-z]matches one character from the specified range.[^abc]matches one character not in the specified set.
Examples:
SELECT * FROM Employee
WHERE EmployeeName LIKE 'A%';This returns names beginning with A.
SELECT * FROM Employee
WHERE EmployeeName LIKE '_a%';This returns names whose second character is a.
A NULL value represents missing, unknown, or inapplicable information. It is not equal to zero, an empty string, or another NULL value. Therefore, = NULL must not be used.
SELECT * FROM Employee
WHERE Email IS NULL;SELECT * FROM Employee
WHERE Email IS NOT NULL;Functions such as ISNULL(Email, 'Not provided') or COALESCE(Email, AlternateEmail, 'Not provided') can substitute another value when an expression is NULL.
What is a SQL join? Explain INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN with their result behavior.
A join combines rows from two or more tables using a related column or join condition.
Assume Employee.DepartmentId refers to Department.DepartmentId.
1. INNER JOIN: Returns only matching rows from both tables.
SELECT e.EmployeeName, d.DepartmentName
FROM Employee AS e
INNER JOIN Department AS d
ON e.DepartmentId = d.DepartmentId;2. LEFT JOIN: Returns every row from the left table and matching rows from the right table. Missing right-side values become NULL.
SELECT e.EmployeeName, d.DepartmentName
FROM Employee AS e
LEFT JOIN Department AS d
ON e.DepartmentId = d.DepartmentId;3. RIGHT JOIN: Returns every row from the right table and matching rows from the left table.
SELECT e.EmployeeName, d.DepartmentName
FROM Employee AS e
RIGHT JOIN Department AS d
ON e.DepartmentId = d.DepartmentId;4. FULL OUTER JOIN: Returns matching rows and all unmatched rows from both tables. Missing columns are represented by NULL.
SELECT e.EmployeeName, d.DepartmentName
FROM Employee AS e
FULL OUTER JOIN Department AS d
ON e.DepartmentId = d.DepartmentId;The appropriate join depends on whether only matched data or also unmatched data is required.
Explain CROSS JOIN and self join in SQL Server. Give an appropriate example of each.
CROSS JOIN:
A CROSS JOIN produces the Cartesian product of two tables. Every row of the first table is combined with every row of the second table. If the first table has rows and the second has rows, the result contains:
rows.
SELECT c.ColorName, s.SizeName
FROM Color AS c
CROSS JOIN Size AS s;If there are 4 colors and 3 sizes, the query returns combinations. It is useful for generating all possible combinations but may produce very large results.
Self join:
A self join joins a table to itself. Aliases are required to represent separate logical instances of the same table.
SELECT e.EmployeeName AS Employee,
m.EmployeeName AS Manager
FROM Employee AS e
LEFT JOIN Employee AS m
ON e.ManagerId = m.EmployeeId;Here, e represents employees and m represents managers. A self join is useful for hierarchical relationships such as employee-manager, category-parent category, or prerequisite-course relationships.
Define a SQL Server view. Explain its advantages, limitations, and basic syntax.
A view is a named database object defined by a SELECT query. It presents data from one or more tables as a virtual table. A normal view stores its query definition rather than storing a separate copy of the result data.
Syntax:
CREATE VIEW dbo.ActiveEmployees
AS
SELECT EmployeeId, EmployeeName, DepartmentId
FROM dbo.Employee
WHERE Status = 'Active';It can be queried like a table:
SELECT * FROM dbo.ActiveEmployees;Advantages:
- Hides complex joins and calculations.
- Presents a simpler interface to applications.
- Restricts access to selected rows and columns.
- Promotes query reuse and consistency.
- Provides a level of abstraction from base tables.
Limitations:
- Some views are not directly updatable, especially those using grouping, aggregates,
DISTINCT, or certain joins. - A view does not automatically guarantee better performance.
- Changes to base-table structures may affect dependent views.
- Nested and complex views can become difficult to maintain.
A view can be modified using ALTER VIEW and removed using DROP VIEW.
Discuss the major types of views in SQL Server, including simple, complex, indexed, partitioned, and system views.
SQL Server views may be classified according to their query structure or purpose.
1. Simple view:
- Usually based on one table.
- Does not normally contain grouping or aggregate functions.
- Is often updatable when each view row maps clearly to a base-table row.
2. Complex view:
- May use multiple tables, joins, calculations, grouping, or aggregate functions.
- Simplifies complicated reporting queries.
- May not be directly updatable.
3. Indexed view:
- Has a unique clustered index created on it.
- Physically stores the indexed result and may improve certain query workloads.
- Requires
WITH SCHEMABINDINGand must satisfy SQL Server restrictions. - Adds maintenance cost when base-table data changes.
4. Partitioned view:
- Combines horizontally partitioned data from multiple tables using
UNION ALL. - May represent data divided by year, region, or another range.
- Can be local or distributed across servers.
5. System view:
- Supplied by SQL Server to expose metadata and system information.
- Examples include
sys.tables,sys.columns, andsys.views.
Each type serves a different purpose, such as abstraction, reporting, metadata inspection, performance optimization, or combining distributed data.
How is a user-defined view created, altered, used, and dropped in SQL Server? Illustrate with an example.
A user-defined view is created by a database user or developer to present required data through a reusable SELECT statement.
Creating a view:
CREATE VIEW dbo.EmployeeDepartmentView
AS
SELECT e.EmployeeId,
e.EmployeeName,
e.Salary,
d.DepartmentName
FROM dbo.Employee AS e
INNER JOIN dbo.Department AS d
ON e.DepartmentId = d.DepartmentId;Using the view:
SELECT EmployeeName, DepartmentName
FROM dbo.EmployeeDepartmentView
WHERE Salary > 50000;Altering the view:
ALTER VIEW dbo.EmployeeDepartmentView
AS
SELECT e.EmployeeId,
e.EmployeeName,
e.Email,
e.Salary,
d.DepartmentName
FROM dbo.Employee AS e
INNER JOIN dbo.Department AS d
ON e.DepartmentId = d.DepartmentId
WHERE e.Status = 'Active';Dropping the view:
DROP VIEW dbo.EmployeeDepartmentView;Good practices:
- Use a schema-qualified name such as
dbo.ViewName. - Avoid
SELECT *because base-table changes may affect the view unexpectedly. - Grant users access to the view instead of exposing sensitive table columns.
- Keep the view focused on a clear business requirement.
What is a stored procedure in SQL Server? Explain its advantages, components, and execution process.
A stored procedure is a named collection of T-SQL statements stored in the database and executed as a unit. It can accept parameters, perform queries or data modifications, contain programming logic, and return result sets, output parameters, or a return status.
Basic components:
- Procedure name and schema
- Input and output parameters
- T-SQL statements
- Local variables
- Conditional statements and loops
- Transaction and error-handling logic
- Return status or result set
Advantages:
- Reusability: The same logic can be called by different applications.
- Maintainability: Business logic can be changed centrally.
- Security: Users may receive
EXECUTEpermission without direct table permissions. - Reduced network traffic: Multiple statements are invoked through one procedure call.
- Consistency: Applications use the same validated operations.
- Performance: SQL Server can reuse suitable execution plans, although performance still depends on query design and parameters.
Execution process:
- The application calls the procedure with parameter values.
- SQL Server validates permissions and parameters.
- The procedure statements are compiled or an existing plan is reused.
- Statements execute on the server.
- Results, output parameters, and the return status are sent to the caller.
Create and explain a user-defined stored procedure that inserts an employee, validates the salary, uses a transaction, and handles errors.
A user-defined stored procedure can combine parameters, validation, transaction management, and error handling in one reusable operation.
CREATE PROCEDURE dbo.AddEmployee
@EmployeeId INT,
@EmployeeName VARCHAR(100),
@Email VARCHAR(150),
@Salary DECIMAL(10, 2),
@DepartmentId INT
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF @Salary < 0
THROW 50001, 'Salary cannot be negative.', 1;
IF NOT EXISTS
(
SELECT 1
FROM dbo.Department
WHERE DepartmentId = @DepartmentId
)
THROW 50002, 'Invalid department.', 1;
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO dbo.Employee
(
EmployeeId,
EmployeeName,
Email,
Salary,
DepartmentId
)
VALUES
(
@EmployeeId,
@EmployeeName,
@Email,
@Salary,
@DepartmentId
);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK TRANSACTION;
THROW;
END CATCH;
END;Execution:
EXEC dbo.AddEmployee
@EmployeeId = 101,
@EmployeeName = 'Riya Gupta',
@Email = 'riya@example.com',
@Salary = 55000,
@DepartmentId = 2;Explanation:
- Parameters receive employee details from the caller.
- The first validation prevents a negative salary.
EXISTSchecks whether the department is valid.BEGIN TRANSACTIONmakes the insertion an atomic operation.COMMITpermanently saves a successful insertion.TRY...CATCHintercepts runtime errors.ROLLBACKreverses an incomplete transaction.THROWpasses the error to the calling application.SET NOCOUNT ONprevents unnecessary row-count messages.
Define a database. Explain the major characteristics and advantages of using a database management system.
A database is an organized collection of related data stored electronically so that it can be efficiently accessed, managed, updated, and analyzed. A Database Management System (DBMS) is software that enables users and applications to interact with databases.
Major characteristics of a database:
- Structured storage: Data is organized into tables, records, and fields.
- Data relationships: Related data can be connected using keys.
- Controlled redundancy: Unnecessary duplication of data is minimized.
- Data integrity: Rules ensure that stored data remains accurate and consistent.
- Concurrent access: Multiple users can access the database simultaneously.
- Security: Access can be controlled through users, roles, and permissions.
Advantages of a DBMS:
- Reduces data duplication and inconsistency.
- Supports fast searching, sorting, and reporting.
- Provides backup and recovery facilities.
- Enforces integrity through constraints.
- Supports transaction management.
- Allows centralized administration and secure data sharing.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. 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. Chip in only if it was worth it. What it pays for →