Most Asked Sql Interview Questions

  1. What is a primary key?

    A primary key is a unique identifier for a record in a table. It ensures that each row in a table is uniquely identifiable. It can be a single column or a combination of columns.

  2. What is a foreign key?

    A foreign key is a column or a set of columns in a table that refers to the primary key of another table. It establishes a relationship between two tables, enforcing referential integrity.

  3. What is the difference betweenDELETEandTRUNCATE?

    • DELETE is a DML (Data Manipulation Language) command that removes rows from a table based on a condition. It can be rolled back and triggers can be fired.

    • TRUNCATE is a DDL (Data Definition Language) command that removes all rows from a table. It cannot be rolled back, and it resets identity columns. It's faster than DELETE as it doesn't generate individual delete statements.

  4. What is a self-join?

    A self-join is a join in which a table is joined with itself. It's typically used to compare rows within the same table. For example, to find employees who have the same manager:

     SELECT e1.name, e2.name
     FROM employees e1
     JOIN employees e2 ON e1.manager_id = e2.manager_id
     WHERE e1.employee_id != e2.employee_id;
    
  5. What is a subquery?

    A subquery is a query nested within another query. It can be used in various SQL clauses like SELECT, INSERT, UPDATE, or DELETE to return data that is used by the outer query. For example:

     SELECT name 
     FROM employees 
     WHERE department_id IN (SELECT department_id FROM departments WHERE location = 'New York');
    
  6. What is the difference betweenHAVINGandWHERE clauses?

    • WHERE is used to filter rows before any groupings are made.

    • HAVING is used to filter rows after the grouping has occurred. It's typically used with aggregate functions like SUM, COUNT, etc.

  7. Explain the ACID properties of database transactions.

    • Atomicity: A transaction is atomic; it's either completely executed or not executed at all.

    • Consistency: Transactions must leave the database in a consistent state. All constraints must be satisfied.

    • Isolation: Transactions should be isolated from each other. Changes made by one transaction should be invisible to other transactions until they are committed.

    • Durability: Once a transaction is committed, its changes are permanent and survive system failures.

  8. What is the difference betweenUNIONandUNION ALL?

    • UNION removes duplicate rows from the result set.

    • UNION ALL retains all rows from the result set, including duplicates.

  9. What is a view in SQL?

    A view is a virtual table based on the result set of a SELECT query. It behaves like a table but doesn't store data itself. Views are useful for simplifying complex queries, enforcing security, and providing a consistent interface to users.

  10. What is a stored procedure?

    A stored procedure is a set of SQL statements that are stored in the database and can be executed repeatedly. It allows for modular programming within the database, improves performance, and enhances security by reducing the risk of SQL injection.

    Here's an example of creating a simple stored procedure that retrieves employee information based on a given department ID:

    CREATE PROCEDURE get_employee_info(IN department_id INT)
    BEGIN
        SELECT * FROM employees WHERE department_id = department_id;
    END;
    

    In this example:

    • get_employee_info is the name of the stored procedure.

    • IN department_id INT declares an input parameter named department_id of type INT.

    • BEGIN ... END contains a single SQL statement that selects all columns from the employees table where the department_id matches the input parameter value.

Once the stored procedure is created, you can execute it using the CALL statement:

    CALL get_employee_info(1);

This will execute the stored procedure get_employee_info with the parameter department_id set to 1, retrieving information about employees in the department with ID 1.

  1. What is function ?

    Pre-built actions that perform calculations, manipulate data, and return results

    To create a function in SQL, you typically use the CREATE FUNCTION statement.

    Here's an example of creating a simple function that calculates the total salary of an employee based on their salary and bonus:

    CREATE FUNCTION calculate_total_salary (salary DECIMAL(10, 2), bonus DECIMAL(10, 2))
    RETURNS DECIMAL(10, 2)
    BEGIN
        DECLARE total_salary DECIMAL(10, 2);
        SET total_salary = salary + bonus;
        RETURN total_salary;
    END;
    

    In this example:

    • calculate_total_salary is the name of the function.

    • (salary DECIMAL(10, 2), bonus DECIMAL(10, 2)) declares two input parameters named salary and bonus, both of type DECIMAL(10, 2).

    • RETURNS DECIMAL(10, 2) specifies that the function will return a decimal value with a precision of 10 and a scale of 2.

    • BEGIN ... END contains the procedural logic of the function, which calculates the total salary by adding the salary and bonus parameters together and assigns the result to the total_salary variable. Finally, it returns the total_salary value.

Once the function is created, you can call it in SQL statements like any other function:

    SELECT calculate_total_salary(5000.00, 1000.00) AS total_salary;

This will return the total salary calculated by the calculate_total_salary function for the given salary and bonus values.

  • Functions are typically used to compute and return a single value based on input parameters. They are often used in SQL queries, expressions, or as part of other functions.

  • Stored procedures are used to group and execute a series of SQL statements and procedural logic. They can perform various operations, such as data manipulation, transaction control, and business logic execution.

  1. What is the difference betweenCHARandVARCHAR data types?

    • CHAR is a fixed-length character data type. It stores a fixed amount of characters, padding with spaces if necessary.

    • VARCHAR is a variable-length character data type. It stores a variable amount of characters, up to a specified maximum length.

  2. What is a transaction in SQL?

    A transaction is a unit of work performed on a database that must be executed completely or not at all. It ensures data integrity and consistency by either committing changes (making them permanent) or rolling back changes (undoing them) if an error occurs.

  3. What is theGROUP BYclause used for?

    The GROUP BY clause is used to group rows that have the same values into summary rows. It's typically used with aggregate functions like SUM, COUNT, AVG, etc., to perform calculations on grouped data.

  4. What is a correlated subquery?

    A correlated subquery is a subquery that references columns from the outer query. It executes once for each row processed by the outer query. Correlated subqueries can be less efficient than non-correlated subqueries but are necessary in certain situations.

  5. What is normalization and why is it important?

    Normalization is the process of organizing data in a database efficiently. It reduces data redundancy and dependency by breaking down large tables into smaller, related tables. Normalization helps improve data integrity, reduces storage space, and facilitates easier database maintenance.

  6. Explain the difference betweenINNER JOIN,LEFT JOIN, and RIGHT JOIN.

    • INNER JOIN: Returns rows when there is a match in both tables.

    • LEFT JOIN: Returns all rows from the left table and matching rows from the right table. If there is no match, NULL values are returned for the right table columns.

    • RIGHT JOIN: Returns all rows from the right table and matching rows from the left table. If there is no match, NULL values are returned for the left table columns.

  7. What is a trigger in SQL?

    A trigger is a set of SQL statements that automatically execute in response to certain events on a table, such as INSERT, UPDATE, or DELETE operations. Triggers are useful for enforcing data integrity rules, auditing changes, and implementing complex business logic.

    To create a trigger in SQL, you use the CREATE TRIGGER statement. Here's the basic syntax along with an example:

    CREATE TRIGGER trigger_name
    {BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE}
    ON table_name
    FOR EACH ROW
    BEGIN
        -- SQL statements to be executed when the trigger condition is met
    END;
    

    Let's break down the syntax:

    • trigger_name: This is the name of the trigger.

    • {BEFORE | AFTER | INSTEAD OF}: Specifies when the trigger should fire.

      • BEFORE: The trigger fires before the specified operation.

      • AFTER: The trigger fires after the specified operation.

      • INSTEAD OF: Used for triggers on views, where the trigger replaces the default action of the operation.

    • {INSERT | UPDATE | DELETE}: Specifies the type of operation that activates the trigger.

    • ON table_name: Specifies the table on which the trigger should be created.

    • FOR EACH ROW: Indicates that the trigger should be executed for each row affected by the triggering statement.

    • BEGIN ... END: Contains the SQL statements to be executed when the trigger is fired.

Here's an example of creating a trigger that automatically updates a last_updated column in a products table whenever a row is updated:

    CREATE TRIGGER update_last_updated
    AFTER UPDATE
    ON products
    FOR EACH ROW
    BEGIN
        UPDATE products
        SET last_updated = CURRENT_TIMESTAMP
        WHERE product_id = NEW.product_id;
    END;

In this example:

  • update_last_updated is the name of the trigger.

  • AFTER UPDATE specifies that the trigger should fire after an UPDATE operation.

  • products is the name of the table on which the trigger is created.

  • FOR EACH ROW indicates that the trigger should be executed for each row affected by the UPDATE statement.

  • BEGIN ... END contains the SQL statements to be executed when the trigger is fired. In this case, it updates the last_updated column to the current timestamp for the row that was updated (NEW.product_id refers to the product ID of the updated row).

  1. What is CTE(common table expression) ?

    A Common Table Expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. It helps improve the readability and maintainability of complex SQL queries by breaking them down into smaller, more manageable parts.

    Here's an example of using a CTE to retrieve employee names and their managers from an employees table:

    WITH CTE1 AS (
        SELECT column1, column2
        FROM table1
    ),
    CTE2 AS (
        SELECT column3, column4
        FROM table2
    )
    SELECT *
    FROM CTE1
    JOIN CTE2 ON CTE1.column1 = CTE2.column3;
    
  2. What are indexes and how to create an index in SQL:

    Indexes are data structures that improve the speed of data retrieval operations on a database table. They allow for faster lookup of data based on the indexed columns.

    To create an index in SQL, you use the CREATE INDEX statement. For example, to create an index on the email column of a table named users:

    CREATE INDEX idx_email ON users (email);
    
  3. How to create and drop an index:

    To create an index, you use the CREATE INDEX statement as shown above.

    To drop an index, you use the DROP INDEX statement. For example, to drop the index we created on the email column:

    DROP INDEX idx_email ON users;
    
  4. Disadvantages of indexes:

    While indexes can significantly speed up data retrieval, they also have some drawbacks:

    • Increased disk space usage.

    • Slower data modification operations (such as INSERT, UPDATE, DELETE) because indexes must be updated.

    • Indexes need to be maintained, which can lead to overhead in write-heavy systems.

  5. If you drop a table, does it drop views and stored procedures:

    No, dropping a table does not automatically drop views or stored procedures that reference that table. You need to drop them separately if you want to remove them.

  6. How to tune your SQL

    Here are some tips for tuning SQL queries based on the provided points:

    • Select only the necessary fields.

    • Avoid using SELECT DISTINCT unless required.

    • Use proper joins like INNER JOIN.

    • Use WHERE instead of HAVING for filters.

    • Minimize the number of joins.

    • Avoid cursors.

    • Use BETWEEN instead of IN where applicable.

    • Consider the performance order of operators.

    • Force index usage if necessary.

    • Limit the result set.

    • Use wildcards at the end of phrases.

    • Restrict the number of rows and columns in the result set, using TOP if needed.

  7. How to find the 3rd highest salary:

    You can achieve this by using the LIMIT clause with an ORDER BY clause in descending order. Assuming you have an employees table with a salary column:

    SELECT salary 
    FROM employees
    ORDER BY salary DESC
    LIMIT 2, 1;
    
  8. Write an SQL query to fetch the 5th higest salary

    SELECT s1.GPA 
    FROM student s1 
    WHERE 4 = (
        SELECT COUNT(DISTINCT s2.GPA) 
        FROM student s2 
        WHERE s2.GPA > s1.GPA
    );
    
  9. Write an SQL query to fetch three max GPA from a table using co-related subquery

    SELECT GPA
    FROM student s1
    WHERE 3 > (
        SELECT COUNT(DISTINCT s2.GPA)
        FROM student s2
        WHERE s2.GPA > s1.GPA
    )
    ORDER BY GPA DESC;
    
  10. Write an SQL query to fetch three min GPA from a table using co-related subquery

    SELECT GPA
    FROM student s1
    WHERE 3 > (
        SELECT COUNT(DISTINCT s2.GPA)
        FROM student s2
        WHERE s2.GPA < s1.GPA
    )
    ORDER BY GPA ASC;
    
  11. Sales report

    SELECT stock_name,
           SUM(CASE WHEN operation = 'Sell' THEN price ELSE 0 END) -
           SUM(CASE WHEN operation = 'Buy' THEN price ELSE 0 END) AS capital_gain_loss
    FROM your_table_name
    GROUP BY stock_name;