datalitico.com

SQL Interview Questions

Our carefully crafted collection of SQL Interview Questions covers a wide spectrum of difficulty levels, from beginner to advanced, and is accompanied by detailed answers. Whether you’re a novice looking to grasp the fundamentals or a SQL pro aiming to tackle complex queries with confidence, our resource is designed to check your knowledge and help you prepare for your next job interview.

Beginner

SQL (Structured Query Language) is a programming language used for managing and querying relational databases. It’s essential in data analysis because it allows users to retrieve, manipulate, and analyze data stored in databases efficiently.

To retrieve all records from the “Employees” table, you can use the SQL query: SELECT * FROM Employees;

The WHERE clause is used to filter records based on specific conditions. For example, SELECT * FROM Customers WHERE Country='USA'; retrieves all records from the “Customers” table where the “Country” column equals ‘USA.’

To sort records in ascending order, use ORDER BY with no additional keyword. To sort in descending order, add DESC after the column name. For example, SELECT * FROM Products ORDER BY Price DESC; sorts products by price in descending order.

The COUNT function returns the number of rows that match a specified condition. For instance, SELECT COUNT(*) FROM Orders WHERE CustomerID=1; counts the number of orders for a customer with ID 1.

The LIMIT clause restricts the number of rows returned, while the OFFSET clause skips a specified number of rows. For example, SELECT * FROM Customers LIMIT 10 OFFSET 20; retrieves 10 records starting from the 21st record, which is useful for pagination.

The LIKE operator is used to search for patterns in text data. Wildcard characters ‘%’ (matches any sequence of characters) and ‘_’ (matches any single character) can be used. For example, SELECT * FROM Products WHERE ProductName LIKE 'App%'; retrieves products with names starting with “App.”

The DISTINCT keyword removes duplicate values from the result set. For example, SELECT DISTINCT Category FROM Products; retrieves unique product categories, useful for exploring distinct values in a column.

Aggregate functions perform calculations on groups of rows. For example:

  • SELECT AVG(Price) FROM Products; calculates the average price.
  • SELECT SUM(Quantity) FROM Orders; calculates the total quantity ordered.
  • SELECT MAX(Salary) FROM Employees; retrieves the highest salary.

SQL data types define the kind of data a column can hold. Common data types include INTEGER (whole numbers), VARCHAR (variable-length character strings), and DATE (date values). Choosing the right data type is crucial for data accuracy, storage efficiency, and query optimization.

Intermediate

SQL JOINs combine data from multiple tables based on a related column. An INNER JOIN returns only matching rows.

For example,

SELECT Orders.OrderID, Customers.CustomerName

FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

combines orders and customer data and will display only matching rows.

SQL GROUP BY groups rows with the same values in specified columns, and HAVING filters grouped results. For example, SELECT Country, COUNT(CustomerID) FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5; lists countries with more than 5 customers.

A subquery is a query embedded within another query. For example,

SELECT ProductName FROM Products

WHERE SupplierID IN

(SELECT SupplierID FROM Suppliers WHERE Country='USA');

retrieves product names from suppliers in the USA.

To add records: INSERT INTO Employees (FirstName, LastName) VALUES ('John', 'Doe');

To update records: UPDATE Employees SET Salary=60000 WHERE EmployeeID=1;

To delete records: DELETE FROM Customers WHERE CustomerID=5;

The DISTINCT keyword removes duplicate values from the result set. For example, SELECT DISTINCT Category FROM Products; retrieves unique product categories, useful for exploring distinct values in a column.

Indexes improve query performance by allowing faster data retrieval. Clustered indexes determine the physical order of data in a table and are typically used on the primary key. Non-clustered indexes are used on columns frequently searched but don’t affect data order. Use clustered indexes for primary keys and non-clustered indexes for commonly searched columns.

A self-join is used to combine data from a single table based on a related column. For example, to find employees who manage other employees in an “Employees” table, you can use a self-join:

SELECT e1.EmployeeName AS Manager, e2.EmployeeName AS Employee FROM Employees e1 INNER JOIN Employees e2 ON e1.EmployeeID = e2.ManagerID;

Transactions ensure data consistency by allowing a series of SQL statements to be executed as a single unit. For example:

BEGIN TRANSACTION; UPDATE Accounts SET Balance=Balance-500 WHERE AccountID=1; UPDATE Accounts SET Balance=Balance+500 WHERE AccountID=2; COMMIT;

Window functions perform calculations across a set of table rows. The ROW_NUMBER() function assigns unique row numbers. For example, SELECT ProductName, Price, ROW_NUMBER() OVER (ORDER BY Price) AS RowNum FROM Products; assigns row numbers based on ascending product prices.

Advanced

Triggers are database objects that automatically respond to events like INSERT, UPDATE, or DELETE operations. For example, you can use a trigger to automatically log changes to a specific table whenever a record is updated, ensuring data integrity and auditing.

Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity. An example of a normalized database structure is splitting customer data into separate tables for customers, orders, and products, linked by keys, minimizing data duplication.

UNION combines results of two or more SELECT statements, removing duplicates, while UNION ALL includes all rows, including duplicates. For example:

  • SELECT ProductName FROM Products WHERE Category='Electronics' UNION SELECT ProductName FROM Products WHERE Category='Appliances'; combines unique product names.
  • SELECT ProductName FROM Products WHERE Category='Electronics' UNION ALL SELECT ProductName FROM Products WHERE Category='Appliances'; combines all product names.

Stored procedures are precompiled SQL code blocks that can be executed on demand. For example:

CREATE PROCEDURE GetEmployeeInfo AS BEGIN SELECT FirstName, LastName, Salary FROM Employees; END;

This stored procedure retrieves employee information.

Indexes improve query performance by allowing faster data retrieval. They are like a table of contents for a database. For example, creating an index on a frequently queried column can significantly speed up SELECT statements involving that column.

The CASE statement allows you to perform conditional operations and create data categorization. For example, SELECT ProductName, Price, CASE WHEN Price > 100 THEN 'Expensive' ELSE 'Affordable' END AS PriceCategory FROM Products; categorizes products based on their price.

SQL data types define the kind of data a column can hold. User-defined data types (UDTs) allow you to create custom data types for specific needs. For example, you might create a UDT for storing complex geographic coordinates with attributes like latitude and longitude.

Foreign keys establish relationships between tables by referencing the primary key of another table. They ensure data integrity by enforcing referential integrity rules. For example, a foreign key in an “Orders” table referencing the “Customers” table’s primary key ensures that orders are associated with existing customers.

SQL views are virtual tables created from the result of a SELECT statement. They simplify complex queries and restrict access to certain data.

For example,

CREATE VIEW HighValueProducts AS SELECT * FROM Products WHERE Price > 100; creates a view for high-value products.

CTEs are temporary result sets defined within a SELECT, INSERT, UPDATE, or DELETE statement. They simplify complex queries and allow recursive operations. For example, a CTE can be used to traverse hierarchical data structures like organizational charts or bill of materials.

Scroll to Top