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

st1

The document is a SQL test for freshers, covering both theory and practical questions. It includes topics such as SQL definitions, types of joins, keys, normalization, subqueries, aggregate functions, and transactions, along with practical SQL queries and aptitude questions. Each section provides definitions, explanations, and examples to aid understanding of SQL concepts and operations.

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)
2 views

st1

The document is a SQL test for freshers, covering both theory and practical questions. It includes topics such as SQL definitions, types of joins, keys, normalization, subqueries, aggregate functions, and transactions, along with practical SQL queries and aptitude questions. Each section provides definitions, explanations, and examples to aid understanding of SQL concepts and operations.

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/ 8

SQL Test for Freshers

Theory Questions
1. What is SQL?
o Describe its purpose and the types of operations it supports.
Ans- SQL (Structured Query Language) is a standard programming
language designed to manage and manipulate relational databases.
 Purpose:
o Retrieve, insert, update, and delete data in a database.
o Define database structures (DDL).
o Control database access and security.
 Operations:
o Data Querying: SELECT.
o Data Manipulation: INSERT, UPDATE, DELETE.
o Data Definition: CREATE, ALTER, DROP.
o Data Control: GRANT, REVOKE.

2. What is the difference between INNER JOIN and LEFT JOIN?


o Explain how each join works and provide examples.
Ans-
Aspect INNER JOIN LEFT JOIN

Returns all rows from the left table and


Returns only the rows where there is a match matching rows from the right table. Non-
Definition
in both tables. matching rows from the right table are
filled with NULL.

Includes only rows with matching keys in both Includes all rows from the left table,
Matching Rows
tables. regardless of a match in the right table.

Unmatched rows from the left table are


Unmatched Rows Unmatched rows are excluded. included with NULL values for columns
from the right table.

Usually as large as the left table or larger,


Result Size Usually smaller or equal to the smaller table.
depending on matches.

When you need all rows from the left table


Use Case When you need only rows with exact matches.
and optional matches from the right table.

Fetch all customers, including those who


Example (Concept) Fetch customers who placed orders.
didn’t place orders.

3. What are primary keys and foreign keys?


o Discuss their roles in database design and relationships.
Ans- Primary Key
 Definition: A column or a set of columns in a table that uniquely
identifies each row in that table.
 Key Characteristics:
o Must contain unique values.
o Cannot contain NULL values (enforces entity integrity).
SQL Test for Freshers

o Each table can have only one primary key.


 Purpose: Ensures that each record in a table is unique.

Foreign Key
 Definition: A column or a set of columns in a table that establishes
a relationship between the data in two tables. It references the
primary key in another table.
 Key Characteristics:
o Can have duplicate values.
o Can contain NULL values (if the relationship is optional).
o Used to enforce referential integrity.
 Purpose: Links two tables and maintains data consistency between
them.

4. What is normalization?
o Explain its importance and the different normal forms.
Ans- Normalization: Organizing database tables to reduce redundancy
and improve data integrity.
 Importance:
o Minimizes data anomalies.
o Improves storage efficiency.
 Normal Forms:
o 1NF: Atomic values, unique rows.
o 2NF: Satisfies 1NF, no partial dependency.
o 3NF: Satisfies 2NF, no transitive dependency.
o BCNF: Stronger form of 3NF.

5. What is a subquery in SQL?


o Describe what it is and provide an example of its usage.
Ans- Subquery in SQL
 Definition: A subquery is a query embedded within another query.
It provides data to the main query for further processing.
 Purpose: Used to perform operations that depend on results from
another query.

Types of Subqueries
1. Single-row Subquery: Returns exactly one value.
Example: Find the highest salary in a specific department.
2. Multi-row Subquery: Returns multiple rows.
Example: List employees working in multiple departments.
3. Correlated Subquery: Executes once for each row in the outer
query.
Example: Compare each employee’s salary to the average salary of
their department.
4. Nested Subquery: A subquery within another subquery.
Example: Find offices based on conditions derived from nested
conditions.

6. What is the difference between GROUP BY and ORDER BY?


SQL Test for Freshers

o Explain how each clause is used in SQL queries.


Aspect GROUP BY ORDER BY

Groups rows with the same Sorts the result set in a specific
Purpose
values into summary rows. order.

Used for aggregation (e.g., SUM,


Focus Used for sorting data.
AVG).

Typically used with aggregate Used without or with aggregate


Clause Usage
functions (COUNT, SUM, etc.). functions.

Executes before SELECT and Executes after SELECT and GROUP


Order of Execution
HAVING clauses. BY clauses.

Reorganizes rows in ascending or


Result Reduces rows to one per group.
descending order.

Syntax GROUP BY column_name `ORDER BY column_name [ASC

SELECT department,
SELECT name, salary FROM
SUM(salary) FROM
Example Employees GROUP BY
Employees ORDER BY salary
DESC;
department;

 GROUP BY:
 Groups rows with the same values in specified columns into one
group.
 Often used with aggregate functions like SUM, AVG, MAX, COUNT.
 Example Use Case: Calculate total sales per region.
 ORDER BY:
 Arranges rows in a specific order, either ascending (ASC) or
descending (DESC).
 Can be used independently or after GROUP BY.
 Example Use Case: Display a list of employees sorted by their
salary.

7. What is an index in SQL?


o Discuss its purpose and how it affects query performance.
Ans- Definition:
An index in SQL is a data structure that improves the speed of data
retrieval operations on a database table. It works like a book's index,
allowing the database to locate rows faster without scanning the entire
table.

Purpose of an Index:
SQL Test for Freshers

1. Faster Query Performance: Speeds up SELECT queries by quickly


locating rows based on indexed columns.
2. Efficient Sorting: Helps in sorting results when using ORDER BY or
GROUP BY.
3. Enforces Uniqueness: Unique indexes prevent duplicate values in
a column.
4. Primary Keys: Automatically create a unique index to ensure fast
lookups.

How It Affects Query Performance:


1. Positive Impact:
o Search Speed: Reduces the time for searches, especially in
large tables.
o Join Operations: Enhances performance during joins
involving indexed columns.
o Filters: Speeds up queries with WHERE clauses that use
indexed columns.
2. Negative Impact:
o Slower Insert/Update/Delete: Maintaining the index incurs
overhead, as changes to the data require updating the index
as well.
o Storage Usage: Indexes consume additional disk space.

Types of Indexes:
1. Single-column Index: Based on a single column.
2. Composite Index: Based on multiple columns.
3. Unique Index: Ensures all values in the indexed column are unique.
4. Full-text Index: Optimized for text searches.
5. Clustered Index: Determines the physical order of data in the
table (one per table).
6. Non-clustered Index: Creates a separate structure pointing to the
table data (can have multiple per table).

When to Use an Index:


 For columns frequently used in WHERE, JOIN, or ORDER BY clauses.
 For large tables where searching performance is critical.
 For primary and foreign key columns to enforce relationships and
speed lookups.

8. What are aggregate functions in SQL?


o List some common aggregate functions and their uses.
Ans-Definition:
Aggregate functions perform calculations on a set of values and return a single result. They
are commonly used with the GROUP BY clause to summarize data.
Key Features
 Can be used with or without the GROUP BY clause.
o Without GROUP BY: Applies the function to the entire table.
o With GROUP BY: Applies the function to each group.
SQL Test for Freshers

 Null values are ignored in calculations unless explicitly handled.

Examples of Usage (Without Code)


1. COUNT: Counting how many orders were placed.
2. SUM: Calculating the total revenue for a specific time period.
3. AVG: Determining the average age of students in a class.
4. MAX: Identifying the employee with the highest salary.
5. MIN: Finding the earliest date of an event in a calendar.

9. What is the purpose of the HAVING clause?


o Explain how it differs from the WHERE clause.
HAVING Clause in SQL
Definition:
The HAVING clause is used to filter groups of data after aggregation. It is
typically used with GROUP BY and aggregate functions (e.g., SUM, COUNT,
AVG, etc.).

Purpose:
 Filters the results of grouped data based on conditions applied to
aggregate functions.
 Ensures only groups that meet the specified criteria appear in the
result set.

Aspect HAVING WHERE

Filters groups after Filters rows before


Application Stage
aggregation. aggregation.
Works with aggregate
Cannot be used with
Use with Aggregates functions (e.g., SUM,
aggregate functions.
COUNT).

Comes after GROUP BY in Comes before GROUP BY


Clause Order
a query. in a query.

Scope Filters grouped data. Filters individual rows.

10. What is a transaction in SQL?


o Describe its properties (ACID) and significance.
Ans-Definition:
A transaction in SQL is a sequence of one or more SQL operations (such as INSERT, UPDATE,
DELETE) executed as a single unit of work. Transactions ensure that operations are completed
successfully or not executed at all, maintaining database integrity.

Property Description
SQL Test for Freshers

The transaction is treated as a single unit, which means it either completes


Atomicity entirely or does not happen at all. If one part of the transaction fails, the
entire transaction is rolled back.

The database must always be in a valid state before and after the transaction.
Consistency It ensures that the transaction takes the database from one consistent state to
another.

Transactions are isolated from each other. The intermediate state of a


Isolation transaction is invisible to other transactions until it is committed. It prevents
transactions from interfering with each other.

Once a transaction is committed, its changes are permanent and survive any
Durability system crashes. The changes are written to persistent storage (e.g., a hard disk
or database).

Practical Questions
1. Write an SQL query to find the second highest salary from
an employees table
Ans-SELECT MAX(Salary) AS SecondHighestSalary
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);
2. Create a query to count the number of employees in each
department from a departments table.
Ans- SELECT department_id, COUNT(employee_id) AS num_employees
FROM employees
GROUP BY department_id;
3. Write an SQL statement to retrieve all columns from
the products table where the price is greater than 100.
Ans- SELECT * FROM products WHERE price > 100;
4. Write a query to update the email of an employee in
the employees table where the employee ID is 5.
Ans- UPDATE Employees
SET Email = '[email protected]'
WHERE EmployeeID = 5;
5. Create a SQL query to delete all records from
a temp_users table that were created more than 30 days
ago.
Ans- DELETE FROM temp_users
WHERE created_at < CURRENT_DATE - INTERVAL 30 DAY;

Aptitude Questions
1. If a database has 2000 records and you want to find a
specific record with a binary search, how many comparisons
would it take in the worst case?
Ans-
SQL Test for Freshers

To find a specific record in a database using binary search, the


number of comparisons required in the worst case can be calculated
using the formula:
Comparisons=⌈log⁡2(N)⌉\text{Comparisons} = \lceil \log_2(N) \
rceilComparisons=⌈log2(N)⌉
Where:

 ⌈⌉\lceil \rceil⌈⌉ represents the ceiling function, which rounds up to the


 NNN is the number of records in the database.

nearest whole number.


For N=2000N = 2000N=2000 records:
log⁡2(2000)≈10.97\log_2(2000) \approx 10.97log2(2000)≈10.97

⌈10.97⌉=11\lceil 10.97 \rceil = 11⌈10.97⌉=11


Rounding up to the nearest whole number:

Thus, in the worst case, it would take 11 comparisons to find a


specific record in a database of 2000 records using binary search.

2. If a query takes 5 seconds to execute and you double the


dataset size, how would you expect the execution time to
change, assuming linear growth?
Ans-
If the execution time of a query grows linearly with the dataset size,
doubling the dataset would approximately double the execution time.
Given that the original dataset takes 5 seconds to execute:
 Initial dataset size: 5 seconds
 Doubled dataset size: 5 seconds × 2 = 10 seconds
Assumption:
This assumes linear growth, meaning the time taken for the query to
execute is directly proportional to the size of the dataset.
However, in real-world scenarios, query execution time may not always
grow linearly, especially if the database faces increased complexity
with the larger dataset (e.g., indexing, caching, joins).

3. In a table with 10 columns, how many possible combinations


of columns can be selected if you choose 3 at a time?
Ans-
To calculate the number of possible combinations of 3 columns selected
from a table with 10 columns, you use the combination 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 (10),
 rrr is the number of columns to be selected (3).
Substituting the values:
C(10,3)=10!3!(10−3)!=10!3!7!=10×9×83×2×1=120C(10, 3) = \
frac{10!}{3!(10 - 3)!} = \frac{10!}{3!7!} = \frac{10 \times 9 \times 8}
{3 \times 2 \times 1} = 120C(10,3)=3!(10−3)!10!=3!7!10!
=3×2×110×9×8=120
There are 120 possible combinations of 3 columns selected from a table
with 10 columns.
SQL Test for Freshers

4. If you have 5 tables and you need to join all of them, how
many total joins will be required?
Ans-
To calculate the total number of joins required to join 5 tables, you can
use the following formula:
Total Joins=Number of Tables−1\text{Total Joins} = \text{Number of
Tables} - 1Total Joins=Number of Tables−1
This is because, to join nnn tables, you need to perform n−1n - 1n−1
joins.
For 5 Tables:
Total Joins=5−1=4\text{Total Joins} = 5 - 1 = 4Total Joins=5−1=4
You will need 4 joins to join 5 tables.

5. If a database table has 50 rows and you apply a LIMIT


10 clause, how many rows will be returned?
Ans-
If a database table has 50 rows and you apply a LIMIT 10 clause, the
query will return 10 rows.
The LIMIT clause restricts the number of rows returned by the query,
regardless of how many rows are in the table.
The query will return 10 rows.

You might also like