SQL Basic and Intermediate levels Questions, with answers and examples
Basic SQL Questions
1. What is SQL?
Answer: SQL (Structured Query Language) is used for managing and manipulating relational databases.
2. What is a database?
Answer: An organized collection of data stored electronically and managed by a DBMS.
3. What is a table in SQL?
Answer: A table is a collection of rows and columns in a database, representing structured data.
Example:
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(50),
Price DECIMAL(10, 2)
);
4. What is a primary key?
Answer: A primary key is a unique identifier for each record in a table.
Example:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE
);
5. What is a foreign key?
Answer: A foreign key is a column or set of columns in one table that uniquely identifies rows in another table.
Example:
CREATE TABLE OrderDetails (
OrderDetailID INT PRIMARY KEY,
OrderID INT,
ProductID INT,
FOREIGN KEY (OrderID) REFERENCES Orders(OrderID)
);
6. What is a JOIN? Explain different types of JOINs.
Answer: JOIN combines rows from two or more tables based on a related column.
INNER JOIN: Returns rows with matching values in both tables.
LEFT JOIN: Returns all rows from the left table and matched rows from the right table.
RIGHT JOIN: Returns all rows from the right table and matched rows from the left table.
FULL JOIN: Returns rows when there is a match in either table.
Example:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
LEFT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
7. What is the SELECT statement used for?
Answer: Retrieves data from a database.
Example:
SELECT ProductName, Price
FROM Products;
8. What is the WHERE clause used for?
Answer: Filters records based on specified conditions.
Example:
SELECT ProductName, Price
FROM Products
WHERE Price > 20.00;
9. What does the GROUP BY clause do?
Answer: Groups rows that have the same values into summary rows.
Example:
SELECT Department, COUNT(*)
FROM Employees
GROUP BY Department;
10. What is an ORDER BY clause?
Answer: Sorts the result set of a query by one or more columns.
Example:
SELECT FirstName, LastName
FROM Employees
ORDER BY LastName ASC;
11. What is the INSERT INTO statement?
Answer: Adds new rows to a table.
Example:
INSERT INTO Products (ProductID, ProductName, Price)
VALUES (1, 'Laptop', 999.99);
12. What does the UPDATE statement do?
Answer: Modifies existing records in a table.
Example:
UPDATE Products
SET Price = Price * 1.10
WHERE ProductID = 1;
13. What is the DELETE statement used for?
Answer: Removes rows from a table.
Example:
DELETE FROM Products
WHERE ProductID = 1;
14. What is an ALTER TABLE statement?
Answer: Modifies the structure of an existing table.
Example:
ALTER TABLE Products
ADD Category VARCHAR(50);
15. What does DISTINCT do in a query?
Answer: Removes duplicate rows from the result set.
Example:
SELECT DISTINCT Category
FROM Products;
16. What is a VIEW in SQL?
Answer: A virtual table based on the result of a query.
Example:
CREATE VIEW ActiveEmployees AS
SELECT FirstName, LastName
FROM Employees
WHERE Status = 'Active';
17. What is the LIMIT clause used for?
Answer: Limits the number of rows returned by a query.
Example:
SELECT * FROM Products
LIMIT 5;
18. What is the HAVING clause?
Answer: Filters groups based on aggregated data.
Example:
SELECT Department, COUNT(*)
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
19. How do you create an index on a table?
Answer: Improves query performance by allowing faster data retrieval.
Example:
CREATE INDEX idx_price
ON Products (Price);
20. What is a NULL value in SQL?
Answer: Represents the absence of a value or an unknown value.
Example:
SELECT * FROM Employees
WHERE Email IS NULL;
21. What is a DEFAULT value in SQL?
Answer: Provides a default value for a column when no value is specified during insertion.
Example:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Status VARCHAR(10) DEFAULT 'Active'
);
22. How do you use the IN operator in SQL?
Answer: Tests if a value is within a set of values.
Example:
SELECT * FROM Products
WHERE Category IN ('Electronics', 'Appliances');
23. What is the purpose of the BETWEEN operator?
Answer: Filters the result set within a specified range.
Example:
SELECT * FROM Products
WHERE Price BETWEEN 50 AND 150;
24. What is a SUBQUERY ?
Answer: A query nested inside another query.
Example:
SELECT FirstName, LastName
FROM Employees
WHERE DepartmentID = (
SELECT DepartmentID
FROM Departments
WHERE DepartmentName = 'HR'
);
25. How do you use the LIKE operator?
Answer: Searches for a specified pattern in a column.
Example:
SELECT * FROM Products
WHERE ProductName LIKE 'Laptop%';
26. What does TRUNCATE TABLE do?
Answer: Removes all rows from a table and resets any auto-increment counters.
Example:
TRUNCATE TABLE Products;
27. How do you use CONCAT in SQL?
Answer: Concatenates two or more strings.
Example:
SELECT CONCAT(FirstName, ' ', LastName) AS FullName
FROM Employees;
28. What is the COALESCE function?
Answer: Returns the first non-NULL value from a list of expressions.
Example:
SELECT COALESCE(Phone, 'No phone number') AS ContactNumber
FROM Customers;
29. What is a TRIGGER ?
Answer: A trigger automatically executes in response to specific events on a table.
Example:
CREATE TRIGGER BeforeInsertEmployee
BEFORE INSERT ON Employees
FOR EACH ROW
BEGIN
-- Trigger logic here
END;
30. What is an ENUM type in SQL?
Answer: An ENUM type allows you to define a column that can store one value from a list of predefined values.
Example:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
Status ENUM('Pending', 'Shipped', 'Delivered') NOT NULL
);
Intermediate SQL Questions
1. What is an INNER JOIN ?
Answer: Combines rows from two tables where there is a match in both tables.
Example:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
2. What is a LEFT JOIN ?
Answer: Returns all rows from the left table and matched rows from the right table. Non-matching rows from the right table will have NULL
values.
Example:
SELECT Employees.First
Name, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
3. **What is a `RIGHT JOIN`?**
- **Answer:** Returns all rows from the right table and matched rows from the left table. Non-matching rows from the left table will have NULL va
**Example:**
```sql
SELECT Orders.OrderID, Products.ProductName
FROM Orders
RIGHT JOIN Products ON Orders.ProductID = Products.ProductID;
4. What is a FULL JOIN ?
Answer: Returns rows when there is a match in either table. Non-matching rows from both tables will have NULL values.
Example:
SELECT Employees.FirstName, Departments.DepartmentName
FROM Employees
FULL JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
5. What is a subquery?
Answer: A query nested inside another query. Subqueries are used to retrieve data that will be used in the main query.
Example:
SELECT FirstName, LastName
FROM Employees
WHERE DepartmentID IN (
SELECT DepartmentID
FROM Departments
WHERE DepartmentName = 'Sales'
);
6. What is the purpose of GROUP_CONCAT ?
Answer: Aggregates values from multiple rows into a single string.
Example:
SELECT Department, GROUP_CONCAT(EmployeeName)
FROM Employees
GROUP BY Department;
7. What is a Common Table Expression (CTE) ?
Answer: A temporary result set that can be referenced within a SELECT , INSERT , UPDATE , or DELETE statement.
Example:
WITH DepartmentSales AS (
SELECT Department, SUM(Sales) AS TotalSales
FROM Sales
GROUP BY Department
)
SELECT Department
FROM DepartmentSales
WHERE TotalSales > 10000;
8. What is a stored procedure?
Answer: A precompiled collection of SQL statements that can be executed as a unit.
Example:
CREATE PROCEDURE GetEmployeeByID (@EmployeeID INT)
AS
BEGIN
SELECT * FROM Employees
WHERE EmployeeID = @EmployeeID;
END;
9. How do you create a trigger?
Answer: A trigger automatically executes in response to certain events on a table.
Example:
CREATE TRIGGER UpdateEmployeeHistory
ON Employees
AFTER UPDATE
AS
BEGIN
INSERT INTO EmployeeHistory (EmployeeID, ChangeDate, NewSalary)
SELECT EmployeeID, GETDATE(), Salary
FROM inserted;
END;
10. What is a window function?
Answer: Performs calculations across a set of table rows related to the current row, such as ranking or aggregate calculations.
Example:
SELECT EmployeeID, Salary,
RANK() OVER (ORDER BY Salary DESC) AS SalaryRank
FROM Employees;
11. What is the RANK() function?
Answer: Assigns a rank to each row within the partition of a result set, with gaps in ranking when there are ties.
Example:
SELECT EmployeeID, Salary,
RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS Rank
FROM Employees;
12. What is the ROW_NUMBER() function?
Answer: Assigns a unique sequential integer to rows within a partition of a result set.
Example:
SELECT EmployeeID, Salary,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum
FROM Employees;
13. How do you use the PIVOT operator?
Answer: Converts rows into columns for better data presentation.
Example:
SELECT Department, [Jan], [Feb], [Mar]
FROM (
SELECT Department, Month, Sales
FROM SalesData
) AS SourceTable
PIVOT (
SUM(Sales)
FOR Month IN ([Jan], [Feb], [Mar])
) AS PivotTable;
14. What is a MERGE statement?
Answer: Performs an INSERT , UPDATE , or DELETE operation based on matching conditions.
Example:
MERGE INTO TargetTable AS Target
USING SourceTable AS Source
ON Target.ID = Source.ID
WHEN MATCHED THEN
UPDATE SET Target.Column1 = Source.Column1
WHEN NOT MATCHED THEN
INSERT (ID, Column1) VALUES (Source.ID, Source.Column1);
15. What is an INTERSECT operator?
Answer: Returns common rows from two SELECT statements.
Example:
SELECT EmployeeID FROM Employees
INTERSECT
SELECT EmployeeID FROM Managers;
16. What is a UNION ALL operator?
Answer: Combines the result sets of two or more SELECT statements, including duplicates.
Example:
SELECT FirstName FROM Employees
UNION ALL
SELECT FirstName FROM Managers;
17. What is the EXISTS operator?
Answer: Tests for the existence of rows returned by a subquery.
Example:
SELECT FirstName
FROM Employees
WHERE EXISTS (
SELECT 1
FROM Orders
WHERE Orders.EmployeeID = Employees.EmployeeID
);
18. How do you use the CASE statement in SQL?
Answer: Provides conditional logic within SQL queries.
Example:
SELECT EmployeeID, Salary,
CASE
WHEN Salary > 100000 THEN 'High'
WHEN Salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'Low'
END AS SalaryCategory
FROM Employees;
19. What is a SELF JOIN ?
Answer: Joins a table with itself.
Example:
SELECT e1.EmployeeID, e1.FirstName AS Employee, e2.FirstName AS Manager
FROM Employees e1
INNER JOIN Employees e2 ON e1.ManagerID = e2.EmployeeID;
20. What is the COALESCE function?
Answer: Returns the first non-NULL value from a list of expressions.
Example:
SELECT EmployeeID, COALESCE(Phone, 'No phone number') AS ContactNumber
FROM Employees;
21. What is a PARTITION BY clause in SQL?
Answer: Divides the result set into partitions to perform calculations across each partition separately.
Example:
SELECT EmployeeID, Salary,
SUM(Salary) OVER (PARTITION BY Department) AS DepartmentTotal
FROM Employees;
22. What is a ROW_NUMBER() function?
Answer: Assigns a unique sequential integer to rows within a partition of a result set.
Example:
SELECT EmployeeID, Salary,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum
FROM Employees;
23. What is a CROSS JOIN ?
Answer: Produces the Cartesian product of two tables.
Example:
SELECT Employees.FirstName, Departments.DepartmentName
FROM Employees
CROSS JOIN Departments;
24. How do you handle transactions in SQL?
Answer: Transactions ensure that a series of SQL statements are executed as a single unit of work, and they can be rolled back if any statement
fails.
Example:
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2;
COMMIT;
25. What is the purpose of ROLLBACK in SQL?
Answer: Reverts changes made in the current transaction.
Example:
BEGIN TRANSACTION;
UPDATE Products SET Price = Price - 50 WHERE ProductID = 1;
ROLLBACK;
26. What is the TRUNCATE command used for?
Answer: Removes all rows from a table and resets any auto-increment values. It is faster than DELETE but cannot be rolled back in most
databases.
Example:
TRUNCATE TABLE Products;
27. How do you use the REPLACE function in SQL?
Answer: Replaces occurrences of a substring within a string with another substring.
Example:
SELECT REPLACE(ProductName, 'Old', 'New') AS UpdatedProductName
FROM Products;
28. What is a NOT EXISTS operator?
Answer: Tests if no rows are returned by a subquery.
**Example
😗*
sql SELECT ProductID FROM Products WHERE NOT EXISTS ( SELECT 1 FROM Orders WHERE Orders.ProductID = Products.Pr
29. What is a CONSTRAINT ?
Answer: A rule enforced on data columns to ensure data integrity.
Example:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE
);
30. How do you implement data integrity with FOREIGN KEY constraints?
Answer: Ensures that a value in one table corresponds to a value in another table, maintaining referential integrity.
Example:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);