Skip to main content
Home  /  Knowledge Hub  /  Interview Questions

Interview Questions& Model Answers

Real questions. Real answers. Built from 20 years of actual hiring and being hired.

1,774
Total Questions
89
Technologies
7
Levels
✕ Clear filters

Showing 3 questions · Junior · SQL fundamentals

Clear all filters
SQL-JR-001 Can you explain the purpose of a primary key in a SQL database and how it is different from a foreign key?
SQL fundamentals Databases Junior
3/10
Answer

A primary key is a unique identifier for a record in a table, ensuring that no two records can have the same value in that column. A foreign key, on the other hand, is a reference to a primary key in another table, establishing a relationship between the two tables.

Deep Explanation

The primary key serves as a unique identifier for each record in a SQL table, which means that it must contain unique values and cannot contain NULLs. This uniqueness allows for efficient data retrieval and ensures data integrity. Most commonly, a primary key is set on an ID column, which is often auto-incremented. In contrast, a foreign key is used to establish a link between the data in two tables. It is a column or a set of columns in one table that refers to the primary key in another table. This relationship allows for complex queries that can join data across multiple tables, which is critical for normalized database designs.

Understanding the distinction between primary and foreign keys is crucial for designing a relational database efficiently. It helps maintain data integrity by ensuring that references between tables are valid and consistent. Without proper usage of these keys, databases can face issues such as orphaned records where a foreign key points to a non-existent primary key.

Real-World Example

In a retail database, the 'Customers' table might have a primary key called 'CustomerID' to uniquely identify each customer. The 'Orders' table would then use a foreign key called 'CustomerID' to link each order back to the corresponding customer. This allows you to run queries to find all orders placed by a specific customer, leveraging the relationship established by these keys.

⚠ Common Mistakes

One common mistake is to use non-unique or NULL values as a primary key, which can lead to data integrity issues and difficulty in data retrieval. Another mistake is neglecting to properly define foreign keys, which can result in orphaned records and inconsistencies in data across related tables. Failing to enforce these relationships can complicate data management and lead to erroneous results in queries.

🏭 Production Scenario

In a production environment, you might face issues if foreign keys are not set up correctly. For instance, if a developer forgets to add a foreign key constraint in a customer order management system, it could allow orders to be recorded without a valid customer, resulting in incomplete data and making it difficult to analyze customer behavior or generate accurate reporting.

Follow-up Questions
How would you define a composite primary key? Can foreign keys be NULL? What are the implications of not using foreign keys? How would you approach database normalization??
ID: SQL-JR-001  ·  Difficulty: 3/10  ·  Level: Junior
SQL-JR-002 Can you describe a situation where you had to troubleshoot a slow-running SQL query, and what steps you took to identify and resolve the issue?
SQL fundamentals Behavioral & Soft Skills Junior
4/10
Answer

I once encountered a slow query that was taking too long to execute. I started by analyzing the execution plan to identify bottlenecks, then I checked for missing indexes and optimized the SQL statement by simplifying it and removing unnecessary joins. After making these adjustments, the query performance improved significantly.

Deep Explanation

Troubleshooting a slow SQL query often involves a systematic approach. First, you should check the execution plan, which provides insights into how the database engine is executing the query. By identifying operations that take significant time, such as full table scans or large joins, you can pinpoint performance bottlenecks. Missing indexes are a common culprit; adding appropriate indexes can dramatically reduce the execution time of queries. Additionally, simplifying the query—by reducing the number of joins or filtering results sooner—can also alleviate performance issues. Always remember to test your changes in a development environment before applying them to production to avoid unintended consequences.

Real-World Example

In a previous project, we had a query joining multiple tables to generate a sales report, which started taking several minutes to run as our data grew. After analyzing the execution plan, I noticed that it was performing full table scans due to missing indexes on frequently queried columns. I added those indexes, which reduced the query execution time from five minutes to under ten seconds, allowing our team to access data quickly and improve overall workflow efficiency.

⚠ Common Mistakes

One common mistake is jumping to conclusions about performance issues without first examining the execution plan. This can lead to unnecessary changes that don’t address the root cause. Another mistake is ignoring the importance of indexing and how it can affect query performance. Developers sometimes add indexes based on assumptions rather than actual query performance needs, which can lead to overhead during data modifications and slower overall performance. It's crucial to analyze the specific needs of each query before making these decisions.

🏭 Production Scenario

In a production environment, I once saw a significant drop in application performance due to several slow-running SQL queries as the database grew. Team members were frustrated with long load times for reports. By troubleshooting these queries through execution plans and optimizing them, we were able to restore application performance and improve user satisfaction. This experience highlighted the importance of continuous learning and monitoring of our SQL queries, especially as data volume increases.

Follow-up Questions
What tools do you use to analyze query performance? Can you explain how indexes work and when you would use them? Have you ever had to refactor a complex query? What metrics do you track to assess SQL query performance??
ID: SQL-JR-002  ·  Difficulty: 4/10  ·  Level: Junior
SQL-JR-003 What is the purpose of using the GROUP BY clause in SQL, and how does it differ from the WHERE clause?
SQL fundamentals Algorithms & Data Structures Junior
4/10
Answer

The GROUP BY clause in SQL is used to aggregate data across rows that have the same values in specified columns. It differs from the WHERE clause, which filters rows before any aggregation occurs, while GROUP BY operates on the results of an aggregation.

Deep Explanation

The GROUP BY clause is essential for summarizing data in SQL. When you need to calculate aggregates like COUNT, SUM, AVG, or MAX for specific groups of rows, you use GROUP BY to specify the columns that define those groups. The key difference from the WHERE clause is that WHERE filters records before any grouping or aggregation takes place, whereas GROUP BY is applied after the filtering to organize the remaining records into groups for aggregation. If you try to aggregate without grouping, SQL will return an error since it wouldn’t know how to summarize the data correctly.

It's also important to note that when you use GROUP BY, all selected columns must either be included in the GROUP BY clause or be used in an aggregate function, as this specifies how the data should be combined. This behavior becomes crucial in maintaining data integrity and accuracy during queries.

Real-World Example

In a retail database, suppose you have a table of sales records with columns for product_id, sales_amount, and sale_date. If you want to find the total sales for each product over a month, you would use the GROUP BY clause on product_id and aggregate using SUM on sales_amount. This would allow you to get a clear picture of how much each product sold in that time period, which informs inventory and marketing strategies.

⚠ Common Mistakes

A common mistake is using the GROUP BY clause without understanding its interactions with the SELECT statement, often leading to errors or unexpected results. For instance, including a column in the SELECT that is neither grouped nor aggregated will produce an error. Another frequent error is neglecting to include non-aggregated fields in the GROUP BY clause, which can cause SQL to throw an error or produce incorrect results, leading to potential misinterpretation of data.

🏭 Production Scenario

In a financial report generation setting, data analysts often use the GROUP BY clause to summarize monthly expenditure by department. A junior developer might initially try to filter expenses with WHERE after grouping them, leading to incorrect results. Understanding the sequence of operation—first filtering with WHERE and then grouping with GROUP BY—becomes critical for accurate financial reporting.

Follow-up Questions
Can you describe a scenario where using GROUP BY would lead to performance issues? What happens if you use GROUP BY without any aggregate functions? How would you handle NULL values when grouping? Can you explain the significance of the HAVING clause in relation to GROUP BY??
ID: SQL-JR-003  ·  Difficulty: 4/10  ·  Level: Junior