Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

SQL interview questions

The document provides a comprehensive overview of SQL, covering basic to advanced interview questions, including definitions, uses, commands, and key concepts such as normalization, joins, and indexing. It explains SQL functionalities like data manipulation, constraints, and the differences between various SQL commands and clauses. Additionally, it addresses practical scenarios and data analysis-focused SQL questions, making it a valuable resource for SQL interview preparation.

Uploaded by

arunkumar799392
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

SQL interview questions

The document provides a comprehensive overview of SQL, covering basic to advanced interview questions, including definitions, uses, commands, and key concepts such as normalization, joins, and indexing. It explains SQL functionalities like data manipulation, constraints, and the differences between various SQL commands and clauses. Additionally, it addresses practical scenarios and data analysis-focused SQL questions, making it a valuable resource for SQL interview preparation.

Uploaded by

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

SQL(STRUCTURED QUERY LANGUAGE)

Basic SQL Interview Questions


1. What is SQL? Explain its uses.

What is SQL?

SQL (Structured Query Language) is a programming language used to interact with relational
databases. It helps in managing, querying, and manipulating data effectively.

Uses of SQL

Query Data: Retrieve specific data using SELECT.

Manipulate Data: Add, update, or delete records (INSERT, UPDATE, DELETE).

Manage Schema: Create or modify database structures (CREATE, ALTER).

Control Access: Grant or revoke user permissions (GRANT, REVOKE).

Ensure Data Integrity: Enforce constraints like PRIMARY KEY and FOREIGN KEY.

Perform Analysis: Use aggregate functions (SUM, AVG) and GROUP BY for reports.

Handle Transactions: Maintain data integrity with COMMIT and ROLLBACK.

2. What are the different types of SQL commands?

o DDL (Data Definition Language), DML (Data Manipulation Language), DCL (Data
Control Language), TCL (Transaction Control Language), and DQL (Data Query
Language).

3. What is the difference between DELETE and TRUNCATE?

Feature DELETE TRUNCATE


Purpose Deletes specific rows from a Removes all rows from a table.
table.
Filter Can use WHERE clause to delete Cannot use WHERE; removes all rows.
specific rows.
Logging Fully logged (slower). Each row Minimal logging for performance.
deletion is logged.
Rollback Can be rolled back using Can be rolled back only if wrapped in a
ROLLBACK. transaction.
Constraints Triggers and constraints (like Does not enforce triggers but checks
foreign keys) are enforced. constraints.
Resets Does not reset Resets AUTO_INCREMENT to the default
Identity? AUTO_INCREMENT values. value.
Speed Slower for large datasets. Faster as it doesn’t log individual rows.
Usage Use when you want to delete Use when you want to quickly clear all
specific rows. data.
4. What are constraints in SQL? List types.

o PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, DEFAULT.

5. What is the difference between a PRIMARY KEY and a UNIQUE KEY?

Feature PRIMARY KEY UNIQUE KEY

Purpose Uniquely identifies each Ensures unique values in a column


record in a table. but allows one NULL.
Uniqueness Values must be unique for all Values must also be unique for all
rows. rows.
NULL Values Does not allow NULL values. Allows a single NULL value.
Number per Only one PRIMARY KEY is Multiple UNIQUE KEYS are
Table allowed per table. allowed in a table.
Indexing Automatically creates a Creates a non-clustered index by
clustered index. default.
Relationship Used to establish Not generally used for relationships
relationships between but ensures uniqueness.
tables.

6. What is a foreign key in SQL?

A Foreign Key is a column in one table that refers to the Primary Key of another table,
creating a relationship between the two tables and ensuring data integrity.

Key Features

1. Maintains Relationships: Links two tables (parent-child).

2. Data Validation: Ensures values in the foreign key column exist in the referenced table.

3. Cascading Actions: Supports ON DELETE and ON UPDATE rules (e.g., CASCADE, SET NULL).

Example

Parent Table: Departments

sql

CopyEdit

CREATE TABLE Departments (

dept_id INT PRIMARY KEY,

dept_name VARCHAR(50)

);
Child Table: Employees

sql

CopyEdit

CREATE TABLE Employees (

emp_id INT PRIMARY KEY,

emp_name VARCHAR(100),

dept_id INT,

FOREIGN KEY (dept_id) REFERENCES Departments(dept_id)

);

Here, dept_id in Employees is the Foreign Key referencing dept_id in Departments.

7. What is a JOIN? Explain its types.

o INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN, SELF JOIN.

8. What is normalization? Explain its types (1NF, 2NF, 3NF, BCNF).

Normalization in SQL

Normalization is the process of organizing data in a database to eliminate redundancy and


improve data integrity.

Types of Normalization

1. 1NF (First Normal Form)

o Ensures atomic values (no repeating groups).

o Each column contains unique, indivisible values.

o Example: Split multiple values in one column into multiple rows.

2. 2NF (Second Normal Form)

o Achieved by being in 1NF.

o Removes partial dependency (non-key columns should depend on the entire


primary key).

o Example: Split tables to ensure all non-key attributes depend on the whole primary
key.

3. 3NF (Third Normal Form)

o Achieved by being in 2NF.

o Removes transitive dependency (non-key columns should not depend on other non-
key columns).
o Example: Remove columns that depend on other non-key columns (e.g., location
depending on department).

4. BCNF (Boyce-Codd Normal Form)

o Achieved by being in 3NF.

o Every determinant (column that determines others) is a candidate key.

o Example: Split tables where a non-candidate key column determines other columns.

Summary

 1NF: Atomic values.

 2NF: No partial dependencies.

 3NF: No transitive dependencies.

 BCNF: Every determinant is a candidate key.

9. What is denormalization? When is it used?

Denormalization is the process of introducing redundancy into a database to improve read


performance by combining tables or duplicating data.

When is Denormalization Used?

1. Performance Optimization: To speed up read-heavy queries by reducing the need for


complex joins.

2. Simplify Queries: To simplify complex queries that require data from multiple tables.

3. Reporting: In data warehouses or OLAP systems for faster reporting and aggregation.

4. Reduce Joins: When frequent joins slow down performance.

When Not to Use?

 When data integrity is a priority, as it may lead to inconsistencies.

 In systems with frequent updates, as they become more complex to maintain.

Key takeaway: Denormalization is used to optimize for faster reads but may lead to
redundancy and maintenance challenges.

10. What is the difference between WHERE and HAVING clauses?

Feature WHERE HAVING


Purpose Filters rows before grouping Filters groups after aggregation (used
(used with SELECT, UPDATE, with GROUP BY).
DELETE).
Applies to Rows in the database table. Groups of rows created by GROUP BY.
Used with Can be used without GROUP Used with GROUP BY and aggregate
BY. functions.
Can Filter Regular column values (non- Aggregated data (e.g., COUNT, SUM,
aggregated). AVG).
Example SELECT * FROM Employees SELECT department, COUNT(*) FROM
WHERE age > 30; Employees GROUP BY department
HAVING COUNT(*) > 5;

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

Feature UNION UNION ALL


Duplicates Removes duplicate rows between Includes all rows, even duplicates.
the result sets.
Performance Slower, as it checks for duplicates Faster, since it doesn’t check for duplicates.
and removes them.
Result Returns only unique rows across all Returns all rows, including duplicates.
queries.
Usage Used when you want distinct results. Used when you want all rows, including dup

12. What is the difference between an alias and a subquery?

Feature Alias Subquery


An alias is a temporary name given
A subquery is a query nested inside another
Definition to a table or column for ease of
used to retrieve data for the outer query.
reference in a query.
Used to retrieve intermediate data for the o
Used to simplify and shorten long
Purpose query, often for filtering, aggregation, or
table or column names.
comparison.
Appears in the SELECT, FROM, or Appears in SELECT, WHERE, or FROM clau
Location
WHERE clauses. enclosed in parentheses.
Local to the query in which it's Can return a single value or a result set and i
Scope
defined. executed independently of the main query.
SELECT * FROM Employees WHERE
SELECT first_name AS Name department_id IN (SELECT department_
Example FROM Employees; FROM Departments WHERE dept_name
'HR');

Key Difference:

 Alias: A temporary name for columns or tables to make queries easier to read.

 Subquery: A nested query used to retrieve data that will be used by the outer query

Intermediate SQL Interview Questions

1. What is a view? How is it different from a table?


A View is a virtual table in a database that presents data from one or more underlying tables
through a SELECT query. It does not store data itself but retrieves it dynamically when
accessed. Views can simplify complex queries and can be used to present data in a specific
format.

Feature View Table


Does not store data; it displays
Data Storage Stores data physically in the database.
data from underlying tables.
Defined by a SELECT query
A physical structure that holds data
Definition that pulls data from one or
organized in rows and columns.
more tables.
Can be updatable if it’s based
Updatability on simple queries (usually on a Can be updated directly.
single table).
Used for presenting data in a
Stores and manages actual data in the
Purpose specific format or combining
database.
data from multiple tables.
May be slower, as it executes
Faster, as it holds actual data for quick
Performance the query each time the view is
access.
accessed.
CREATE VIEW
CREATE TABLE Employees (emp_id
Employee_View AS SELECT
Example * FROM Employees WHERE
INT, emp_name VARCHAR(100),
dept_id INT);
dept_id = 1;

Key Difference:

 View: Virtual, does not store data, used for presenting or simplifying queries.

 Table: Physical storage, holds data permanently.

2. What is an index? What are its types?

o Clustered Index, Non-clustered Index, Unique Index.

3. What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?

Function RANK() DENSE_RANK()


Skips ranks for ties (e.g., two
No gaps in ranks for ties (e.g., two tied
Ties Handling tied values get rank 1, the next
values get rank 1, the next gets rank 2).
gets rank 3).
When you need ranks with
Use Case When you need ranks without gaps for ties.
gaps for ties.
Example:

1. RANK():
Same values get the same rank, but subsequent rows have skipped ranks.

2. DENSE_RANK():
Same values get the same rank, but no rank is skipped.
3. ROW_NUMBER():
Every row gets a unique number, no matter if values are the same.

4. Explain the concept of a CTE (Common Table Expression).

A CTE (Common Table Expression) is a temporary result set in SQL that you can reference
within a SELECT, INSERT, UPDATE, or DELETE statement. It is defined using the WITH clause,
and it improves query readability and maintainability, especially for complex queries.

Key Features of CTE:

1. Temporary: It exists only during the execution of a single query.

2. Readability: Helps break down complex queries into simpler, more manageable parts.

3. Recursion: CTEs can be recursive, which is useful for querying hierarchical data (e.g.,
organizational charts, bill of materials).

4. Reference: You can reference the CTE multiple times in the main query.

Syntax:

sql

CopyEdit

WITH CTE_Name AS (

-- Query defining the CTE

SELECT column1, column2

FROM table

WHERE condition

-- Main query referencing the CTE

SELECT * FROM CTE_Name;

Example:

sql

CopyEdit

WITH TopEmployees AS (

SELECT EmployeeID, Name, Salary

FROM Employees

WHERE Salary > 50000

)
SELECT * FROM TopEmployees;

 Explanation: The WITH clause creates a CTE called TopEmployees, which contains employees
earning more than 50,000. The main query then selects all the records from this CTE.

When to Use CTE?

1. Simplifying complex joins or subqueries.

2. Recursion (like traversing hierarchical data).

3. Improving query organization.

Key Difference with Subqueries:

 CTEs can be self-referenced and used multiple times in the same query, whereas subqueries
are executed only once and are embedded in the main query.

5. What are aggregate functions in SQL? Provide examples.

o Examples: COUNT(), SUM(), AVG(), MAX(), MIN().

6. What is a stored procedure? How is it different from a function?

7. What are triggers in SQL? Provide a use case.

8. What is the difference between a correlated subquery and a regular subquery?

9. How do you handle NULL values in SQL?

o Use functions like IS NULL, IS NOT NULL, COALESCE(), and NULLIF().

10. Explain the difference between a CROSS JOIN and an INNER JOIN.

Advanced SQL Interview Questions

1. How does indexing affect performance? When should you use or avoid it?

2. What is a transaction in SQL? Explain ACID properties.

3. What is a window function? Provide examples.

o Examples: ROW_NUMBER(), RANK(), NTILE(), LAG(), LEAD().

4. What is the difference between a materialized view and a regular view?

5. How do you optimize a slow SQL query?

o Indexing, query restructuring, avoiding SELECT *, using EXPLAIN plans, etc.

6. Explain partitioning in SQL. What are the types?

o Range, List, Hash, Composite Partitioning.

7. What are database locks? Explain the types.

o Shared lock, Exclusive lock, Deadlocks.


8. What are the different types of relationships in a database?

o One-to-One, One-to-Many, Many-to-Many.

9. What is a recursive query? Provide an example.

10. How do you write a query to find the second-highest salary in a table?

sql

CopyEdit

SELECT MAX(salary)

FROM employees

WHERE salary < (SELECT MAX(salary) FROM employees);

Scenario-Based Questions

1. Write a query to fetch employees who joined in the last 6 months.

2. Write a query to find duplicate rows in a table.

sql

CopyEdit

SELECT column1, column2, COUNT(*)

FROM table_name

GROUP BY column1, column2

HAVING COUNT(*) > 1;

3. Write a query to find customers who have made more than 5 purchases.

4. How would you design a query to retrieve the top N records from a table?

sql

CopyEdit

SELECT * FROM table_name ORDER BY column_name DESC LIMIT N;

5. Write a query to fetch employees with the same salary in a table.

6. Write a query to find employees with the highest bonus in each department.

sql

CopyEdit

SELECT department_id, MAX(bonus)

FROM employees

GROUP BY department_id;
7. How would you delete duplicate rows from a table?

8. Write a query to find customers who didn’t make any purchases.

Data Analysis-Focused SQL Questions

1. How would you calculate a running total in SQL?

2. Write a query to calculate the percentage of sales for each product.

3. How do you calculate the median in SQL?

4. Write a query to group data by month and calculate the total revenue.

5. Explain how you would use SQL for A/B testing analysis.

You might also like