Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views8 pages

SQL Interview QSN

Uploaded by

sujalsujal4777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

SQL Interview QSN

Uploaded by

sujalsujal4777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

50 SQL Interview Questions and Answers

Follow me : Rajat Jain for more Interview Questions for Data Analyst Role

This document provides a comprehensive list of 50 SQL interview questions along with their
answers. It is designed to help candidates prepare for SQL-related interviews by covering a
wide range of topics, from basic concepts to advanced queries. Whether you are a beginner
or an experienced professional, this guide will enhance your understanding of SQL and
improve your chances of success in interviews.

Basic SQL Questions


1. What is SQL?
• SQL (Structured Query Language) is a standard programming language used to
manage and manipulate relational databases. It allows users to create, read,
update, and delete data.

2. What are the different types of SQL commands?


• SQL commands are categorized into five types:
• DDL (Data Definition Language): CREATE, ALTER, DROP
• DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE
• DCL (Data Control Language): GRANT, REVOKE
• TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT
• DQL (Data Query Language): SELECT

Overview of SQL Command Types

DML
DDL DCL
Commands for
Commands for Commands for
manipulating
defining controlling access
data within
database to data
tables
structures

TCL DQL
Commands for Commands for
managing querying data
transaction from databases
processes

3. What is a primary key?


• A primary key is a unique identifier for a record in a table. It ensures that no two
rows have the same value in that column and cannot contain NULL values.

4. What is a foreign key?


• A foreign key is a field (or collection of fields) in one table that uniquely
identifies a row in another table. It establishes a relationship between the two
tables.

5. What is normalization?
• Normalization is the process of organizing data in a database to reduce
redundancy and improve data integrity. It involves dividing large tables into
smaller ones and defining relationships between them.

Intermediate SQL Questions


6. What are the different types of joins in SQL?
• The main types of joins are:

• INNER JOIN: Returns records with matching values in both tables.


• LEFT JOIN: Returns all records from the left table and matched records
from the right table.
• RIGHT JOIN: Returns all records from the right table and matched records
from the left table.
• FULL OUTER JOIN: Returns all records when there is a match in either left
or right table.

INNER JOIN LEFT JOIN

Matching Values Left Table Records


Both Tables Matched Right Table Records
Types of
FULL OUTER JOIN Joins in SQL RIGHT JOIN

Match in Left Table Right Table Records


Match in Right Table Matched Left Table Records

7. What is a subquery?
• A subquery is a query nested inside another query. It can be used in SELECT,
INSERT, UPDATE, or DELETE statements to perform operations based on the
results of the outer query.

8. What is an index?
• An index is a database object that improves the speed of data retrieval
operations on a table. It creates a pointer to the data in a table, allowing for
faster searches.

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


• UNION combines the results of two or more SELECT statements and removes
duplicate rows. UNION ALL combines the results and includes all duplicates.

10. What is a view?


• A view is a virtual table based on the result of a SELECT query. It does not store
data physically but provides a way to simplify complex queries and enhance
security.

Advanced SQL Questions


11. What is a stored procedure?
• A stored procedure is a precompiled collection of SQL statements that can be
executed as a single unit. It allows for code reuse and can accept parameters.

12. What is a trigger?


• A trigger is a special type of stored procedure that automatically executes in
response to certain events on a particular table, such as INSERT, UPDATE, or
DELETE.

13. What is the difference between clustered and non-clustered indexes?


• A clustered index determines the physical order of data in a table and can only
be created on one column. A non-clustered index creates a separate structure
from the data and can be created on multiple columns.

14. What is a transaction?


• A transaction is a sequence of one or more SQL operations that are executed as
a single unit of work. Transactions follow the ACID properties (Atomicity,
Consistency, Isolation, Durability).

15. What is the purpose of the GROUP BY clause?


• The GROUP BY clause is used to group rows that have the same values in
specified columns into summary rows, like COUNT, SUM, AVG, etc.

SQL Functions and Operators


16. What are aggregate functions?
• Aggregate functions perform calculations on a set of values and return a single
value. Common aggregate functions include COUNT, SUM, AVG, MAX, and MIN.

17. What is the difference between COUNT(*) and COUNT(column_name)?


• COUNT(*) counts all rows in a table, including NULLs. COUNT(column_name)
counts only the non-NULL values in that specific column.

Choose the appropriate COUNT function for your SQL query

COUNT(*) COUNT(column_name)
Counts all rows, Counts non-NULL values
including NULLs in a specific column

18. What is the purpose of the HAVING clause?


• The HAVING clause is used to filter records after the GROUP BY operation. It
allows for conditions to be applied to aggregate functions.
19. What are window functions?
• Window functions perform calculations across a set of table rows that are
related to the current row. They are used for tasks like running totals and
moving averages.

20. What is the COALESCE function?


• The COALESCE function returns the first non-NULL value in a list of arguments. It
is useful for handling NULL values in queries.

SQL Performance and Optimization


21. What is query optimization?
• Query optimization is the process of improving the performance of a SQL query
by analyzing and modifying its execution plan to reduce resource consumption
and execution time.

22. What are some common performance tuning techniques?


• Common techniques include:

• Using indexes effectively


• Avoiding SELECT *
• Writing efficient JOINs
• Analyzing execution plans
• Reducing the number of subqueries

Which performance tuning


technique should be used to
optimize SQL queries?

Use Indexes Avoid SELECT


Enhances query speed by Reduces unnecessary data
reducing data scan size retrieval, saving resources

Write Efficient JOINs Analyze Execution Plans


Optimizes data retrieval Provides insights into
from multiple tables query performance

23. What is a deadlock?


• A deadlock occurs when two or more transactions are waiting for each other to
release locks, resulting in a standstill. Database systems typically have
mechanisms to detect and resolve deadlocks.

24. What is the difference between a temporary table and a table variable?
• A temporary table is created in the tempdb database and can be accessed by
multiple sessions. A table variable is scoped to the batch, stored procedure, or
function in which it is declared.

25. What is the purpose of the EXPLAIN statement?


• The EXPLAIN statement provides information about how a SQL query will be
executed, including details about the execution plan, indexes used, and
estimated costs.
SQL Data Types and Constraints
26. What are the different data types in SQL?
• Common data types include:

• INT: Integer values


• VARCHAR: Variable-length string
• CHAR: Fixed-length string
• DATE: Date values
• FLOAT: Floating-point numbers

27. What are constraints in SQL?


• Constraints are rules applied to table columns to enforce data integrity.
Common constraints include PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL,
and CHECK.

28. What is the difference between a unique constraint and a primary key?
• A unique constraint ensures that all values in a column are different, while a
primary key uniquely identifies a row and cannot contain NULL values.

29. What is a CHECK constraint?


• A CHECK constraint limits the values that can be placed in a column based on a
specified condition. It ensures that data meets certain criteria.

30. What is the purpose of the DEFAULT constraint?


• The DEFAULT constraint provides a default value for a column when no value is
specified during an INSERT operation.

SQL Miscellaneous Questions


31. What is the difference between SQL and NoSQL?
• SQL databases are relational and use structured query language for defining and
manipulating data, while NoSQL databases are non-relational and can handle
unstructured data, offering flexibility in data storage.

32. What is a schema in SQL?


• A schema is a logical container for database objects such as tables, views, and
procedures. It helps organize and manage database objects.

33. What is the purpose of the ROLLBACK statement?


• The ROLLBACK statement undoes changes made during the current transaction,
reverting the database to its previous state.

34. What is a data warehouse?


• A data warehouse is a centralized repository that stores large volumes of
structured and unstructured data from multiple sources for analysis and
reporting.

35. What is the difference between OLTP and OLAP?


• OLTP (Online Transaction Processing) systems are designed for managing
transaction-oriented applications, while OLAP (Online Analytical Processing)
systems are optimized for complex queries and data analysis.
SQL Best Practices
36. What are some best practices for writing SQL queries?
• Best practices include:

• Using meaningful table and column names


• Avoiding unnecessary complexity
• Commenting code for clarity
• Testing queries for performance
• Regularly reviewing and optimizing queries

Database Query Optimization Process

Initial Database Queries

Use Meaningful Names

Avoid Complexity

Comment for Clarity

Test Performance

Review and Optimize

Optimized Database Queries

37. How can you prevent SQL injection attacks?


• Prevent SQL injection by using prepared statements, parameterized queries, and
input validation to ensure that user inputs do not alter the intended SQL
commands.

38. What is the importance of backups in SQL?


• Backups are crucial for data recovery in case of data loss, corruption, or system
failure. Regular backups ensure that data can be restored to a previous state.

39. What is the role of a database administrator (DBA)?


• A DBA is responsible for managing, maintaining, and securing a database
environment. Their tasks include performance tuning, backup and recovery, and
ensuring data integrity.

40. What is data integrity?


• Data integrity refers to the accuracy and consistency of data over its lifecycle. It
is maintained through constraints, validation rules, and proper database design.
SQL Scenario-Based Questions
41. How would you retrieve the second highest salary from a table?

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

42. How can you find duplicate records in a table?

SELECT column_name, COUNT(*)


FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1;

43. How would you update records in a table based on another table?

UPDATE target_table
SET target_column = source_table.source_column
FROM source_table
WHERE target_table.id = source_table.id;

44. How can you delete duplicate rows from a table?

DELETE FROM table_name


WHERE id NOT IN (SELECT MIN(id)
FROM table_name
GROUP BY column_name);

45. How would you calculate the total sales for each product?

SELECT product_id, SUM(sales_amount)


FROM sales
GROUP BY product_id;

SQL Advanced Scenario Questions


46. How can you implement pagination in SQL?

SELECT *
FROM table_name
ORDER BY column_name
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;
47. How would you find the most frequently sold product?

SELECT product_id, COUNT(*) AS frequency


FROM sales
GROUP BY product_id
ORDER BY frequency DESC
LIMIT 1;

48. How can you join three tables in SQL?

SELECT a.column1, b.column2, c.column3


FROM table_a a
JOIN table_b b ON a.id = b.a_id
JOIN table_c c ON b.id = c.b_id;

49. How would you create a temporary table?

CREATE TEMPORARY TABLE temp_table AS


SELECT * FROM original_table WHERE condition;

50. How can you retrieve the current date and time in SQL?

SELECT CURRENT_TIMESTAMP;

Follow me : Rajat Jain for more Interview Questions


(https://www.linkedin.com/in/rajatjain01/)

Check my Youtube Channel for Interview Preparation


(https://www.youtube.com/@rajatjain001)

You might also like