SQL Test 2 - Copy (2)
SQL Test 2 - Copy (2)
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.
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.
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.
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
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.
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
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(nlogn)O(n \log n)O(nlogn). For 200 records:
Comparisons=200×log2(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.