SQL Interview Questions and Answers for freshers

100 SQL Interview Questions and Answers for Freshers
  1. What is SQL?

    • Answer: SQL (Structured Query Language) is a domain-specific language used for managing and manipulating databases. It's used to interact with relational database management systems (RDBMS) like MySQL, PostgreSQL, Oracle, and SQL Server.
  2. What are the different types of SQL statements?

    • Answer: SQL statements can be broadly classified into DDL (Data Definition Language) for creating and modifying database structures (CREATE, ALTER, DROP), DML (Data Manipulation Language) for manipulating data (SELECT, INSERT, UPDATE, DELETE), DCL (Data Control Language) for controlling access to data (GRANT, REVOKE), and TCL (Transaction Control Language) for managing transactions (COMMIT, ROLLBACK).
  3. Explain the difference between CHAR and VARCHAR.

    • Answer: `CHAR` stores fixed-length strings. If you specify `CHAR(10)`, it will always use 10 bytes, even if you store a shorter string. `VARCHAR` stores variable-length strings, using only the necessary bytes. `VARCHAR` is generally more efficient for storing strings of varying lengths.
  4. What is a primary key?

    • Answer: A primary key is a unique identifier for each record in a table. It must contain unique values, and cannot contain NULL values. It ensures data integrity and helps in efficient data retrieval.
  5. What is a foreign key?

    • Answer: A foreign key is a column or set of columns in one table that refers to the primary key of another table. It establishes a link between the two tables, creating a relational database structure and enforcing referential integrity.
  6. What is a JOIN? Explain different types of JOINs.

    • Answer: A JOIN clause combines rows from two or more tables based on a related column between them. Types include: INNER JOIN (returns rows only when there is a match in both tables), LEFT (OUTER) JOIN (returns all rows from the left table, and the matched rows from the right table), RIGHT (OUTER) JOIN (returns all rows from the right table, and the matched rows from the left table), and FULL (OUTER) JOIN (returns all rows when there is a match in either left or right table).
  7. What is the difference between UNION and UNION ALL?

    • Answer: Both `UNION` and `UNION ALL` combine the result sets of two or more `SELECT` statements. `UNION` removes duplicate rows from the combined result set, while `UNION ALL` includes all rows, even duplicates.
  8. What is an index in SQL?

    • Answer: An index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and storage space to maintain the index data structure. Indexes are similar to the index in the back of a book.
  9. What is normalization? Why is it important?

    • Answer: Normalization is the process of organizing data to reduce redundancy and improve data integrity. It involves breaking down larger tables into smaller ones and defining relationships between them. This reduces data redundancy, improves data consistency, and simplifies data modification.
  10. What is a subquery? Give an example.

    • Answer: A subquery is a query nested inside another query. It's used to obtain data that is then used in the outer query. Example: `SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);` This finds employees with salaries above the average.
  11. What are aggregate functions in SQL? Give examples.

    • Answer: Aggregate functions perform calculations on a set of values and return a single value. Examples include: `AVG()` (average), `SUM()` (sum), `COUNT()` (number of rows), `MAX()` (maximum value), `MIN()` (minimum value).
  12. Explain the use of GROUP BY and HAVING clauses.

    • Answer: `GROUP BY` groups rows with the same values in specified columns into summary rows, like "sum of sales by region". `HAVING` filters the grouped rows based on a condition, similar to `WHERE` but applied after grouping.
  13. What is a transaction in SQL?

    • Answer: A transaction is a sequence of operations performed as a single logical unit of work. It ensures data integrity by either committing all changes or rolling back all changes if an error occurs.
  14. What are the ACID properties of transactions?

    • Answer: ACID stands for Atomicity (all or nothing), Consistency (maintains database integrity), Isolation (transactions are independent), and Durability (changes are permanent).
  15. How do you handle NULL values in SQL?

    • Answer: NULL represents the absence of a value. Use `IS NULL` and `IS NOT NULL` in `WHERE` clauses to check for NULLs. Functions like `COALESCE` or `ISNULL` can replace NULLs with a specified value.
  16. What is a view in SQL?

    • Answer: A view is a stored query that acts like a virtual table. It simplifies complex queries and provides a customized perspective of the data without storing the data itself.
  17. What is a stored procedure?

    • Answer: A stored procedure is a pre-compiled SQL code block that can be stored and reused. It improves performance and enhances database security by encapsulating SQL logic.
  18. What is the difference between DELETE and TRUNCATE commands?

    • Answer: `DELETE` removes rows one by one and allows `WHERE` clause filtering; it logs changes. `TRUNCATE` removes all rows in a table faster, without logging individual row deletions. `TRUNCATE` is faster but cannot be rolled back.
  19. Write a SQL query to find the second highest salary from an employees table.

    • Answer: There are several ways; one common approach uses a subquery: `SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);`
  20. Write a SQL query to find the names of employees who work in the 'Sales' department.

    • Answer: `SELECT employee_name FROM employees WHERE department = 'Sales';`
  21. Write a SQL query to display the current date.

    • Answer: The specific function varies by database system. Examples include `SELECT CURRENT_DATE;` (MySQL, PostgreSQL) or `SELECT GETDATE();` (SQL Server).
  22. Explain different data types in SQL.

    • Answer: Common data types include `INT` (integer), `FLOAT` or `DOUBLE` (floating-point numbers), `VARCHAR` (variable-length string), `CHAR` (fixed-length string), `DATE`, `TIME`, `DATETIME`, `BOOLEAN` (true/false).
  23. What is a self-join? Give an example.

    • Answer: A self-join joins a table to itself, treating it as two separate tables to find relationships within the same table. Example: Finding employees who report to other employees in the same table.
  24. What are constraints in SQL?

    • Answer: Constraints enforce rules on data within a table, ensuring data integrity. Types include PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK.
  25. What is the difference between a clustered and a non-clustered index?

    • Answer: A clustered index determines the physical order of data rows in a table. A non-clustered index is a separate structure that points to the data rows.
  26. How to create a table in SQL?

    • Answer: Use the `CREATE TABLE` statement, specifying the table name and column definitions with data types and constraints.
  27. How to alter a table in SQL?

    • Answer: Use the `ALTER TABLE` statement to add, modify, or delete columns, or add constraints.
  28. How to drop a table in SQL?

    • Answer: Use the `DROP TABLE` statement to delete a table and its data.
  29. What is a CASE statement in SQL?

    • Answer: A `CASE` statement allows conditional logic within SQL queries, similar to an `if-else` statement in programming languages.
  30. Explain the use of LIKE operator.

    • Answer: The `LIKE` operator is used in `WHERE` clauses for pattern matching in string data, using wildcards like `%` (any sequence of characters) and `_` (any single character).
  31. What is a transaction log?

    • Answer: A transaction log records all changes made to a database, ensuring data recovery in case of failures. It's crucial for maintaining data integrity and consistency.
  32. What is deadlock in SQL?

    • Answer: A deadlock occurs when two or more transactions are blocked indefinitely, waiting for each other to release resources. This results in a system standstill.
  33. How to prevent deadlocks?

    • Answer: Strategies include setting a consistent order for accessing resources, using shorter transactions, and employing timeout mechanisms.
  34. What are the different types of database normalization forms?

    • Answer: Common normalization forms include 1NF (first normal form), 2NF (second normal form), 3NF (third normal form), BCNF (Boyce-Codd normal form), and others.
  35. What is the difference between INNER JOIN and CROSS JOIN?

    • Answer: `INNER JOIN` combines rows only when there's a match in the join condition. `CROSS JOIN` returns the Cartesian product of two tables (all possible combinations of rows from both tables).
  36. What is a trigger in SQL?

    • Answer: A trigger is a stored procedure that automatically executes in response to certain events on a particular table or view, such as INSERT, UPDATE, or DELETE operations.
  37. Explain the concept of data integrity.

    • Answer: Data integrity refers to the accuracy, consistency, and reliability of data. It ensures that data is valid, meaningful, and free from errors.
  38. What are some common SQL functions?

    • Answer: String functions (e.g., `UPPER`, `LOWER`, `SUBSTRING`), Date/time functions (e.g., `DATE_ADD`, `DATE_SUB`), Mathematical functions (e.g., `ABS`, `SQRT`, `ROUND`), and aggregate functions (e.g., `SUM`, `AVG`, `COUNT`).
  39. What is the purpose of the WHERE clause?

    • Answer: The `WHERE` clause filters rows in a `SELECT` statement based on specified conditions, returning only the rows that meet the criteria.
  40. How do you update data in a table?

    • Answer: Use the `UPDATE` statement, specifying the table, the columns to update, the new values, and optionally a `WHERE` clause to filter the rows to update.
  41. How do you delete data from a table?

    • Answer: Use the `DELETE` statement, specifying the table and optionally a `WHERE` clause to filter the rows to delete.
  42. What is a cursor in SQL?

    • Answer: A cursor is a database object used to fetch one row at a time from a result set. It allows row-by-row processing of data.
  43. What is the difference between a view and a materialized view?

    • Answer: A view is a virtual table, while a materialized view is a physical table that stores the result set of a query. Materialized views improve performance by pre-calculating results.
  44. What is data warehousing?

    • Answer: Data warehousing is the process of collecting and managing data from various sources to provide a centralized, integrated view for analysis and reporting.
  45. What is OLTP and OLAP?

    • Answer: OLTP (Online Transaction Processing) focuses on efficient transaction processing. OLAP (Online Analytical Processing) focuses on data analysis and reporting.
  46. What is a database schema?

    • Answer: A database schema is a formal description of the structure of a database, including tables, columns, data types, relationships, and constraints.
  47. What is an auto-increment column?

    • Answer: An auto-increment column automatically generates unique integer values for each new row inserted into a table, often used as a primary key.
  48. What are some common SQL keywords?

    • Answer: `SELECT`, `FROM`, `WHERE`, `INSERT`, `UPDATE`, `DELETE`, `CREATE`, `ALTER`, `DROP`, `JOIN`, `GROUP BY`, `HAVING`, `ORDER BY`, `LIMIT`, `OFFSET`.
  49. What is a CTE (Common Table Expression)?

    • Answer: A CTE is a temporary named result set that can be referenced within a single query. It helps to improve readability and make complex queries easier to understand.
  50. How do you handle exceptions in SQL?

    • Answer: Techniques include using `TRY...CATCH` blocks (in some database systems) or implementing error handling within stored procedures.
  51. What is the role of a database administrator (DBA)?

    • Answer: A DBA is responsible for designing, implementing, managing, and maintaining databases, ensuring data integrity, security, and availability.
  52. Explain the concept of referential integrity.

    • Answer: Referential integrity ensures that relationships between tables are consistent, preventing orphaned records (records in one table referencing non-existent records in another).
  53. What is a database management system (DBMS)?

    • Answer: A DBMS is a software system that allows users to define, create, maintain, and control access to a database.
  54. What is the difference between SQL and NoSQL databases?

    • Answer: SQL databases use a relational model with structured data, enforcing schemas and ACID properties. NoSQL databases are non-relational, offering flexibility with various data models (document, key-value, graph) and often prioritizing scalability and availability over strict consistency.
  55. What is indexing and why is it important?

    • Answer: Indexing is creating a data structure that speeds up data retrieval. It's important for improving query performance, especially on large tables.
  56. Describe your experience with SQL (if any).

    • Answer: (This requires a personalized answer based on the candidate's experience. Mention specific projects, tasks, and technologies used.)
  57. What are some common SQL errors you have encountered and how did you resolve them?

    • Answer: (This requires a personalized answer. Mention specific errors, their causes, and how you debugged them.)
  58. How do you ensure data security in a SQL database?

    • Answer: Techniques include access control (user permissions, roles), encryption, input validation, regular backups, and security auditing.
  59. What are some best practices for writing efficient SQL queries?

    • Answer: Use appropriate indexes, avoid using `SELECT *`, use joins efficiently, optimize `WHERE` clauses, and profile queries to identify bottlenecks.
  60. What is your understanding of database performance tuning?

    • Answer: It involves identifying and resolving performance bottlenecks in database operations, using techniques like indexing, query optimization, and hardware upgrades.
  61. How would you approach troubleshooting a slow SQL query?

    • Answer: Use query profiling tools, analyze execution plans, check indexes, optimize the query, and investigate potential hardware limitations.
  62. What are your strengths and weaknesses related to SQL?

    • Answer: (This requires a personalized answer. Be honest and provide examples.)
  63. Are you comfortable working with large datasets?

    • Answer: (Answer honestly, mentioning experience with large datasets or willingness to learn techniques for handling them.)
  64. How do you stay updated with the latest trends in SQL and databases?

    • Answer: Mention resources like online courses, blogs, documentation, conferences, and professional communities.
  65. Why are you interested in this role?

    • Answer: (Personalize this answer based on the specific role and company.)
  66. What are your salary expectations?

    • Answer: (Research industry standards and provide a reasonable range.)

Thank you for reading our blog post on 'SQL Interview Questions and Answers for freshers'.We hope you found it informative and useful.Stay tuned for more insightful content!