Sql Interview Queries With Answers

Advertisement

SQL interview queries with answers are essential for candidates preparing for database-related job interviews. SQL, or Structured Query Language, is the standard programming language used for managing and manipulating relational databases. As organizations increasingly rely on data-driven decision-making, proficiency in SQL has become a highly sought-after skill. This article will provide a comprehensive overview of common SQL interview queries, categorized by their complexity, along with detailed explanations and answers to help you prepare effectively.

Types of SQL Interview Queries



SQL interview queries can be broadly categorized into three types based on their complexity:


  1. Basic SQL Queries

  2. Intermediate SQL Queries

  3. Advanced SQL Queries



Each category serves to test different levels of understanding and proficiency in SQL. Below, we explore each category in detail.

1. Basic SQL Queries



Basic SQL queries are designed to assess fundamental knowledge and skills in SQL. Here are some common queries you might encounter:

Query 1: Select All Columns from a Table



Question: Write a SQL query to select all columns from a table named `employees`.

Answer:
```sql
SELECT FROM employees;
```
This query retrieves all columns and rows from the `employees` table.

Query 2: Select Specific Columns



Question: Write a SQL query to select the `first_name` and `last_name` columns from the `employees` table.

Answer:
```sql
SELECT first_name, last_name FROM employees;
```
This query fetches only the specified columns from the `employees` table.

Query 3: Filtering Results with WHERE



Question: Write a SQL query to select all employees whose job title is 'Manager'.

Answer:
```sql
SELECT FROM employees WHERE job_title = 'Manager';
```
The `WHERE` clause filters the results based on the specified condition.

Query 4: Sorting Results



Question: Write a SQL query to select all employees and sort the results by `last_name` in ascending order.

Answer:
```sql
SELECT FROM employees ORDER BY last_name ASC;
```
The `ORDER BY` clause sorts the results based on the `last_name` column.

2. Intermediate SQL Queries



Intermediate SQL queries involve more complex operations and demonstrate a deeper understanding of SQL functions and concepts.

Query 5: Using Aggregate Functions



Question: Write a SQL query to find the total number of employees in the `employees` table.

Answer:
```sql
SELECT COUNT() AS total_employees FROM employees;
```
The `COUNT()` function counts all rows in the `employees` table.

Query 6: Grouping Results



Question: Write a SQL query to count the number of employees in each job title.

Answer:
```sql
SELECT job_title, COUNT() AS count FROM employees GROUP BY job_title;
```
The `GROUP BY` clause groups the results by `job_title` and counts the number of employees in each title.

Query 7: Joining Tables



Question: Write a SQL query to join the `employees` table with the `departments` table on `department_id`.

Answer:
```sql
SELECT e.first_name, e.last_name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;
```
This query retrieves employee names along with their respective department names using an inner join.

Query 8: Using Subqueries



Question: Write a SQL query to find employees who earn more than the average salary.

Answer:
```sql
SELECT FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
```
This query uses a subquery to calculate the average salary and filter employees earning above that average.

3. Advanced SQL Queries



Advanced SQL queries test your ability to handle complex scenarios and utilize advanced SQL features.

Query 9: Using Window Functions



Question: Write a SQL query to assign a rank to employees based on their salary within their department.

Answer:
```sql
SELECT first_name, last_name, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees;
```
The `RANK()` function assigns ranks to employees within their respective departments based on salary.

Query 10: Conditional Aggregation



Question: Write a SQL query to count the number of employees in each department, categorizing them as 'High Salary' or 'Low Salary' based on a threshold of 50000.

Answer:
```sql
SELECT department_id,
SUM(CASE WHEN salary > 50000 THEN 1 ELSE 0 END) AS high_salary_count,
SUM(CASE WHEN salary <= 50000 THEN 1 ELSE 0 END) AS low_salary_count
FROM employees
GROUP BY department_id;
```
This query uses conditional aggregation to count employees based on their salary relative to a defined threshold.

Query 11: Using Common Table Expressions (CTEs)



Question: Write a SQL query to find the department with the highest average salary using a CTE.

Answer:
```sql
WITH AverageSalaries AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT department_id, avg_salary
FROM AverageSalaries
WHERE avg_salary = (SELECT MAX(avg_salary) FROM AverageSalaries);
```
This query defines a CTE to calculate average salaries and then retrieves the department with the highest average salary.

Query 12: Using Full Outer Join



Question: Write a SQL query to perform a full outer join between the `employees` and `departments` tables.

Answer:
```sql
SELECT e.first_name, e.last_name, d.department_name
FROM employees e
FULL OUTER JOIN departments d ON e.department_id = d.department_id;
```
A full outer join retrieves all records from both tables, displaying null values where there is no match.

Conclusion



Preparing for SQL interviews requires a solid understanding of a wide range of queries and concepts. By practicing these SQL interview queries with answers, candidates can enhance their proficiency and confidence. Remember to not only memorize the queries but also understand the underlying principles, as this will help you tackle unexpected questions during interviews. With the right preparation, you can excel in your SQL interviews and secure the job you desire.

Frequently Asked Questions


What is SQL and why is it important in database management?

SQL, or Structured Query Language, is a standardized programming language used to manage and manipulate relational databases. It is important because it allows users to create, read, update, and delete data efficiently and securely.

Can you explain the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only the rows that have matching values in both tables, while LEFT JOIN returns all rows from the left table and the matched rows from the right table. If there is no match, NULL values will be returned for columns from the right table.

What are aggregate functions in SQL? Can you give examples?

Aggregate functions perform a calculation on a set of values and return a single value. Common examples include COUNT(), SUM(), AVG(), MIN(), and MAX(). These functions are often used with the GROUP BY clause to group results based on one or more columns.

How do you prevent SQL injection attacks?

To prevent SQL injection attacks, you should use prepared statements and parameterized queries, which separate SQL logic from data inputs. Additionally, validating and sanitizing user inputs, as well as applying the principle of least privilege for database access, can help mitigate risks.

What is normalization, and why is it important?

Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity. It involves dividing large tables into smaller, related tables and defining relationships between them. This is important because it enhances efficiency and minimizes data anomalies.

What is the purpose of the GROUP BY clause in SQL?

The GROUP BY clause is used to arrange identical data into groups. It is often used with aggregate functions to perform calculations on each group, such as finding the total sales for each product category.

What is the difference between a primary key and a foreign key?

A primary key is a unique identifier for each record in a table, ensuring that no duplicate entries exist. A foreign key, on the other hand, is a field in one table that links to the primary key of another table, establishing a relationship between the two tables.