LogIn
I don't have account.

Top 50 SQL Interview Questions and Answers (Beginner to Intermediate)

DevSniper
17 Views

Preparing for an SQL interview? Whether you're just starting out or have a few years of experience, understanding what to expect can give you a competitive edge. Here’s a quick overview of the key topics and types of questions that are commonly asked in SQL interviews, tailored for both beginner and intermediate-level candidates.

For Beginners

If you are new in SQL, most interviews will start with foundational questions to assess your basic knowledge and experience.

  • Background and Experience : Be ready to talk about how long you've worked with SQL, what database systems you've used (e.g. MySQL, PostgreSQL, SQL Server etc.) and how confident you feel writing queries.
  • Core Concepts : Expect questions around what SQL is, its real-world applications and basic syntax.
  • SQL Components : Interviewers may quiz you on different types of SQL statements (like SELECT, INSERT, UPDATE, DELETE) data definition commands (CREATE, ALTER, DROP) and basic types of queries.

For Intermediate-Level Candidates

If you’re past the beginner stage, the focus shifts toward more practical and in-depth SQL knowledge

  • SQL Functions : You should be comfortable explaining and using aggregate functions (SUM, COUNT, AVG etc.), scalar functions and even custom user-defined functions.
  • Advanced SQL Commands : Interviewers often explore your understanding of relationships and constraints through topics like: Joins (INNER, LEFT, RIGHT, FULL), Keys (Primary vs Foreign), Indexing strategies, Relationships between tables etc
  • Database Design Principles : Expect questions that test your ability to optimize database structures, including: Normalization vs Denormalization, Use cases for DELETE vs TRUNCATE vs DROP etc
  • Complex Query Writing : You might be asked to solve problems using subqueries (both nested and correlated), GROUP BY clauses or even retrieve the Nth highest record using various approaches like LIMIT, ROW_NUMBER() or common table expressions etc.

✅ Tip : Practice writing queries by hand and explaining them out loud. Many interviews will include whiteboard rounds or live coding tasks where you’ll need to walk through your logic step by step.

General SQL Interview Questions for Beginners

Before diving into the technical side of things, interviewers typically start with a few general questions to understand your background and familiarity with SQL. These questions help them gauge your overall experience and comfort level with database technologies. Here are some common ones

1. Which SQL dialects or database systems have you worked with?

Be prepared to mention the database systems you’ve used, such as MySQL, PostgreSQL, Microsoft SQL Server, Oracle NoSQL or SQLite and highlight any differences you've noticed between them.

2. How would you rate your proficiency in SQL?

Be honest in your self-assessment whether you're a beginner, intermediate or advanced and support your answer with examples. For example, if you say you’re intermediate, you might mention you're confident with JOIN operations, aggregate functions and basic subqueries, but still learning about query optimization or window functions.

3. How long have you been using SQL and in what context?

Mention the timeframe (e.g. “about 1 year”, “about 2 years”) and give context like “during academic projects”, “through internships” or “in my current job.” Highlight how you’ve applied SQL practically such as building reports, managing user data or writing backend queries for a web application.

4. What types of tasks have you used SQL for?

List common use cases where you’ve applied SQL, such as

  • Writing reports and dashboards
  • Filtering and aggregating sales or user data
  • Cleaning up or migrating data
  • Creating database schemas or views

If possible, briefly describe one or two real-world scenarios that showcase your SQL usage.

5. Have you worked with any SQL client tools or database GUIs?

Mention tools like MySQL Workbench, DBeaver, pgAdmin, SSMS or any platform-specific IDEs you’ve used. Talk about how these tools helped you for example, visualizing data structures, debugging queries,or exploring schemas more efficiently.

6. Do you usually write queries manually or rely on query builders or GUIs?

Explain your preferred approach. If you prefer writing SQL manually, mention that it helps you better understand query logic and performance. If you use GUIs for rapid prototyping or schema exploration, that’s okay too just clarify that you understand what’s happening behind the scenes.

7. Have you integrated SQL with any programming languages?

You can mention any experience using SQL with Python (e.g., psycopg2, SQLAlchemy), Java (JDBC, Hibernate), C#, PHP, etc. This shows you understand how SQL fits into real-world applications and back-end workflows.

8. Can you describe a scenario where you solved a problem using SQL?

Think of a situation where SQL helped you extract insights, clean data, automate reports or fix an issue. For example: “I once used a CTE with ROW_NUMBER() to remove duplicate customer records based on email address. It saved a lot of manual cleanup time and improved report accuracy.”

9. Are you familiar with any ORM tools or libraries?

If you’ve used Object-Relational Mapping tools like SQLAlchemy (Python), Hibernate (Java), Entity Framework (C#), or Sequelize (JavaScript), mention them. Highlight how ORMs simplify data access but note that understanding raw SQL is still crucial for performance tuning and debugging.

10. How do you typically test or debug your SQL queries?

Talk about your approach, starting with small queries and adding complexity gradually, using LIMIT, checking sample results and tools like EXPLAIN or ANALYZE to inspect query performance. This demonstrates that you're systematic and thoughtful in your debugging process.

✅ Tip : Always try to answer with short real-world examples. It shows practical experience and makes your answers stand out from generic responses.

Technical SQL Interview Questions for Beginners

Let’s move on to technical questions that test your foundational SQL knowledge.

Tip : When answering technical questions, aim for clear, precise responses. Avoid going off-topic or overexplaining, as it can invite follow-up questions in areas you're less confident about. Stick to what you know well and use examples wherever possible to back up your understanding.

11. What is SQL and why is it used?

SQL (Structured Query Language) is a standardized language used to manage, query and manipulate relational databases. It allows you to retrieve, insert, update and delete data stored in tables. SQL is essential for tasks such as generating reports, handling transactional data, managing large datasets and integrating with backend applications.

12. What are SQL Dialects?

Different database vendors implement their own versions of SQL, known as dialects. While the core syntax remains consistent, each dialect may include unique extensions.

Common SQL Dialects are MySQL, PostgreSQL, Microsoft SQL Server (T-SQL), Oracle (PL/SQL), SQLite.

13. What are the different types of SQL statements?

SQL statements can be grouped into several categories

  • DDL (Data Definition Language) : Defines database structure (e.g., CREATE, ALTER, DROP)
  • DML (Data Manipulation Language) : Manages data within tables (e.g., INSERT, UPDATE, DELETE)
  • DQL (Data Query Language) : Used to fetch data (SELECT)
  • DCL (Data Control Language) : Controls access (e.g., GRANT, REVOKE)
  • TCL (Transaction Control Language) : Manages transactions (e.g., COMMIT, ROLLBACK, SAVEPOINT)

Understanding the purpose of each category helps clarify how SQL is used across database operations.

14 . What is the difference between WHERE and HAVING?

  • WHERE is used to filter rows before aggregation.
  • HAVING is used to filter groups after aggregation.
SELECT department, COUNT(*) 
FROM employees 
WHERE status = 'active' 
GROUP BY department 
HAVING COUNT(*) > 10;

In this example, WHERE filters only active employees before grouping, and HAVING ensures each group has more than 10 people.

Tip : Don't use HAVING when WHERE is sufficient. HAVING is more performance-intensive.

15. What are SQL joins? Explain different types.

Joins are used to combine rows from two or more tables based on a related column. The common types include

  • INNER JOIN: Returns records that match in both tables
  • LEFT JOIN: Returns all rows from the left table and matching ones from the right
  • RIGHT JOIN: Returns all rows from the right table and matching ones from the left
  • FULL OUTER JOIN / FULL JOIN : Returns all records from both tables, matching rows where possible. If there’s no match, the result will still include the row, with NULL values for the missing side.
  • CROSS JOIN : Returns the Cartesian product of two tables, i.e. all combinations of rows.
  • SELF JOIN : A table is joined with itself.

Knowing how and when to use each join is critical for building accurate queries in multi-table databases.

16. What is a primary key?

A primary key is a column (or a combination of columns) that uniquely identifies each row in a table. It must be unique and cannot contain NULL values. Every table should have one primary key to ensure data integrity and allow proper relationships between tables.

17. What is a UNIQUE Key in SQL?

A UNIQUE key is a constraint in SQL that ensures all values in a column (or combination of columns) are distinct, meaning no duplicate values are allowed in that column.

Unlike a primary key, a table can have multiple UNIQUE keys, but only one primary key. Also, while a primary key cannot contain NULLs, a UNIQUE key can allow a single NULL value (depending on the database system, like MySQL or PostgreSQL).

18. What is the different between Primary Key and Unique Key?

A Primary Key is a column (or combination of columns) that uniquely identifies each row in a table and does not allow NULL values. A Unique Key also enforces uniqueness across rows but allows one NULL value and is typically used for enforcing alternate or secondary unique constraints.

CREATE TABLE Employees (
  emp_id INT PRIMARY KEY,          -- uniquely identifies each employee
  email VARCHAR(100) UNIQUE,       -- email must be unique, NULL allowed
  phone VARCHAR(15) UNIQUE         -- phone must be unique, NULL allowed
);

Key differences between Primary Key and Unique Key

Feature Primary Key Unique Key
Uniqueness Must be unique Must be unique
NULL Values Allowed Not allowed Allowed (only one NULL per unique key in most DBMS)
Default Index Automatically creates a clustered index (in many DBMSs like SQL Server) Automatically creates a non-clustered index
Number per Table Only one Primary Key per table Can have multiple Unique Keys
Purpose Main identifier for a row Enforces uniqueness on other columns
Constraint Type Primary Key constraint Unique constraint
Composite Key Support Yes (can be made of multiple columns) Yes (can be made of multiple columns)
Enforces Entity Integrity Yes No
Syntax PRIMARY KEY UNIQUE

19. What is Normalization?

Normalization is the process of organizing data in a relational database to minimize redundancy and improve data integrity. It involves dividing large tables into smaller and related tables and defining relationships between them. This ensures efficient data storage and reduces anomalies during insert, update or delete operations.

Common forms include 1NF, 2NF and 3NF, each with stricter rules for eliminating duplication.

20. Explain 1NF (First Normal Form) with example

  • Each column must contain atomic (indivisible) values and each record must be unique.
  • No repeating groups or arrays.
  • Goal: Eliminate multivalued attributes.
Original Table (Not in 1NF)
StudentID Name Courses
1 John Math, Science
1NF Version (Atomic Values)
StudentID Name Course
1 John Math
1 John Science

21. Explain 2NF (Second Normal Form) with example

  • Rule: Must be in 1NF and no partial dependency (non-key attributes must depend on the whole primary key).
  • Applies to tables with composite primary keys.
Original Table (Violating 2NF)
StudentID CourseID StudentName CourseName
1 101 John Math

StudentName depends only on StudentID → partial dependency

2NF Version (Eliminating Partial Dependency)


Students Table
StudentID StudentName
1 John
Courses Table
CourseID CourseName
101 Math
Enrollment Table
StudentID CourseID
1 101

22. Explain 3NF (Third Normal Form) with example

  • Rule: Must be in 2NF and have no transitive dependency (non-key attributes should not depend on other non-key attributes).
  • All attributes must depend only on the primary key.
Original Table (Violating 3NF)
StudentID Name Department DeptHead
1 John Science Dr. Smith

DeptHead depends on Department, not directly on StudentID.

3NF Version (Removing Transitive Dependency)
Students Table
StudentID Name Department
1 John Science
Departments Table
Department DeptHead
Science Dr. Smith

23. What are aggregate functions in SQL?

Aggregate functions perform calculations on a set of values and return a single result. Common ones include

  • COUNT() – returns the number of rows
  • SUM() – adds up values
  • AVG() – returns the average
  • MAX() / MIN() – find the highest or lowest value

These are often used with GROUP BY to generate grouped summaries

24. What is a subquery?

A subquery is a query nested inside another SQL query. It can be used in SELECT, FROM or WHERE clauses to retrieve or filter data based on dynamic conditions. Subqueries can be

  • Correlated – refers to outer query values and runs once per row
  • Non-correlated – runs independently and returns a single result or set

25. Explain Non-Correlated Subquery

A non-correlated subquery executes independently of the outer query. It runs once and its result is used by the outer query.

Example : Find employees whose salary is higher than the average salary.

SELECT name, salary
FROM employees
WHERE salary > (
    SELECT AVG(salary)
    FROM employees
);
  • Here, the inner query calculates the average salary of all employees.
  • The outer query fetches the names and salaries of employees earning above average.
  • The subquery does not depend on each row of the outer query.

26. Explain Correlated Subquery

A correlated subquery depends on the outer query for its values. It executes once for each row processed by the outer query.

Example : Find employees who earn more than the average salary in their own department.

SELECT e1.name, e1.department, e1.salary
FROM employees e1
WHERE e1.salary > (
    SELECT AVG(e2.salary)
    FROM employees e2
    WHERE e2.department = e1.department
);
  • The subquery calculates the average salary per department.
  • For each employee in the outer query (e1), the subquery (e2) calculates the department's average salary.
  • This is a correlated subquery because the inner query refers to e1.department from the outer query.

27. What are the key applications of SQL?

Some key applications of SQL

  • Data Retrieval – Extract data using SELECT queries.
  • Data Modification – Add, update or delete records with INSERT, UPDATE and DELETE.
  • Database Management – Create or alter tables and schemas using DDL commands.
  • Access Control – Grant or revoke user permissions with GRANT and REVOKE
  • Transaction Handling – Ensure data integrity with COMMIT, ROLLBACK etc.
  • Data Analysis – Perform aggregations and reports using functions like SUM(), GROUP BY.
  • ETL and Migration – Used in data cleaning, transformation and system migrations.

28. What is a database?

A database is an organized collection of data that is stored and managed electronically. It allows data to be easily accessed, managed, updated and retrieved when needed.

In simple terms, think of a database as a digital filing cabinet where information is stored in structured formats, usually in tables consisting of rows and columns.

29. What are Key Features of a Database?

  • Data Storage : Databases store large volumes of structured data efficiently.
  • Data Retrieval : You can quickly search and fetch data using queries like SQL.
  • Data Manipulation : Supports adding, updating and deleting data easily.
  • Data Integrity : Ensures accuracy and consistency using constraints like PRIMARY KEY, FOREIGN KEY etc.
  • Security : Databases offer access control, encryption and authentication to protect data.
  • Concurrency Control : Allows multiple users to access data at the same time without conflicts.
  • Backup and Recovery : Enables automatic backups and restores in case of failure or loss.
  • Data Independence : You can change the structure of data (schema) without affecting the application logic.
  • ACID Compliance : Guarantees reliable transactions with Atomicity, Consistency, Isolation and Durability.
  • Scalability : Databases can scale up to handle more users or data volume.

Example Use Case : An e-commerce app uses a database to manage products, users, orders and payments securely and efficiently.

30. What is DBMS?

A DBMS (Database Management System) is software that creates, manages and interacts with databases. It provides tools and interfaces that allow users and applications to store, retrieve, update and delete data in a structured and secure way.

In simple terms, a DBMS acts as a middle layer between the user and the database, handling all the behind-the-scenes operations.

31. What is RDBMS?

An RDBMS (Relational Database Management System) is a type of DBMS that stores data in tabular form using rows and columns and manages relationships between those tables using keys (like primary keys and foreign keys).

In an RDBMS, each table is related to others through relational integrity rules, allowing complex queries and structured data management.

32. What are the differences Between DBMS and RDBMS

Both DBMS (Database Management System) and RDBMS (Relational Database Management System) are systems designed to manage data efficiently, but they differ significantly in terms of structure, functionality and use cases.

Feature DBMS RDBMS
Data Storage Stores data as files, documents or tables Stores data strictly in relational tables
Data Relationships No relationships between data entities Supports relationships via primary/foreign keys
Normalization Not supported Fully supports normalization to reduce redundancy
Data Integrity Limited Enforces integrity constraints (PK, FK, UNIQUE)
Multi-user Access Limited or not efficient Supports multiple concurrent users with consistency
ACID Transactions Not guaranteed Fully ACID-compliant for reliable transactions
Security & Access Control Basic or minimal Advanced user roles and permission handling
Examples Microsoft Access, File System, XML DB MySQL, PostgreSQL, Oracle, SQL Server
Scalability Suitable for small apps or single users Suitable for enterprise apps and large systems

Note : All RDBMS are DBMS, but ❌ not all DBMS are RDBMS.

33. What is a Table in SQL?

A table is a collection of data organized into rows and columns. Each table represents a specific entity, such as customers, products, employees or orders.

Think of a table like an Excel sheet, each row is a record and each column is a type of information.

34. What is a Field in SQL?

A field is a column in a table. It defines a single type of data that will be stored for every row in that table. Fields = Columns -> define what kind of data will be stored in each record.

For example in the Customers table, columns would be CustomerId ,Name, Email etc

35. How to Create a Table in SQL?

To create a table in SQL, you use the CREATE TABLE statement. It defines the table name, the columns (fields) and their respective data types.

Example
CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    ...
);

36. What are constraints in SQL and why use them?

Constraints enforce rules on the data in a table to ensure accuracy and integrity. Common constraints include

  • PRIMARY KEY: Uniquely identifies each row
  • FOREIGN KEY: Maintains referential integrity
  • NOT NULL: Prevents null values
  • UNIQUE: Prevents duplicate values
  • CHECK: Validates conditions
  • DEFAULT: Sets a default value if none is provided
Example
CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(100) UNIQUE NOT NULL
);

37. What are Indexes in SQL?

An index in SQL is a data structure used by a database to speed up the retrieval of records from a table, similar to how a book index helps you find topics faster without reading every page.

Instead of scanning the entire table row by row (a full table scan), the database uses the index to jump directly to the location of the desired data, making SELECT, JOIN, WHERE and ORDER BY queries much faster.

38. Why to use Indexes?

Indexes make data access faster and more efficient. Without an index, SQL has to scan the entire table row by row (called a full table scan) to find matching data. With an index, it can jump directly to the required rows, making queries much faster.

39. What are key Benefits of Using Indexes

  • Faster Data Retrieval : Speeds up SELECT queries, especially on large tables.
  • Improved Performance : Enhances read operations in applications, reducing response time.
  • Efficient Sorting and Filtering : Helps in ORDER BY, GROUP BY and WHERE clause queries.
  • Better Use of Joins : Speeds up joins by indexing foreign and primary keys.
  • Enforcing Uniqueness : Unique indexes prevent duplicate entries in a column (like email).

40. What is Trade-off using Indexs?

While indexes improve read/query speed, they come with some trade-offs

  • Slower Write Operations : INSERT, UPDATE and DELETE take longer because indexes need to be updated too.
  • Increased Storage : Indexes consume additional disk space.
  • Maintenance Overhead : More indexes = more effort to manage and keep them optimized.
  • Diminishing Returns : Too many indexes can confuse the query planner and hurt performance.

Use indexes only where needed - on columns often used in WHERE, JOIN or ORDER BY. Blindly indexing every column can hurt performance and increase storage usage.

41. How Do Indexes Work?

When you create an index on a column (or multiple columns), the database builds a separate lookup structure (usually a B-tree) that keeps the data in sorted order.

So, instead of going through the entire table row by row, the database uses this structure to jump directly to the relevant data, just like finding a word using a dictionary.

42. How to Create Indexes in SQL?

While Creating a Table
CREATE TABLE Customers (
    CustomerId INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    Email VARCHAR(100),
    INDEX idx_lastname (LastName)
);
After Table Creation
CREATE INDEX idx_email
ON Customers (Email);

43. What all different types of indexes in SQL

Index Type Key Features Best Use Case
Primary Index Unique, no nulls, 1 per table Main row identifier
Unique Index Ensures no two rows have the same value in the indexed column, allows nulls Email, phone, usernames
Composite Index Multi-column indexing Combined filters like (first_name, last_name)
Clustered Index Sorts and stores data rows physically in order (only one per table) Range or sorted queries
Non-Clustered Index Stores a pointer to the actual row, without affecting physical order Fast lookup without affecting row order
Full-Text Index Optimized for large text search Blog posts, product descriptions
Spatial Index Geolocation-based queries Maps, location-based services
Bitmap Index Bitmaps for low-cardinality columns Analytical/data warehouse queries
JSON/XML Index Indexes inside JSON/XML or computed values APIs, modern web apps

44. What is a schema?

A schema is the structure or blueprint of a database. It defines how tables, views, indexes , relationships and more are organized. It also provides a way to control access to different parts of the database.

Example

In a database, you might have a sales schema and a hr schema. Each with its own tables like sales.customers and hr.employees.

45. What is a view in SQL?

A view is a virtual table based on the result of a query. It simplifies complex joins and restricts data access.

Example
CREATE VIEW active_users AS
SELECT name, email FROM users WHERE is_active = 1;

46. What is denormalization?

Denormalization is the reverse of normalization, adding redundant data to reduce the complexity of joins and speed up reads. It's often used in read-heavy systems like reporting or analytics databases.

47. What is a SQL operator?

A SQL operator is a symbol or keyword used in SQL queries to perform actions like comparisons, calculations or filtering. SQL Operator are commonly used with the WHERE clause to define conditions.

48. What is an Alias?

An alias is a temporary name given to a column or table in a query to make results cleaner or improve readability.

Syntax Example
SELECT first_name AS name
FROM employees;
SELECT e.name, d.name
FROM employees AS e
JOIN departments AS d ON e.dept_id = d.id;

49. What is a Clause in SQL?

A clause is a keyword or condition used to define how SQL queries should behave , especially for filtering or structuring results.

Common clauses include

  • WHERE – filter rows
  • ORDER BY – sort results
  • GROUP BY – group data
  • HAVING – filter groups
  • LIMIT – limit rows

50. How to delete a table from a database?

To delete a table and all its data permanently, use the DROP TABLE statement.

Example
DROP TABLE table_name;