search
HomeDatabaseMysql TutorialSQL 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:

  1. Write a query to retrieve the customerName and city for customers in 'USA' and 'France'.
  2. How do you fetch the employeeNumber, lastName, and officeCode of all employees who work in the 'San Francisco' office?
  3. Write a query to find the total number of orders for each customer using orders and customers tables.
  4. How do you retrieve the productName, quantityInStock, and buyPrice for products that have been ordered more than 10 times?
  5. Write a query to fetch the orderNumber, status, and customerName for orders placed by a customer whose customerNumber is 103.
  6. Write a query to find the total sales value (quantityOrdered * priceEach) for each order in the orderdetails table.
  7. How do you find the average quantityOrdered for each orderNumber in the orderdetails table?
  8. Write a query to list the productLine with the highest total revenue (quantityOrdered * priceEach) in the orderdetails table.
  9. Write a query to display the employeeNumber, firstName, lastName, and the office name where the employee works by joining the employees and offices tables.
  10. How do you find the customers who have never placed an order?
  11. 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).
  12. Write a query to find the productName and quantityOrdered for all orders where the quantity of the product ordered is greater than 50.
  13. Retrieve the employeeNumber, firstName, and orderNumber of employees who are assigned as sales representatives to customers that have placed an order.
  14. Write a query to calculate the average price of products in the products table based on buyPrice.
  15. How do you fetch the top 3 most expensive products in the products table?
  16. Write a query to retrieve the customerName, orderNumber, and orderDate of all orders that have a status of 'Shipped'.
  17. How do you display the total number of products sold for each productLine?
  18. Write a query to find employees who report directly to the employee with employeeNumber = 1143.
  19. Write a query to calculate the total number of orders in the orders table, grouped by status.
  20. 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

  1. Query to retrieve the customerName and city for customers in 'USA' and 'France'.
    SQL Basic and Intermediate Questions for Interview

    • 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.
  2. Fetch the employeeNumber, lastName, and officeCode of all employees who work in the 'San Francisco' office.
    SQL Basic and Intermediate Questions for Interview

  3. Query to find the total number of orders for each customer using orders and customers tables.
    SQL Basic and Intermediate Questions for Interview

    • 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.

  4. Retrieve the productName, quantityInStock, and buyPrice for products that have been ordered more than 10 times?
    SQL Basic and Intermediate Questions for Interview

    • 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
  5. Fetch the orderNumber, status, and customerName for orders placed by a customer whose customerNumber is 103.
    SQL Basic and Intermediate Questions for Interview

    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.
  6. Find the total sales value (quantityOrdered * priceEach) for each order in the orderdetails table.
    SQL Basic and Intermediate Questions for Interview

  7. Find the average quantityOrdered for each orderNumber in the orderdetails table.
    SQL Basic and Intermediate Questions for Interview

    • 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.
  8. Query to list the productLine with the highest total revenue (quantityOrdered * priceEach) in the orderdetails table.
    SQL Basic and Intermediate Questions for Interview

    • 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.
  9. Query to display the employeeNumber, firstName, lastName, and the office name where the employee works by joining the employees and offices tables.
    SQL Basic and Intermediate Questions for Interview

    • CONCAT(column, 'separater', column, 'separater', column)
    • CONCAT_WS('separater', columns)
  10. Find the customers who have never placed an order
    SQL Basic and Intermediate Questions for Interview

    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.
  11. Query to retrieve the customerName and the total number of orders placed by each customer (include customers who haven’t placed any orders). SQL Basic and Intermediate Questions for Interview

  12. Find the productName and quantityOrdered for all orders where the quantity of the product ordered is greater than 50.
    SQL Basic and Intermediate Questions for Interview

  13. Retrieve the employeeNumber, firstName, and orderNumber of employees who are assigned as sales representatives to customers that have placed an order.
    SQL Basic and Intermediate Questions for Interview

    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.
  14. Query to calculate the average price of products in the products table based on buyPrice.
    SQL Basic and Intermediate Questions for Interview

  15. Fetch the top 3 most expensive products in the products table?

    SQL Basic and Intermediate Questions for Interview

  16. Rretrieve the customerName, orderNumber, and orderDate of all orders that have a status of 'Shipped'.
    SQL Basic and Intermediate Questions for Interview

  17. Display the total number of products sold for each productLine
    SQL Basic and Intermediate Questions for Interview

  18. Find employees who report directly to the employee with employeeNumber = 1143.
    SQL Basic and Intermediate Questions for Interview

  19. Query to calculate the total number of orders in the orders table, grouped by status.
    SQL Basic and Intermediate Questions for Interview

  20. List employees with their manager’s name.
    SQL Basic and Intermediate Questions for Interview


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
  • 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL String Types: Storage, Performance, and Best PracticesMySQL String Types: Storage, Performance, and Best PracticesMay 10, 2025 am 12:02 AM

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

Understanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreUnderstanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreMay 10, 2025 am 12:02 AM

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

What are the String Data Types in MySQL?What are the String Data Types in MySQL?May 10, 2025 am 12:01 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools