100 SQL Fundamental Interview Question With Answers
100 SQL Fundamental Interview Question With Answers
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL OUTER JOIN
-- INNER JOIN
SELECT employees.name, departments.name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
-- LEFT JOIN
SELECT employees.name, departments.name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id;
-- RIGHT JOIN
SELECT employees.name, departments.name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id;
INNER JOIN: Returns only the rows where there is a match in both tables involved in the join. If there are no matching rows, the
result is null.
OUTER JOIN: Includes all rows from one table and the matching rows from the other table. If there is no match, it returns null for the
columns from the table without a match. This can be further divided into:
LEFT JOIN: Includes all rows from the left table.
RIGHT JOIN: Includes all rows from the right table.
-- INNER JOIN
SELECT employees.name, departments.name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
-- LEFT JOIN
SELECT employees.name, departments.name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id;
-- RIGHT JOIN
SELECT employees.name, departments.name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id;
6. What is a subquery?
Answer:
A subquery is a query nested inside another query. It is used to perform intermediate steps in complex queries, often for filtering results or
performing calculations that are then used by the main query.
-- Subquery to find employees with salary greater than the average salary
SELECT name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
DELETE: Removes specified rows from a table based on a condition and can be rolled back if used within a transaction. It also fires
any associated triggers.
TRUNCATE: Removes all rows from a table without logging individual row deletions and cannot be rolled back in most databases.
TRUNCATE is faster than DELETE and resets any identity columns.
-- DELETE
DELETE FROM employees WHERE department_id = 1;
-- TRUNCATE
TRUNCATE TABLE employees;
-- Example of a trigger
CREATE TRIGGER trgAfterInsert ON employees
FOR INSERT
AS
BEGIN
PRINT 'New employee record inserted';
END;
-- Example of a transaction
BEGIN TRANSACTION;
INSERT INTO employees (id, name, department) VALUES (2, 'Jane Doe', 'Finance');
COMMIT;
COMMIT: Saves all changes made in the transaction to the database permanently.
ROLLBACK: Reverts all changes made in the transaction, restoring the database to its previous state before the transaction began.
-- Example of COMMIT
BEGIN TRANSACTION;
INSERT INTO employees (id, name, department) VALUES (3, 'Mike Smith', 'IT');
COMMIT;
-- Example of ROLLBACK
BEGIN TRANSACTION;
INSERT INTO employees (id, name, department) VALUES (4, 'Anna Johnson', 'HR');
ROLLBACK;
-- Example of HAVING
SELECT department, COUNT(*), AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
WHERE Clause: Filters individual rows before any groupings are made. It cannot be used with aggregate functions.
HAVING Clause: Filters groups of rows after the GROUP BY clause. It can be used with aggregate functions.
-- Example of WHERE
SELECT * FROM employees WHERE salary > 50000;
-- Example of HAVING
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
-- Example of UNION
SELECT name FROM employees
UNION
SELECT name FROM managers;
23. What is the difference between UNION and UNION ALL?
Answer:
UNION: Combines the result sets of two or more SELECT queries and removes duplicate rows.
UNION ALL: Combines the result sets of two or more SELECT queries and includes duplicate rows.
-- Example of UNION
SELECT name FROM employees
UNION
SELECT name FROM managers;
-- Example of DISTINCT
SELECT DISTINCT department FROM employees;
DDL (Data Definition Language): Includes commands like CREATE, ALTER, DROP.
DML (Data Manipulation Language): Includes commands like SELECT, INSERT, UPDATE, DELETE.
DCL (Data Control Language): Includes commands like GRANT, REVOKE.
TCL (Transaction Control Language): Includes commands like COMMIT, ROLLBACK, SAVEPOINT.
DQL (Data Query Language): Primarily includes the SELECT command.
-- Example of DDL command
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(100)
);
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
-- Example of constraints
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
department_id INT,
salary DECIMAL CHECK (salary > 0),
FOREIGN KEY (department_id) REFERENCES departments(id)
);
28. What is the difference between CHAR and VARCHAR data types?
Answer:
CHAR: A fixed-length character data type. It always uses the specified number of bytes, regardless of the length of the stored string.
VARCHAR: A variable-length character data type. It uses only as many bytes as necessary to store the string, up to the specified
maximum length.
-- Example of an alias
SELECT e.name AS employee_name, d.name AS department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;
Clustered Index: Sorts and stores the data rows in the table based on the index key. There can be only one clustered index per
table.
Non-Clustered Index: Creates a separate structure from the data rows. The index contains pointers to the data rows. There can be
multiple non-clustered indexes per table.
-- Example of clustered and non-clustered index
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(100)
);
-- Example of a self-join
SELECT e1.name AS employee_name, e2.name AS manager_name
FROM employees e1
JOIN employees e2 ON e1.manager_id = e2.id;
Atomicity: Ensures that all operations within a transaction are completed successfully; otherwise, the transaction is aborted.
Consistency: Ensures that a transaction brings the database from one valid state to another.
Isolation: Ensures that the operations of one transaction are isolated from those of other transactions.
Durability: Ensures that the results of a committed transaction are permanently saved in the database.
-- Example of ORDER BY
SELECT * FROM employees ORDER BY salary DESC;
-- Example of LIMIT
SELECT * FROM employees ORDER BY salary DESC LIMIT 10;
Alias: A temporary name given to a table or column in a SQL query for the duration of that query.
Synonym: A permanent alias for a database object, which remains until explicitly dropped.
-- Example of alias
SELECT e.name AS employee_name, d.name AS department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;
-- Example of synonym
CREATE SYNONYM emp FOR employees;
SELECT * FROM emp;
47. What is the difference between SQL and PL/SQL?
Answer:
RANK(): Assigns a rank to each row within a partition, with gaps in the ranking sequence for ties.
DENSE_RANK(): Assigns a rank to each row within a partition without gaps in the ranking sequence for ties.
58. What is the difference between INNER JOIN and CROSS JOIN?
Answer:
INNER JOIN: Returns only the rows where there is a match in both tables based on the specified condition.
CROSS JOIN: Returns the Cartesian product of two tables, including all possible combinations of rows from both tables.
62. What is the difference between a primary key and a unique key?
Answer:
Primary Key: Uniquely identifies each row in a table and does not allow NULL values. A table can have only one primary key.
Unique Key: Ensures that all values in a column or a set of columns are unique. It allows NULL values (only one per column) and a
table can have multiple unique keys.
-- Example of AUTO_INCREMENT
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(100)
);
COUNT(*): Counts all rows in the table, including rows with NULL values.
COUNT(column_name): Counts non-NULL values in the specified column.
-- Example of COUNT(*)
SELECT COUNT(*) FROM employees;
-- Example of COUNT(column_name)
SELECT COUNT(department) FROM employees;
69. What is the purpose of the TO_DATE function in SQL?
Answer:
The TO_DATE function converts a string to a date data type. It is used to transform string representations of dates into actual date values for
use in queries and calculations.
TRUNCATE: Removes all rows from a table but retains the table structure for future use. It is faster than DELETE and cannot be
rolled back in most databases.
DROP: Deletes the table and its structure from the database entirely.
-- Example of TRUNCATE
TRUNCATE TABLE employees;
-- Example of DROP
DROP TABLE employees;
-- Example of IS NULL
SELECT * FROM employees WHERE salary IS NULL;
84. What is the difference between the EQUI JOIN and NON-EQUI
JOIN?
Answer:
EQUI JOIN: A type of join that uses the equality operator (=) to match rows between tables based on a common column.
NON-EQUI JOIN: A type of join that uses operators other than the equality operator (such as <, >, <=, >=, <>) to match rows
between tables.
-- Example of EQUI JOIN
SELECT e.name, d.name AS department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;
89. What is the difference between the DATE and TIMESTAMP data
types in SQL?
Answer:
99. What is the difference between the ROLLUP and CUBE operators
in SQL?
Answer:
ROLLUP: Generates subtotals that roll up from the most detailed level to a grand total.
CUBE: Generates subtotals for all possible combinations of a group of columns, including a grand total.
-- Example of ROLLUP
SELECT department, job_title, SUM(salary)
FROM employees
GROUP BY ROLLUP(department, job_title);
-- Example of CUBE
SELECT department, job_title, SUM(salary)
FROM employees
GROUP BY CUBE(department, job_title);
Follow me on:
LinkedIn (https://www.linkedin.com/in/ashish-jangra/)
GitHub (https://github.com/AshishJangra27)
Kaggle (https://www.kaggle.com/ashishjangra27)