0% found this document useful (0 votes)
3 views

SQL Test 2 - Copy (2)

The document is a SQL test designed for freshers, covering various theoretical questions about relational databases, SQL constraints, views, stored procedures, triggers, data integrity, and SQL operations like DELETE, TRUNCATE, and DROP. It explains key concepts, differences between SQL commands, and the significance of using certain SQL statements for query optimization and data management. Additionally, it outlines aggregate functions and the purpose of the WHERE clause in filtering records.

Uploaded by

Abhishek Shete
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL Test 2 - Copy (2)

The document is a SQL test designed for freshers, covering various theoretical questions about relational databases, SQL constraints, views, stored procedures, triggers, data integrity, and SQL operations like DELETE, TRUNCATE, and DROP. It explains key concepts, differences between SQL commands, and the significance of using certain SQL statements for query optimization and data management. Additionally, it outlines aggregate functions and the purpose of the WHERE clause in filtering records.

Uploaded by

Abhishek Shete
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

SQL Test for Freshers

Theory Questions
1. What is a relational database?
o Explain its structure and advantages.
Ans-
A relational database is a type of database that stores data in a structured
format, using rows and columns, which is typically organized into tables.
Each table represents a specific type of data, and relationships are
established between tables through the use of primary keys and foreign
keys.
Structure:
 Tables: A relational database consists of multiple tables, each having
rows (records) and columns (fields).
 Rows: Each row represents a record, for example, a customer, an
order, etc.
 Columns: Columns represent the attributes or properties of each
record, such as customer name, order ID, etc.
 Keys:
o Primary Key: Uniquely identifies each record in a table.
o Foreign Key: A field in one table that refers to the primary key
in another table to establish relationships.
Advantages:
 Data Integrity: The relational model enforces constraints that
maintain the accuracy and consistency of data.
 Flexibility: You can query and manipulate data efficiently using SQL
(Structured Query Language).
 Scalability: Relational databases can manage large volumes of data.
 Normalization: Reduces redundancy and dependency by organizing
data into multiple related tables.

2. What are SQL constraints?


o Describe different types of constraints like NOT
NULL, UNIQUE, CHECK, and DEFAULT.
Ans-
SQL Constraints
SQL constraints are rules or conditions applied to columns or tables to
ensure the accuracy, integrity, and validity of the data in a database.
Constraints help maintain data quality by limiting the type of data that
can be inserted, updated, or deleted from the table.

Types of SQL Constraints


1. PRIMARY KEY:
o Ensures that a column (or combination of columns) uniquely
identifies each row in a table.
o A table can have only one primary key.
o It also implicitly creates a NOT NULL constraint.
o Example: PRIMARY KEY (EmployeeID)
2. FOREIGN KEY:
o Ensures that the values in one column (or combination of
columns) match the values in a column in another table.
SQL Test for Freshers

o Enforces referential integrity between tables.


o Example: FOREIGN KEY (DepartmentID) REFERENCES
Departments(DepartmentID)
3. NOT NULL:
o Ensures that a column cannot have a NULL value.
o Example: EmployeeName VARCHAR(100) NOT NULL
4. UNIQUE:
o Ensures that all values in a column (or a set of columns) are
unique across the table.
o Allows NULL values unless explicitly specified otherwise.
o Example: UNIQUE (EmailAddress)
5. CHECK:
o Ensures that the values in a column meet a specified condition
or constraint.
o Example: CHECK (Age >= 18) ensures that the Age column
only has values greater than or equal to 18.

3. What is the difference between UNION and UNION ALL?


o Explain how each operates with examples.
Ans-
Difference Between UNION and UNION ALL
Both UNION and UNION ALL are used to combine the results of two or
more SELECT queries. However, they have key differences in how they
handle duplicate rows.

1. UNION
 Purpose: Combines the result sets of two or more queries and
removes duplicate rows from the final result.
 Behavior: It performs an implicit DISTINCT operation, meaning it
only returns unique rows.
 Performance: Generally slower than UNION ALL because it must
check for and eliminate duplicates.
2.UNION ALL
 Purpose: Combines the result sets of two or more queries and
includes all rows, even duplicates.
 Behavior: Does not remove duplicates and returns all rows from the
combined queries.
 Performance: Generally faster than UNION because it does not
require duplicate checking.

4. What is a view in SQL?


o Discuss its purpose and how it differs from a table.
Ans-
A view in SQL is a virtual table that is based on the result of a query. It
does not store data itself but presents data from one or more underlying
tables. A view can contain rows and columns like a table, but its content is
dynamically generated when it is queried. Essentially, a view is a stored
query that you can reference like a table.
SQL Test for Freshers

Purpose of a View:
1. Data Abstraction: A view hides the complexity of database schema,
offering a simplified way of accessing data without exposing all the
underlying tables.
2. Security: Views can restrict access to sensitive columns or rows in a
table. By creating views that display only the necessary data, you
can control which parts of the database are exposed to users.
3. Reusability: Views allow you to save complex queries, making them
reusable without having to write the query again every time.
4. Data Integrity: They provide a consistent way to represent the data,
even if the underlying tables change (e.g., after adding or removing
columns).
5. Simplification: You can simplify complex joins and subqueries by
storing them as views, so they can be referenced in future queries
without having to repeat the logic.
Aspect Table View
A view does not store data; it stores a
Storage A table stores actual data.
query.

The data is stored permanently The data is retrieved dynamically when


Data
in the table. queried.

Views generally cannot be modified


Data in a table can be inserted,
Modifications directly (depending on the type of view
updated, or deleted.
and DBMS).
Tables store the core data for Views provide a virtual representation of
Purpose
the database. data.
Querying a view fetches data based on
Querying a table fetches data
Performance the underlying query, which can impact
directly.
performance.
Changes in the schema of a
Changes to the underlying tables can
Schema table (e.g., adding a column)
affect a view, especially if the columns or
Changes directly affect the data in the
structure used in the view are altered.
table.

5. What are stored procedures and triggers?


o Explain the differences and when to use each.
Ans-
1. Stored Procedures
A stored procedure is a set of SQL statements that are stored and
executed in the database. It can take input parameters, perform
operations like querying, updating, or deleting data, and return output
values.
Key Characteristics of Stored Procedures:
 Explicit Invocation: Stored procedures must be explicitly called by
the user or an application.
 Parameterization: They can accept input parameters and return
output parameters.
SQL Test for Freshers

 Reusable: Once defined, a stored procedure can be executed


multiple times without rewriting the logic.
 Control Flow: Stored procedures can contain complex logic, including
conditional statements, loops, and error handling.
When to Use Stored Procedures:
 Reusable Operations: When you need to perform the same
operation multiple times.
 Encapsulate Complex Logic: When the logic involves multiple
SQL statements or business rules.
 Performance: Stored procedures can optimize performance by
reducing the amount of data transferred and minimizing redundant
queries.
2. Triggers
A trigger is a set of SQL statements that automatically execute in
response to certain events on a table (such as INSERT, UPDATE, or
DELETE). Triggers are often used to enforce business rules, ensure data
integrity, or automatically modify other tables.
Key Characteristics of Triggers:
 Automatic Invocation: Triggers are automatically fired in response
to a specific event (e.g., when a row is inserted, updated, or
deleted).
 No Parameters: Triggers don't accept parameters, and they act on
data that has been modified.
 Event-Driven: A trigger is associated with a table or view and is
activated by data modification events.
 Implicit Execution: They run automatically when the event occurs,
without needing to be explicitly called.
When to Use Triggers:
 Enforcing Data Integrity: For example, automatically updating or
maintaining data consistency across tables.
 Audit Logs: When you need to track changes to tables (e.g.,
logging changes to a table for auditing purposes).
 Cascading Operations: When changes in one table need to
propagate to related tables (e.g., updating stock levels when a sale
occurs).

6. What is the significance of the EXPLAIN statement in SQL?


o Discuss how it helps in query optimization.
Ans-
The EXPLAIN statement is a powerful tool in SQL that provides insight into
how the database query optimizer plans to execute a given SQL query. It
describes the execution plan for a query, showing how the database
engine will access the data, which indexes will be used, and the order in
which operations will be performed.
How It Helps in Query Optimization:
1. Understanding the Execution Plan: The EXPLAIN statement breaks
down a query into different stages and operations, such as:
o Table Scans (Full table scans)
SQL Test for Freshers

o Index Scans (Using indexes to speed up the search)


o Join Methods (Nested loop joins, hash joins, etc.)
o Sorting (How data is being sorted, which may use indexes or
temporary tables)
o Aggregations (Summing or averaging data)
2. Identifying Bottlenecks: By reviewing the execution plan, you can
identify areas of inefficiency in a query. For example:
o Full Table Scans: If a table scan is being used instead of an
index, it may indicate a performance issue, especially with
large datasets.
o Expensive Operations: Certain operations, such as nested
loops or hash joins, may be costly in terms of performance.
o Redundant Operations: If the same operation is performed
multiple times or if unnecessary sorting or filtering is done,
these can be optimized.
3. Choosing the Right Indexes: The execution plan will show if indexes
are being used effectively. If the query performs a full table scan
where an index should have been used, you might want to consider
adding an appropriate index to optimize performance. For instance:
o If a query that searches for values in a column is not using an
index, an index can be created to speed up retrieval.
4. Improving Join Efficiency: By analyzing how tables are joined (e.g.,
nested loops vs. hash joins), you can determine the most efficient
way to join tables. For large datasets, hash joins are often more
efficient than nested loops.
5. Estimating Query Costs: Most EXPLAIN output provides an estimated
cost for each operation. This helps in understanding the relative cost
of different parts of a query, guiding you toward optimization
strategies such as reordering joins or selecting a different query
structure.

7. What is data integrity, and why is it important?


o Explain its types and how SQL enforces it.
Ans-
Data integrity ensures the accuracy, consistency, and reliability of data
throughout its lifecycle. It's important because it ensures that data is
accurate, trustworthy, and compliant with regulations, which is crucial for
decision-making and maintaining database reliability.
Types of Data Integrity:
1. Entity Integrity: Ensures each record has a unique identifier (Primary
Key).
2. Referential Integrity: Ensures relationships between tables remain
valid (Foreign Key).
3. Domain Integrity: Ensures data values fall within a valid range (using
data types and constraints).
4. User-Defined Integrity: Ensures business rules are followed (using
triggers or check constraints).
How SQL Enforces Data Integrity:
 Primary Key: Uniquely identifies each record.
SQL Test for Freshers

 Foreign Key: Maintains relationships between tables.


 Unique: Ensures column values are unique.
 Check: Enforces specific conditions on column values.
 Not Null: Prevents null values in critical columns.
 Default: Provides default values if none are supplied.
 Triggers: Automate enforcement of complex rules

8. What is the difference between DELETE, TRUNCATE,


and DROP?
o Discuss the implications of each operation.
Ans-
These three SQL operations are used for removing data or structures, but
they have significant differences in how they function and their
implications.

1. DELETE:
 Purpose: Removes rows from a table based on a condition (can
delete specific rows).
 How it Works:
o It is a DML (Data Manipulation Language) command.
o Removes rows one at a time.
o Can be used with a WHERE clause to delete specific records or
without it to delete all rows.
o It generates log entries for each deleted row, which allows for
rollback (transactions).
o Triggers associated with the table will be fired during a delete
operation.
 Implications:
o Can be rolled back (if in a transaction).
o Slower compared to TRUNCATE because of row-by-row
deletion and logging.
o Can be used to delete specific rows based on a condition.
2. TRUNCATE:
 Purpose: Removes all rows from a table, but does not remove the
table structure.
 How it Works:
o It is a DDL (Data Definition Language) command.
o Faster than DELETE because it does not log each row deletion
individually.
o It is non-recoverable unless wrapped in a transaction.
o Does not fire triggers.
o Resets any identity columns (e.g., auto-increment) to their
starting value.
 Implications:
o Cannot be rolled back (unless inside a transaction, depending
on the DBMS).
o Faster than DELETE due to minimal logging and fewer
resources required.
o All rows are removed and cannot be filtered by a condition.
SQL Test for Freshers

3. DROP:
 Purpose: Removes a table (or other database objects) from the
database entirely.
 How it Works:
o It is a DDL command.
o Deletes the entire table structure along with all the data.
o Does not allow the table to be recovered unless there's a
backup.
o Removes all associated indexes, constraints, and triggers.
 Implications:
o Cannot be rolled back (unless in a transaction or using a
backup).
o Removes the table completely, including the structure and
data.
o More destructive than DELETE or TRUNCATE since it eliminates
the table itself.
Affects Rollback
Operation Affects Data Speed Triggers Fired
Structure Capability

Removes
specific rows Yes (if in
DELETE No Slower Yes
based on transaction)
condition

Removes all No (unless in


TRUNCATE No Faster No
rows transaction)

Removes all Yes, removes


DROP No No
rows the table itself

9. What are aggregate functions, and how are they used?


o List some common aggregate functions with examples.
Ans-
Aggregate functions are SQL functions that operate on a set of values (or
rows) and return a single summarized result. They are typically used to
calculate a summary value for a group of rows, often in combination with
the GROUP BY clause.
Common Aggregate Functions
1. COUNT()
o Returns the number of rows in a specified table or group.
2. SUM()
o Adds up the values of a specified numeric column.
3. AVG()
o Calculates the average value of a numeric column.
4. MIN()
o Finds the smallest value in a specified column.
5. MAX()
o Finds the largest value in a specified column.
SQL Test for Freshers

6. GROUP_CONCAT() / STRING_AGG()
o Concatenates multiple values from a group into a single
string.
How Aggregate Functions Are Used
 With GROUP BY Clause: Used to perform calculations on each group
of data.
 Without GROUP BY Clause: Can be used to calculate an overall
summary across all rows.
 With HAVING Clause: Filters groups based on the result of aggregate
functions.

10. What is the purpose of the WHERE clause?


o Explain how it filters records in a SQL query.
Ans-
Purpose of the WHERE Clause in SQL
The WHERE clause in SQL is used to filter records in a query based on
specified conditions. It allows you to retrieve only the rows that meet a
certain criteria, making it an essential part of SQL queries when you need
to select, update, or delete data based on specific conditions.
How the WHERE Clause Filters Records
 Condition Specification: The WHERE clause defines the condition(s)
that must be satisfied for a row to be included in the result set. This
condition can involve one or more column values, and the criteria
can be based on comparison operators, logical operators, or pattern
matching.
 Filter Operation:
o The query scans the table and checks each row to see if it
satisfies the condition.
o Only the rows that meet the condition specified in the WHERE
clause will be returned or affected.
 Types of Conditions:
o Comparison Operators: =, !=, <, >, <=, >=
o Logical Operators: AND, OR, NOT
o Pattern Matching: LIKE, REGEXP
o Range Checking: BETWEEN, IN
o Null Checking: IS NULL, IS NOT NULL
Examples of Where Clause Filtering
 Basic Condition: Filters rows where a column value matches a
specified condition.
o E.g., finding records where the Salary is greater than 50000.
 Multiple Conditions: Combines conditions using logical operators
(AND, OR).
o E.g., filtering records where Salary is greater than 50000 and
the Department is "Sales".
 Pattern Matching: Filters rows based on patterns in string values
using LIKE.
o E.g., filtering records where a name starts with "A".
Summary
 The WHERE clause filters records based on specified conditions.
SQL Test for Freshers

 It narrows down the result set to include only rows that meet the
criteria defined in the clause.
 It supports various operators and expressions for advanced filtering.

Practical Questions
1. Write an SQL query to retrieve all employees from
the employees table who were hired after January 1, 2020.
Ans-
SELECT *
FROM employees
WHERE hire_date > '2020-01-01';
2. Create a query to calculate the total sales from a sales table
grouped by each product.
Ans-
SELECT product_id, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY product_id;
3. Write an SQL statement to find all distinct job titles in
the employees table.
Ans-
SELECT DISTINCT job_title
FROM employees;
4. Create a query to join customers and orders tables and
display the customer names along with their order dates.
Ans-
SELECT c.customer_name, o.order_date
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id;
5. Write a query to update the salary of all employees in
the departments table by increasing it by 10%.
Ans-
UPDATE employees
SET salary = salary * 1.10;

Aptitude Questions
1. If a table has 150 records and you apply a filter that
matches 30 of them, what percentage of the total records
will be returned?
Ans-
If a table has 150 records and a filter matches 30 of them, the
percentage of records returned can be calculated as:
Percentage=(Matching RecordsTotal Records)×100\text{Percentage} =
\left( \frac{\text{Matching Records}}{\text{Total Records}} \right) \
times 100Percentage=(Total RecordsMatching Records)×100
Percentage=(30150)×100=20%\text{Percentage} = \left( \frac{30}
{150} \right) \times 100 = 20\%Percentage=(15030)×100=20%
20% of the total records will be returned.
SQL Test for Freshers

2. In a dataset with 1000 records, if 100 records are deleted,


what will be the new total number of records?
Ans-
If you have 1000 records and delete 100 of them, the new total number
of records will be:
New Total=Original Total−Records Deleted\text{New Total} = \
text{Original Total} - \text{Records
Deleted}New Total=Original Total−Records Deleted
New Total=1000−100=900\text{New Total} = 1000 - 100 =
900New Total=1000−100=900
The new total number of records will be 900.

3. If you have a table with 4 columns, how many unique


combinations of 2 columns can be selected?
Ans-
The number of unique combinations of 2 columns that can be selected
from 4 columns is calculated using combinations formula C(n,r)=n!r!
(n−r)!C(n, r) = \frac{n!}{r!(n-r)!}C(n,r)=r!(n−r)!n!, where nnn is the
total number of columns and rrr is the number of columns to be
selected:
C(4,2)=4!2!(4−2)!=4×32×1=6C(4, 2) = \frac{4!}{2!(4-2)!} = \frac{4 \
times 3}{2 \times 1} = 6C(4,2)=2!(4−2)!4!=2×14×3=6
There are 6 unique combinations of 2 columns that can be selected
from 4 columns.

4. In a situation where you have 200 records and you sort them
in descending order, how many comparisons might be
needed in the worst case?
Ans-
In the worst case, the number of comparisons required for sorting 200
records using a comparison-based sorting algorithm like QuickSort or
MergeSort is O(nlog⁡n)O(n \log n)O(nlogn). For 200 records:
Comparisons=200×log⁡2(200)\text{Comparisons} = 200 \times \
log_2(200)Comparisons=200×log2(200)
Comparisons≈200×7.64=1528\text{Comparisons} \approx 200 \times
7.64 = 1528Comparisons≈200×7.64=1528
In the worst case, approximately 1528 comparisons might be needed.

5. If an index is applied to a column in a table, what effect does


it have on the performance of SELECT queries?
Ans-
When an index is applied to a column in a table:
 Improves SELECT query performance by allowing the database
to quickly locate the rows that match the query conditions (using a
tree structure or other methods to minimize the search time).
 The performance gain is particularly significant when querying
large tables or filtering by columns that have high selectivity (few
duplicate values).
SQL Test for Freshers

 Drawback: Indexes can slow down INSERT, UPDATE, and DELETE


operations because the index needs to be updated every time the
data in the indexed column changes.
Applying an index to a column generally improves SELECT query
performance, especially for large tables or when filtering by indexed
columns.

You might also like