Skip to content
  • Home
  • Software Engineering Jobs
  • Internship Opportunities
  • Remote Jobs
  • Layoffs Tracker
  • Interview Preparation
  • Resume Score Checker
  • Tech News
logo1
  • Software Engineering Jobs
  • Latest Jobs
  • Internships
  • Remote Job
  • Interview Preparation
  • Paid courses
  • Technology News

Database Interview

Database Interview Questions

Database Interview Questions & Answers

Question Answer
What is a database? A database is an organized collection of structured information or data, typically stored electronically in a computer system.
What is the difference between SQL and NoSQL databases? SQL databases are relational and use structured query language (SQL) for defining and manipulating data. NoSQL databases are non-relational, offering flexibility in data models like document, key-value, or graph.
What are the different types of database models? The different types include relational models, hierarchical models, network models, and object-oriented models.
What is normalization in databases? Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity. It typically involves dividing a database into two or more tables and defining relationships between them.
Explain ACID properties in a database. ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties ensure that database transactions are processed reliably.
What is a primary key? A primary key is a unique identifier for a record in a database table. It ensures that each record can be uniquely identified.
What is a foreign key? A foreign key is a field in one table that uniquely identifies a row of another table. It creates a relationship between the two tables.
What is the difference between INNER JOIN and LEFT JOIN? INNER JOIN returns rows that have matching values in both tables. LEFT JOIN returns all rows from the left table and matched rows from the right table, or NULL if no match is found.
What are indexes in databases? Indexes are used to speed up query retrieval times by providing fast access to rows in a database table.
What is a stored procedure? A stored procedure is a set of SQL queries that can be executed as a unit. It is stored in the database and can be reused for repetitive tasks.
What is a trigger in a database? A trigger is a set of instructions that are automatically executed in response to certain events in the database, such as INSERT, UPDATE, or DELETE operations.
What is a view in a database? A view is a virtual table that provides a way to access data from one or more tables. It is essentially a stored query that can simplify complex queries.
What is a deadlock in databases? A deadlock occurs when two or more transactions are blocked indefinitely because each transaction is waiting for a resource held by another.
What is a database schema? A database schema is the structure that defines the organization of data in a database. It defines tables, columns, relationships, and constraints.
What is the difference between DELETE and TRUNCATE commands? DELETE removes rows one by one and logs each deletion. TRUNCATE removes all rows from a table and does not log individual row deletions.
What is a database transaction? A database transaction is a sequence of operations performed as a single unit. Transactions must follow the ACID properties to maintain database integrity.
What are the different types of database relationships? The types of relationships are one-to-one, one-to-many, and many-to-many.
What is a composite key? A composite key is a primary key that consists of two or more columns, where each column is a part of the key.
What is data redundancy? Data redundancy occurs when the same piece of data is stored in multiple places within a database, leading to unnecessary duplication.
What is referential integrity? Referential integrity ensures that foreign keys in a database table only refer to existing rows in another table, maintaining the consistency of relationships between tables.
What is the difference between UNION and UNION ALL? UNION combines the results of two queries and removes duplicate rows, while UNION ALL includes all rows, even duplicates.
What is denormalization? Denormalization is the process of intentionally introducing redundancy into a database by merging tables, usually to improve read performance.
What is a surrogate key? A surrogate key is a unique identifier for an entity, often a system-generated value (e.g., an auto-incremented integer), that doesn't have any business meaning.
What are database constraints? Constraints are rules enforced on data in a database table to ensure the accuracy, integrity, and consistency of the data (e.g., PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL).
What is a correlation in SQL? A correlation in SQL refers to the relationship between a subquery and the outer query, allowing the subquery to reference columns of the outer query.
What is a batch processing system in a database? A batch processing system processes large volumes of data in batches or groups, typically without user interaction, and often during off-peak hours.
What is SQL injection? SQL injection is a code injection technique where malicious SQL queries are inserted into input fields, allowing attackers to manipulate the database.
What is a schema in the context of databases? A schema is the structure that defines the organization of data in a database, including tables, views, and relationships.
What is the purpose of the GROUP BY clause in SQL? The GROUP BY clause is used to group rows that have the same values into summary rows, such as calculating the COUNT, SUM, AVG, etc., for each group.
What is a composite index? A composite index is an index on multiple columns of a table, which improves query performance when those columns are used together in queries.
What is an ER diagram? An Entity-Relationship (ER) diagram is a visual representation of the entities in a database and their relationships. It helps to design and model the database structure.
What is sharding in a database? Sharding is a database architecture pattern where data is distributed across multiple servers to improve scalability and performance.
What is a normalization form? A normalization form is a set of rules used to organize a database into a structure that reduces redundancy and dependency. Examples include 1NF, 2NF, and 3NF.
What is a database trigger? A database trigger is a set of SQL statements that are automatically executed or triggered when certain events, like an INSERT, UPDATE, or DELETE, occur in a table.
What is a clustered index? A clustered index determines the physical order of data in a table. There can be only one clustered index per table.
What is a non-clustered index? A non-clustered index creates a separate structure from the data rows and stores pointers to the actual data. Multiple non-clustered indexes can exist in a table.
What is the purpose of the HAVING clause in SQL? The HAVING clause is used to filter records after the GROUP BY operation, allowing conditions to be applied to groups.
What is a full-text search in a database? A full-text search enables searching for text within large volumes of data, including words, phrases, and even partial matches, for more efficient querying.
What is an OLAP cube? OLAP (Online Analytical Processing) cubes allow users to analyze data in multiple dimensions, enabling fast query performance and aggregation for complex queries.
What is a data warehouse? A data warehouse is a centralized repository for storing large volumes of structured data from different sources, optimized for reporting and analysis.
What is the difference between OLTP and OLAP? OLTP (Online Transaction Processing) focuses on transaction-oriented tasks with a high volume of small queries, while OLAP (Online Analytical Processing) focuses on read-heavy tasks for complex data analysis.
What is a foreign key? A foreign key is a column or group of columns in one table that uniquely identifies a row of another table, ensuring referential integrity between the two tables.
What are the different types of relationships in database design? The different types of relationships are: one-to-one, one-to-many, and many-to-many.
What is the difference between a view and a table? A view is a virtual table that is based on the result of a SELECT query, while a table is a physical structure that stores data.
What is an index in a database? An index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional space and maintenance overhead.
What is the purpose of a subquery in SQL? A subquery is a query embedded within another query, used to perform operations or filter data that cannot be handled directly by the main query.
What is a materialized view? A materialized view is a database object that stores the results of a query as a physical table and can be refreshed periodically.
What is the difference between DELETE and TRUNCATE in SQL? DELETE removes records from a table and logs the changes for each row, while TRUNCATE removes all rows and does not log individual row deletions.
What is referential integrity in a database? Referential integrity ensures that foreign keys in a database table always point to valid rows in another table, maintaining consistency across related data.
What is the ACID property in database transactions? ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties ensure reliable database transactions.
What is the difference between clustered and non-clustered indexes? A clustered index determines the physical order of data in the table, while a non-clustered index is a separate structure that holds pointers to the data.
What is a deadlock in a database? A deadlock occurs when two or more transactions are blocked, waiting for each other to release resources, resulting in an infinite wait cycle.
What is database normalization? Database normalization is the process of organizing data in a way that reduces redundancy and improves data integrity by dividing a database into smaller tables.
What are the different types of database backups? The different types of backups are: full backup, incremental backup, and differential backup.
What is the difference between CHAR and VARCHAR in SQL? CHAR is a fixed-length data type, while VARCHAR is a variable-length data type. VARCHAR uses storage only for the actual length of the string.
What is a stored procedure? A stored procedure is a precompiled collection of SQL statements stored in the database that can be executed repeatedly with different parameters.
What is a trigger in SQL? A trigger is a database object that automatically executes a specified set of actions when certain events (INSERT, UPDATE, DELETE) occur on a table or view.
What is a primary key? A primary key is a column or set of columns in a table that uniquely identifies each row in that table. It cannot have NULL values.
What is database sharding? Sharding is a database architecture pattern in which data is partitioned across multiple servers (shards) to improve performance and scalability.
What is the difference between an inner join and a left join? An inner join returns only the matching rows from both tables, while a left join returns all rows from the left table and the matching rows from the right table.
What is a self-join in SQL? A self-join is a join operation where a table is joined with itself, typically to query hierarchical data or compare rows within the same table.
What is the purpose of the GROUP BY clause in SQL? The GROUP BY clause is used to group rows that have the same values into summary rows, typically used with aggregate functions like COUNT, SUM, AVG, etc.
What is the difference between a view and a materialized view? A view is a virtual table based on a query, while a materialized view is a physical copy of the query results stored as a table, which needs to be refreshed.
What is a composite key in a database? A composite key is a combination of two or more columns that uniquely identify a row in a table, providing a higher level of data integrity.
What is the difference between a UNION and a UNION ALL in SQL? UNION combines the results of two or more queries and removes duplicates, while UNION ALL includes all duplicates in the result set.
What is a cross join in SQL? A cross join returns the Cartesian product of two tables, meaning it combines all rows from the first table with all rows from the second table.
What is a unique constraint in SQL? A unique constraint ensures that all values in a column or a combination of columns are distinct across the rows in a table.
What is denormalization in a database? Denormalization is the process of intentionally introducing redundancy into a database by combining tables, often to improve query performance.
What is a composite key? A composite key is a primary key made up of two or more columns that together uniquely identify a row in a table.
What is a surrogate key? A surrogate key is a unique identifier for a record that is generated automatically, typically used in place of a natural key.
What is a clustered index? A clustered index determines the physical order of data in a table and can only have one per table. The table rows are stored in the same order as the index.
What is a non-clustered index? A non-clustered index is a separate structure that points to the actual data. You can have multiple non-clustered indexes per table.
What is SQL injection? SQL injection is a type of security vulnerability that allows attackers to execute arbitrary SQL code on a database by manipulating input parameters.
What is a join condition? A join condition defines how two tables should be connected by specifying which columns should be compared between them.
What are aggregate functions in SQL? Aggregate functions perform calculations on a set of values and return a single result, such as COUNT, SUM, AVG, MIN, and MAX.
What is a database schema? A schema is the structure that defines the organization of data in a database, including tables, columns, constraints, and relationships.
What is the difference between a schema and a database? A database is a collection of data, while a schema is a logical container that holds the database objects (tables, views, etc.) and their relationships.
What is an ER diagram? An Entity-Relationship (ER) diagram is a graphical representation of entities and their relationships in a database.
What is a rollback in a database? A rollback is the operation of undoing all changes made during the current transaction, returning the database to its state before the transaction started.
What is a savepoint in SQL? A savepoint is a marker within a transaction that allows you to roll back to that point without rolling back the entire transaction.
What are the advantages of using stored procedures? Stored procedures improve performance, security, and code reusability. They can also simplify complex queries and reduce network traffic.
What is the difference between CHAR and TEXT data types? CHAR is a fixed-length string, while TEXT is a variable-length string used to store larger amounts of text data.
What is the difference between SQL and NoSQL databases? SQL databases are relational, use structured data, and support ACID transactions, while NoSQL databases are non-relational, scale horizontally, and support flexible, schema-less data models.
What is an example of a NoSQL database? Examples of NoSQL databases include MongoDB, Cassandra, CouchDB, and Redis.
What is normalization in a database? Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity by dividing large tables into smaller, related tables.
What is the difference between the primary key and the foreign key? A primary key uniquely identifies each row in a table, whereas a foreign key is a column or a set of columns that links a table to another table by referencing its primary key.
What are ACID properties in a database? ACID stands for Atomicity, Consistency, Isolation, and Durability, which are the properties that guarantee that database transactions are processed reliably.
What is an index in a database? An index is a database object that improves the speed of data retrieval operations on a table at the cost of additional space and slower write operations.
What is the difference between DELETE and TRUNCATE? DELETE removes rows from a table based on a condition and can be rolled back, while TRUNCATE removes all rows from a table without logging individual row deletions and cannot be rolled back.
What is a trigger in SQL? A trigger is a set of SQL statements that automatically execute when a specific event (INSERT, UPDATE, DELETE) occurs on a particular table or view.
What is the difference between a stored procedure and a function in SQL? A stored procedure performs an action (e.g., insert, update, delete) and may or may not return a value, while a function is used to compute a value and must return a value.
What is referential integrity? Referential integrity is a concept that ensures that relationships between tables remain consistent, meaning foreign keys must match primary keys in the referenced table.
What is the difference between a snapshot isolation level and serializable isolation level? Snapshot isolation provides a consistent view of the data as it was at the start of a transaction, while serializable isolation provides the strictest level of isolation by ensuring transactions are executed sequentially.
What is a view in SQL? A view is a virtual table created by querying one or more base tables. It simplifies complex queries and enhances security by restricting access to specific data.
What is the difference between a database and a data warehouse? A database is designed to handle day-to-day transactions, while a data warehouse is optimized for reporting and data analysis, typically storing large amounts of historical data.
What is the use of the GROUP BY clause in SQL? The GROUP BY clause is used to group rows that have the same values in specified columns, often used with aggregate functions like COUNT, SUM, AVG, etc.
What is the difference between a LEFT JOIN and a RIGHT JOIN? A LEFT JOIN returns all rows from the left table and the matching rows from the right table, while a RIGHT JOIN returns all rows from the right table and the matching rows from the left table.
What is a subquery in SQL? A subquery is a query nested inside another query. It can be used in SELECT, INSERT, UPDATE, or DELETE statements to perform operations based on the results of another query.
What is a database transaction? A database transaction is a sequence of one or more SQL operations executed as a single unit, which ensures ACID properties are maintained.
What is a deadlock in SQL? A deadlock occurs when two or more transactions are blocked, each waiting for the other to release a resource, resulting in a system freeze.
What is a data dictionary in a database? A data dictionary is a collection of metadata that defines the structure of database objects such as tables, columns, data types, and constraints.
What is a database cluster? A database cluster is a collection of databases that share the same server or instance. It can also refer to a group of servers working together to manage a single database for high availability and load balancing.
What is the difference between a stored procedure and a trigger? A stored procedure is explicitly invoked by the user or application, while a trigger is automatically invoked by database events such as INSERT, UPDATE, or DELETE operations.
What is sharding in a database? Sharding is a method of distributing data across multiple machines or databases to improve performance, scalability, and availability.
Write a query to find the second highest salary from the Employee table.
SELECT MAX(salary) 
            FROM Employee 
            WHERE salary < (SELECT MAX(salary) FROM Employee);
Write a query to get the current date in SQL.
SELECT CURRENT_DATE;
Write a query to find the employee who has the highest salary in the Employee table.
SELECT * FROM Employee 
            WHERE salary = (SELECT MAX(salary) FROM Employee);
Write a query to find all employees who are older than 30 years.
SELECT * FROM Employee 
            WHERE age > 30;
Write a query to count the number of employees in each department.
SELECT department_id, COUNT(*) 
            FROM Employee 
            GROUP BY department_id;
Write a query to find the total salary paid to all employees.
SELECT SUM(salary) 
            FROM Employee;
Write a query to list all departments that have more than 10 employees.
SELECT department_id 
            FROM Employee 
            GROUP BY department_id 
            HAVING COUNT(*) > 10;
Write a query to find employees who have not received any bonus (assuming a bonus column).
SELECT * FROM Employee 
            WHERE bonus IS NULL;
Write a query to get the names of all employees who work in 'HR' department.
SELECT employee_name 
            FROM Employee 
            WHERE department = 'HR';
Write a query to retrieve all employees who joined in the last 6 months.
SELECT * FROM Employee 
            WHERE hire_date > CURDATE() - INTERVAL 6 MONTH;
Write a query to list all unique job titles in the Employee table.
SELECT DISTINCT job_title 
            FROM Employee;
Write a query to display all employees in descending order of salary.
SELECT * FROM Employee 
            ORDER BY salary DESC;
Write a query to find the average salary of employees in the 'Sales' department.
SELECT AVG(salary) 
            FROM Employee 
            WHERE department = 'Sales';
Write a query to retrieve employees who were hired between '2020-01-01' and '2021-01-01'.
SELECT * FROM Employee 
            WHERE hire_date BETWEEN '2020-01-01' AND '2021-01-01';
Write a query to find employees who have a salary greater than 50,000 but less than 100,000.
SELECT * FROM Employee 
            WHERE salary BETWEEN 50000 AND 100000;
Write a query to display the top 5 highest-paid employees.
SELECT * FROM Employee 
            ORDER BY salary DESC 
            LIMIT 5;
Write a query to join the Employee table with the Department table.
SELECT Employee.employee_name, Department.department_name 
            FROM Employee 
            JOIN Department 
            ON Employee.department_id = Department.department_id;
Write a query to delete all employees who have not received a salary for the past 3 months.
DELETE FROM Employee 
            WHERE last_payment_date < CURDATE() - INTERVAL 3 MONTH;
Write a query to find the department with the highest average salary.
SELECT department_id, AVG(salary) AS avg_salary 
            FROM Employee 
            GROUP BY department_id 
            ORDER BY avg_salary DESC 
            LIMIT 1;
Write a query to find employees who work in 'IT' and have a salary greater than 70,000.
SELECT * FROM Employee 
            WHERE department = 'IT' 
            AND salary > 70000;
Write a query to find all employees whose name starts with 'A'.
SELECT * FROM Employee 
            WHERE employee_name LIKE 'A%';
Write a query to find the number of employees in each department with salary greater than 50,000.
SELECT department_id, COUNT(*) 
            FROM Employee 
            WHERE salary > 50000 
            GROUP BY department_id;
Write a query to update the salary of all employees by 10%.
UPDATE Employee 
            SET salary = salary * 1.1;
Write a query to retrieve all employees who are in the 'IT' department and have been employed for more than 5 years.
SELECT * FROM Employee 
            WHERE department = 'IT' 
            AND hire_date < CURDATE() - INTERVAL 5 YEAR;
Write a query to find the employees with the lowest salary.
SELECT * FROM Employee 
            WHERE salary = (SELECT MIN(salary) FROM Employee);
Write a query to list employees who are neither managers nor supervisors.
SELECT * FROM Employee 
            WHERE job_title NOT IN ('Manager', 'Supervisor');
Write a query to find the total number of employees in the 'Sales' department.
SELECT COUNT(*) 
            FROM Employee 
            WHERE department = 'Sales';
Write a query to select the first 10 employees based on hire date.
SELECT * FROM Employee 
            ORDER BY hire_date 
            LIMIT 10;
Write a query to find the employees who have the same job title.
SELECT job_title, COUNT(*) 
            FROM Employee 
            GROUP BY job_title 
            HAVING COUNT(*) > 1;
Write a query to get the department name and the number of employees in each department.
SELECT Department.department_name, COUNT(Employee.employee_id) 
            FROM Department 
            JOIN Employee ON Employee.department_id = Department.department_id 
            GROUP BY Department.department_name;
Write a query to display the second highest salary from the Employee table.
SELECT MAX(salary) 
            FROM Employee 
            WHERE salary < (SELECT MAX(salary) FROM Employee);
Write a query to fetch employees whose salary is between 60,000 and 100,000.
SELECT * FROM Employee 
            WHERE salary BETWEEN 60000 AND 100000;
Write a query to calculate the average salary of all employees.
SELECT AVG(salary) 
            FROM Employee;
Write a query to retrieve all employees who work for the 'HR' department or 'IT' department.
SELECT * FROM Employee 
            WHERE department IN ('HR', 'IT');
Write a query to retrieve the name of employees who have been with the company for more than 10 years.
SELECT employee_name 
            FROM Employee 
            WHERE hire_date < CURDATE() - INTERVAL 10 YEAR;
Write a query to find the highest and lowest salary from the Employee table.
SELECT MAX(salary), MIN(salary) 
            FROM Employee;
Write a query to find employees who work in the 'IT' department and have more than 5 years of experience.
SELECT * FROM Employee 
            WHERE department = 'IT' 
            AND hire_date < CURDATE() - INTERVAL 5 YEAR;
Write a query to fetch employees who have received a bonus greater than 5000.
SELECT * FROM Employee 
            WHERE bonus > 5000;
Write a query to find all employees who were hired after 2015-01-01.
SELECT * FROM Employee 
            WHERE hire_date > '2015-01-01';
Write a query to find the Nth highest salary from the Employee table.
SELECT DISTINCT salary FROM Employee 
            ORDER BY salary DESC 
            LIMIT 1 OFFSET N-1;
Write a query to find employees who have the same manager as employee 'X'.
SELECT * FROM Employee 
            WHERE manager_id = (SELECT manager_id FROM Employee WHERE employee_name = 'X');
Write a query to find duplicate email addresses in a table.
SELECT email, COUNT(*) 
            FROM Employee 
            GROUP BY email 
            HAVING COUNT(*) > 1;
Write a query to find employees who have a manager but the manager is also an employee in the same table.
SELECT e1.employee_name 
            FROM Employee e1 
            JOIN Employee e2 ON e1.manager_id = e2.employee_id;
Write a query to list the employees who have a salary higher than their manager.
SELECT e1.employee_name 
            FROM Employee e1 
            JOIN Employee e2 ON e1.manager_id = e2.employee_id 
            WHERE e1.salary > e2.salary;
Write a query to calculate the total salary for each department.
SELECT department_id, SUM(salary) 
            FROM Employee 
            GROUP BY department_id;
Write a query to find the employees who have the same department but a different manager.
SELECT e1.employee_name 
            FROM Employee e1 
            JOIN Employee e2 ON e1.department_id = e2.department_id 
            WHERE e1.manager_id != e2.manager_id;
Write a query to find employees whose salary is greater than the average salary of their department.
SELECT employee_name 
            FROM Employee 
            WHERE salary > (SELECT AVG(salary) 
                             FROM Employee 
                             WHERE department_id = Employee.department_id);
Write a query to find the top 3 highest-paid employees in each department.
SELECT * 
            FROM (SELECT employee_name, salary, department_id, 
                         ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank 
                  FROM Employee) AS ranked 
            WHERE rank <= 3;
Write a query to find employees who have not been assigned a manager.
SELECT * 
            FROM Employee 
            WHERE manager_id IS NULL;
Write a query to find the difference in salary between the highest and lowest salary in each department.
SELECT department_id, 
                            (MAX(salary) - MIN(salary)) AS salary_difference 
            FROM Employee 
            GROUP BY department_id;
Write a query to find the count of employees in each department with a salary greater than 50,000.
SELECT department_id, COUNT(*) 
            FROM Employee 
            WHERE salary > 50000 
            GROUP BY department_id;
Write a query to fetch the first and last names of employees who have worked in the company for more than 5 years but have not received a promotion.
SELECT first_name, last_name 
            FROM Employee 
            WHERE hire_date < CURDATE() - INTERVAL 5 YEAR 
            AND promotion_date IS NULL;
Write a query to fetch all employees whose salary is in the top 10% of all employees.
SELECT * 
            FROM Employee 
            WHERE salary >= (SELECT salary 
                             FROM Employee 
                             ORDER BY salary DESC 
                             LIMIT 1 OFFSET (SELECT COUNT(*) * 0.1 FROM Employee));
Write a query to find employees whose salary is between the average salary and the highest salary.
SELECT employee_name 
            FROM Employee 
            WHERE salary BETWEEN (SELECT AVG(salary) FROM Employee) 
            AND (SELECT MAX(salary) FROM Employee);
Write a query to find departments that have employees who have a salary higher than the average salary of their department.
SELECT DISTINCT department_id 
            FROM Employee 
            WHERE salary > (SELECT AVG(salary) 
                             FROM Employee 
                             WHERE department_id = Employee.department_id);
Write a query to find the employees who have been with the company the longest.
SELECT employee_name 
            FROM Employee 
            WHERE hire_date = (SELECT MIN(hire_date) FROM Employee);
Write a query to get a list of employees who are the highest paid in their department.
SELECT employee_name, department_id, salary 
            FROM Employee 
            WHERE (department_id, salary) IN (SELECT department_id, MAX(salary) 
                                               FROM Employee 
                                               GROUP BY department_id);
Write a query to find the second highest salary from the Employee table.
SELECT MAX(salary) 
            FROM Employee 
            WHERE salary < (SELECT MAX(salary) FROM Employee);
Write a query to find the number of employees in each department, but exclude departments with no employees.
SELECT department_id, COUNT(*) 
            FROM Employee 
            GROUP BY department_id 
            HAVING COUNT(*) > 0;
Write a query to calculate the cumulative salary for each employee ordered by salary in ascending order.
SELECT employee_name, salary, 
                            SUM(salary) OVER (ORDER BY salary) AS cumulative_salary 
            FROM Employee;
Write a query to find employees who have worked more than 5 years in the company and have a salary above the average salary.
SELECT employee_name 
            FROM Employee 
            WHERE DATEDIFF(CURDATE(), hire_date) > 5 * 365 
            AND salary > (SELECT AVG(salary) FROM Employee);
Write a query to find all the managers who manage more than 5 employees.
SELECT manager_id, COUNT(*) 
            FROM Employee 
            GROUP BY manager_id 
            HAVING COUNT(*) > 5;
Write a query to find the average salary of employees who have worked for less than 3 years.
SELECT AVG(salary) 
            FROM Employee 
            WHERE DATEDIFF(CURDATE(), hire_date) < 3 * 365;
Write a query to find the most recent employee who joined the company.
SELECT employee_name 
            FROM Employee 
            WHERE hire_date = (SELECT MAX(hire_date) FROM Employee);
Write a query to find the department with the highest total salary expenditure.
SELECT department_id, SUM(salary) AS total_salary 
            FROM Employee 
            GROUP BY department_id 
            ORDER BY total_salary DESC 
            LIMIT 1;
Write a query to find the total number of employees in each department, including departments with no employees (use LEFT JOIN).
SELECT d.department_name, COUNT(e.employee_id) AS employee_count 
            FROM Department d 
            LEFT JOIN Employee e ON d.department_id = e.department_id 
            GROUP BY d.department_name;
Write a query to find the department with the highest average salary.
SELECT department_id, AVG(salary) AS avg_salary 
            FROM Employee 
            GROUP BY department_id 
            ORDER BY avg_salary DESC 
            LIMIT 1;

© 2025 Geeksprep - All rights reserved.

  • Privacy Policy
  • Terms of Use
  • DMCA
  • CCPA