SQL Basic and Intermediate Questions for Interview
Let's come to the point.
I have created an Awesome SQL Interview GitHub repo to prepare for interview questions and practice SQL queries. I have divided the SQL queries into three sections: Basic (L0), Intermediate (L1), and Advanced (L2). This is the solution for the basic section.
This is L1 (Intermediate) SQL queries to practice, refer to L0 first for better practice.
Note: These examples are tested in MySQL. Syntax may vary for other databases like MS-SQL or Oracle.
L1: Intermediate SQL
- Queries that involve working with multiple tables, using JOIN, GROUP BY, HAVING, and complex WHERE conditions.
- Introduction to subqueries, aggregate functions, and case statements.
Questions:
- Write a query to retrieve the customerName and city for customers in 'USA' and 'France'.
- How do you fetch the employeeNumber, lastName, and officeCode of all employees who work in the 'San Francisco' office?
- Write a query to find the total number of orders for each customer using orders and customers tables.
- How do you retrieve the productName, quantityInStock, and buyPrice for products that have been ordered more than 10 times?
- Write a query to fetch the orderNumber, status, and customerName for orders placed by a customer whose customerNumber is 103.
- Write a query to find the total sales value (quantityOrdered * priceEach) for each order in the orderdetails table.
- How do you find the average quantityOrdered for each orderNumber in the orderdetails table?
- Write a query to list the productLine with the highest total revenue (quantityOrdered * priceEach) in the orderdetails table.
- Write a query to display the employeeNumber, firstName, lastName, and the office name where the employee works by joining the employees and offices tables.
- How do you find the customers who have never placed an order?
- Write a query to retrieve the customerName and the total number of orders placed by each customer (include customers who haven’t placed any orders).
- Write a query to find the productName and quantityOrdered for all orders where the quantity of the product ordered is greater than 50.
- Retrieve the employeeNumber, firstName, and orderNumber of employees who are assigned as sales representatives to customers that have placed an order.
- Write a query to calculate the average price of products in the products table based on buyPrice.
- How do you fetch the top 3 most expensive products in the products table?
- Write a query to retrieve the customerName, orderNumber, and orderDate of all orders that have a status of 'Shipped'.
- How do you display the total number of products sold for each productLine?
- Write a query to find employees who report directly to the employee with employeeNumber = 1143.
- Write a query to calculate the total number of orders in the orders table, grouped by status.
- List employees with their manager’s name.
I will mention wrong things also, It is important to know what do to but also very important what not to do, and where we make mistake. let's go to the point again...
Solution with the explanation WHERE needed
-
Query to retrieve the customerName and city for customers in 'USA' and 'France'.
- OR -> Slightly slower if there are a lot of conditions, as the query checks each condition one by one.
- IN -> slightly optimized internally by the database engine, especially for long lists.
- Both are fine for 2-3 conditions. For readability and scalability, IN is better, especially when handling larger lists of values.
- IS is used for checking conditions like IS NULL or IS NOT NULL, not for string comparison.
Fetch the employeeNumber, lastName, and officeCode of all employees who work in the 'San Francisco' office.
-
Query to find the total number of orders for each customer using orders and customers tables.
- Always include non-aggregated columns in the GROUP BY clause when using aggregate functions in your query.
- This ensures SQL knows how to group rows and avoids ambiguity when selecting additional columns.
- In our example: customerNumber and customerName must both be in the GROUP BY clause since we are selecting them along with COUNT(*).
? Golden Rule:
Every column in the SELECT list must either:
Be in the GROUP BY clause, OR
Use an aggregate function like COUNT(), SUM(), etc. -
Retrieve the productName, quantityInStock, and buyPrice for products that have been ordered more than 10 times?
- This query is efficient for small and medium size databases, for large sizes we can use indexes, and reduce data scanned using WHERE clause instead of relying solely on HAVING clause
-
Fetch the orderNumber, status, and customerName for orders placed by a customer whose customerNumber is 103.
Explanation:
- Tables Used:
- orders: Contains orderNumber and status.
- customers: Contains customerName.
- INNER JOIN:
- Combines orders and customers tables using the customerNumber column (common key).
- WHERE Clause:
- Filters the data to include only records where customerNumber = 103.
- Columns Selected:
- o.orderNumber: The order number.
- o.status: The order status.
- c.customerName: The name of the customer placing the order.
- Tables Used:
Find the total sales value (quantityOrdered * priceEach) for each order in the orderdetails table.
-
Find the average quantityOrdered for each orderNumber in the orderdetails table.
- Explanation:
- orderNumber:
- Groups the rows by the orderNumber.
- AVG(quantityOrdered):
- Calculates the average quantityOrdered for all rows that belong to the same orderNumber.
- GROUP BY:
- Ensures the average is calculated for each orderNumber separately.
-
Query to list the productLine with the highest total revenue (quantityOrdered * priceEach) in the orderdetails table.
- Explanation:
- productLine:
- Categorizes the products into different lines, like "Motorcycles" or "Planes."
- SUM(od.quantityOrdered * od.priceEach):
- Calculates the total revenue for each productLine.
- INNER JOIN:
- Joins products and orderdetails tables on productCode to associate product lines with their order details.
- GROUP BY p.productLine:
- Groups the results by each productLine.
- ORDER BY totalRevenue DESC:
- Sorts the grouped results in descending order of revenue, so the highest revenue appears first.
- LIMIT 1:
- Restricts the result to only the productLine with the highest revenue.
-
Query to display the employeeNumber, firstName, lastName, and the office name where the employee works by joining the employees and offices tables.
- CONCAT(column, 'separater', column, 'separater', column)
- CONCAT_WS('separater', columns)
-
Find the customers who have never placed an order
Explanation:
- LEFT JOIN: Retrieves all customers from the customers table, whether or not they have matching rows in the orders table.
- o.orderNumber IS NULL: Identifies customers who do not have any corresponding orders (i.e., orderNumber is NULL because there's no match in the orders table).
-
Columns:
- customerNumber: Unique identifier for the customer.
- customerName: Name of the customer.
Query to retrieve the customerName and the total number of orders placed by each customer (include customers who haven’t placed any orders).
Find the productName and quantityOrdered for all orders where the quantity of the product ordered is greater than 50.
-
Retrieve the employeeNumber, firstName, and orderNumber of employees who are assigned as sales representatives to customers that have placed an order.
Explanation:
-
FROM employees e:
- We start with the employees table (aliased as e) because we want the employee details, specifically the employeeNumber and firstName.
-
JOIN customers c ON e.employeeNumber = c.salesRepEmployeeNumber:
- We join the customers table (aliased as c) on the employeeNumber from employees and salesRepEmployeeNumber from customers. This creates the relationship between employees (sales reps) and customers. Now, we can identify which employee is assigned to each customer.
-
JOIN orders o ON c.customerNumber = o.customerNumber:
- We further join the orders table (aliased as o) with the customers table using the customerNumber. This gives us the orders placed by each customer.
-
SELECT e.employeeNumber, e.firstName, o.orderNumber:
- Finally, we select the employeeNumber and firstName from the employees table (sales reps) and the orderNumber from the orders table for each customer who has placed an order.
-
FROM employees e:
Query to calculate the average price of products in the products table based on buyPrice.
Fetch the top 3 most expensive products in the products table?
Rretrieve the customerName, orderNumber, and orderDate of all orders that have a status of 'Shipped'.
Display the total number of products sold for each productLine
Find employees who report directly to the employee with employeeNumber = 1143.
Query to calculate the total number of orders in the orders table, grouped by status.
List employees with their manager’s name.
Hey, My name is Jaimin Baria AKA Cloud Boy..., If you have enjoyed and learned something useful, like this post, add a comment, and visit my Awesome SQL Interview GitHub repo.
Don't forget to give it a start ?.
Happy Coding ??
Other Posts
- SQL Practices:
- Part 1
- L0: Basic SQL
- L1: Intermediate SQL
- L2: Advanced SQL - Will Come soon
- Part 1
- System Design
- Implementation of ACID transaction in Database
- ACID Transactions in System Design
?️ Fixes Suggested by Readers
The above is the detailed content of SQL Basic and Intermediate Questions for Interview. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.
