0% found this document useful (0 votes)
16 views22 pages

Database Nest Quiz

Uploaded by

l226451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views22 pages

Database Nest Quiz

Uploaded by

l226451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Database 122

Sure, let's dive into these SQL concepts in detail:

1. Group-By, Having, Order-By Clause

Group-By Clause

The GROUP BY clause in SQL is used to group rows that have the same values in specified
columns into aggregated data, such as a summary row. It is often used in conjunction with
aggregate functions (like COUNT(), SUM(), AVG(), MIN(), and MAX()).

Syntax:

sql
Copy code
SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1;

Example:

sql
Copy code
SELECT department, COUNT(*)
FROM employees
GROUP BY department;

This query groups employees by department and counts the number of employees in each
department.

Having Clause

The HAVING clause is used to filter groups created by the GROUP BY clause. It is similar to the
WHERE clause but is applied after the aggregation.

Syntax:

sql
Copy code
SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1
HAVING aggregate_function(column2) condition;

Example:
sql
Copy code
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;

This query returns departments that have more than 10 employees.

Order-By Clause

The ORDER BY clause is used to sort the result set by one or more columns, either in ascending
(ASC) or descending (DESC) order. By default, it sorts in ascending order.

Syntax:

sql
Copy code
SELECT column1, column2
FROM table
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];

Example:

sql
Copy code
SELECT employee_name, salary
FROM employees
ORDER BY salary DESC;

This query retrieves all employees and sorts them by salary in descending order.

2. Set Operations (Union, Intersect, etc.)

Set operations are used to combine the results of two or more queries. The main set operations
are UNION, INTERSECT, EXCEPT, and MINUS.

Union

UNION combines the results of two or more SELECT statements into a single result set. Duplicate
rows are removed by default.

Syntax:

sql
Copy code
SELECT column1, column2
FROM table1
UNION
SELECT column1, column2
FROM table2;

Example:

sql
Copy code
SELECT employee_name
FROM current_employees
UNION
SELECT former_employee_name
FROM former_employees;

This query returns a list of all employee names, both current and former, without duplicates.

Intersect

INTERSECT returns only the rows that are present in both result sets.

Syntax:

sql
Copy code
SELECT column1, column2
FROM table1
INTERSECT
SELECT column1, column2
FROM table2;

Example:

sql
Copy code
SELECT employee_name
FROM department1_employees
INTERSECT
SELECT employee_name
FROM department2_employees;

This query returns the names of employees who are in both departments.

Except / Minus

EXCEPT (or MINUS in some databases like Oracle) returns rows from the first result set that are not
present in the second result set.

Syntax:

sql
Copy code
SELECT column1, column2
FROM table1
EXCEPT
SELECT column1, column2
FROM table2;

Example:

sql
Copy code
SELECT employee_name
FROM all_employees
EXCEPT
SELECT employee_name
FROM terminated_employees;

This query returns names of all employees who are not in the list of terminated employees.

3. Substring Comparison

Substring comparison involves checking if a string contains another string. SQL provides
functions for substring operations, like SUBSTRING(), CHARINDEX(), and LIKE.

Syntax for SUBSTRING():

sql
Copy code
SUBSTRING(string_expression, start_position, length)

Example:

sql
Copy code
SELECT employee_name
FROM employees
WHERE SUBSTRING(employee_name, 1, 3) = 'Sam';

This query returns names of employees where the first three characters are 'Sam'.

Syntax for LIKE:

sql
Copy code
SELECT column
FROM table
WHERE column LIKE pattern;

Example:

sql
Copy code
SELECT employee_name
FROM employees
WHERE employee_name LIKE 'Sam%';

This query retrieves names of employees that start with 'Sam'.

4. Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value. Common
aggregate functions include:

 COUNT(): Counts the number of rows.

Example:

sql
Copy code
SELECT COUNT(*)
FROM employees;

 SUM(): Calculates the sum of a numeric column.

Example:

sql
Copy code
SELECT SUM(salary)
FROM employees;

 AVG(): Calculates the average value of a numeric column.

Example:

sql
Copy code
SELECT AVG(salary)
FROM employees;

 MIN(): Finds the minimum value in a column.

Example:

sql
Copy code
SELECT MIN(salary)
FROM employees;

 MAX(): Finds the maximum value in a column.

Example:
sql
Copy code
SELECT MAX(salary)
FROM employees;

5. Basic SQL Query Syntax

A basic SQL query retrieves data from one or more tables and can include various clauses to
refine the results.

Syntax:

sql
Copy code
SELECT column1, column2, ...
FROM table
WHERE condition
GROUP BY column
HAVING condition
ORDER BY column [ASC|DESC];

Example:

sql
Copy code
SELECT employee_name, salary
FROM employees
WHERE department = 'Sales'
GROUP BY employee_name
HAVING SUM(salary) > 50000
ORDER BY salary DESC;

This query retrieves names and salaries of employees in the Sales department, groups them,
filters those whose total salary is greater than 50,000, and orders the results by salary in
descending order.

Each of these components helps you craft sophisticated queries to extract and manipulate data
efficiently. If you have specific scenarios or further questions, feel free to ask!

Certainly! Here are some practice questions related to the SQL concepts of GROUP BY, HAVING,
ORDER BY, set operations, substring comparisons, aggregate functions, and basic SQL query
syntax:

1. Group-By, Having, Order-By Clause

Group-By Questions:

1. Group and Aggregate: Write a query to find the total number of orders placed by each
customer. Assume you have an orders table with columns customer_id and order_id.
sql
Copy code
SELECT customer_id, COUNT(order_id) AS total_orders
FROM orders
GROUP BY customer_id;

2. Group and Aggregate with Multiple Columns: Find the average salary for each
department. Assume you have an employees table with columns department_id and
salary.

sql
Copy code
SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;

Having Questions:

1. Filter Aggregated Results: Write a query to list all departments where the total number
of employees is more than 20. Assume you have an employees table with a
department_id column.

sql
Copy code
SELECT department_id, COUNT(*) AS num_employees
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 20;

2. Combined Aggregates and Filters: Find the departments with an average salary greater
than $60,000. Assume you have an employees table with columns department_id and
salary.

sql
Copy code
SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 60000;

Order-By Questions:

1. Simple Ordering: Retrieve a list of all employees sorted by their hire date in descending
order. Assume you have an employees table with a hire_date column.

sql
Copy code
SELECT employee_name, hire_date
FROM employees
ORDER BY hire_date DESC;
2. Multiple Columns Ordering: Get the top 10 highest-paid employees from each
department, sorted first by department and then by salary in descending order. Assume
you have an employees table with columns department_id and salary.

sql
Copy code
SELECT department_id, employee_name, salary
FROM employees
ORDER BY department_id, salary DESC;

2. Set Operations

Union Questions:

1. Combine Results: Write a query to combine all unique customer names from two
different customer tables (customers_us and customers_eu).

sql
Copy code
SELECT customer_name
FROM customers_us
UNION
SELECT customer_name
FROM customers_eu;

2. Combined with Additional Columns: Combine and retrieve customer names and email
addresses from two tables (current_customers and former_customers).

sql
Copy code
SELECT customer_name, email
FROM current_customers
UNION
SELECT customer_name, email
FROM former_customers;

Intersect Questions:

1. Common Entries: Find employees who are both managers and team leaders. Assume
you have two tables, managers and team_leaders, each with an employee_id.

sql
Copy code
SELECT employee_id
FROM managers
INTERSECT
SELECT employee_id
FROM team_leaders;
2. Common Products: Get a list of products that are both in stock and have been ordered.
Assume you have in_stock_products and ordered_products tables, each with a
product_id.

sql
Copy code
SELECT product_id
FROM in_stock_products
INTERSECT
SELECT product_id
FROM ordered_products;

Except/Minus Questions:

1. Find Missing Data: Find all products that are in the products table but not in the
discontinued_products table.

sql
Copy code
SELECT product_id
FROM products
EXCEPT
SELECT product_id
FROM discontinued_products;

2. Non-Matching Entries: Get a list of employees who have not attended any training
sessions. Assume you have an employees table and a training_attendance table.

sql
Copy code
SELECT employee_id
FROM employees
EXCEPT
SELECT employee_id
FROM training_attendance;

3. Substring Comparison

1. Basic Substring Search: Retrieve all employee names where the name contains 'Ann'.
Assume you have an employees table with an employee_name column.

sql
Copy code
SELECT employee_name
FROM employees
WHERE employee_name LIKE '%Ann%';

2. Starts With Substring: Find all products whose names start with 'Eco'. Assume you
have a products table with a product_name column.

sql
Copy code
SELECT product_name
FROM products
WHERE product_name LIKE 'Eco%';

3. Extract and Compare Substrings: Write a query to find employees whose phone
number starts with '555-'. Assume you have an employees table with a phone_number
column.

sql
Copy code
SELECT employee_name
FROM employees
WHERE SUBSTRING(phone_number, 1, 4) = '555-';

4. Aggregate Functions

1. Count Records: Write a query to count the number of orders placed in the last year.
Assume you have an orders table with an order_date column.

sql
Copy code
SELECT COUNT(*)
FROM orders
WHERE order_date >= DATEADD(year, -1, GETDATE());

2. Sum and Average: Calculate the total and average sales from a sales table with a
sale_amount column.

sql
Copy code
SELECT SUM(sale_amount) AS total_sales, AVG(sale_amount) AS
average_sales
FROM sales;

3. Minimum and Maximum Values: Find the highest and lowest salary in the employees
table.

sql
Copy code
SELECT MIN(salary) AS lowest_salary, MAX(salary) AS highest_salary
FROM employees;

5. Basic SQL Query Syntax

1. Select with Conditions: Retrieve all columns for employees who work in the 'Marketing'
department. Assume you have an employees table with a department column.

sql
Copy code
SELECT *
FROM employees
WHERE department = 'Marketing';

2. Join and Aggregate: Write a query to find the total number of orders and the average
order value for each customer. Assume you have customers and orders tables, with
customer_id and order_value.

sql
Copy code
SELECT c.customer_id, COUNT(o.order_id) AS total_orders,
AVG(o.order_value) AS average_order_value
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id;

3. Ordering with Limit: Retrieve the top 5 highest-paid employees. Assume you have an
employees table with a salary column.

sql
Copy code
SELECT employee_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;

Feel free to adjust the table names and columns to fit your specific database schema. If you need
further clarification or additional examples, just let me know

1. Group-By, Having, Order-By Clause

 GROUP BY: Groups rows that have the same values into summary rows. Often used
with aggregate functions.

sql
Copy code
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name;

 HAVING: Filters records after the GROUP BY clause has been applied, often used with
aggregate functions.

sql
Copy code
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 5;

 ORDER BY: Sorts the result set based on one or more columns. Can be ascending
(default) or descending.
sql
Copy code
SELECT column_name
FROM table_name
ORDER BY column_name ASC;

2. Set Operations

 UNION: Combines the results of two or more SELECT queries. Removes duplicate
rows.

sql
Copy code
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

 INTERSECT: Returns the common rows between two SELECT queries.

sql
Copy code
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;

 EXCEPT (or MINUS): Returns rows from the first query that are not in the second
query.

sql
Copy code
SELECT column_name FROM table1
EXCEPT
SELECT column_name FROM table2;

3. Substring Comparison

 SUBSTRING: Extracts a portion of a string.

sql
Copy code
SELECT SUBSTRING(column_name FROM start_position FOR length) AS
extracted_substring
FROM table_name;

 LIKE: Used for pattern matching with wildcards.

sql
Copy code
SELECT column_name
FROM table_name
WHERE column_name LIKE 'pattern%'; -- % represents zero or more
characters
4. Aggregate Functions

 COUNT: Returns the number of rows.

sql
Copy code
SELECT COUNT(*) FROM table_name;

 SUM: Returns the sum of values.

sql
Copy code
SELECT SUM(column_name) FROM table_name;

 AVG: Returns the average of values.

sql
Copy code
SELECT AVG(column_name) FROM table_name;

 MAX: Returns the maximum value.

sql
Copy code
SELECT MAX(column_name) FROM table_name;

 MIN: Returns the minimum value.

sql
Copy code
SELECT MIN(column_name) FROM table_name;

5. Basic SQL Query Syntax

 SELECT: Retrieves data from one or more tables.

sql
Copy code
SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1;

 INSERT: Adds new rows to a table.

sql
Copy code
INSERT INTO table_name (column1, column2)
VALUES (value1, value2);
 UPDATE: Modifies existing rows.

sql
Copy code
UPDATE table_name
SET column1 = value1
WHERE condition;

 DELETE: Removes rows from a table.

sql
Copy code
DELETE FROM table_name
WHERE condition;

Make sure to practice writing and executing these queries to get comfortable with the syntax and
functionality. Good luck with your quiz!

Here are some practice questions based on the syllabus for your SQL Quiz 2:

### 1. **Group By, Having, and Order By Clauses**


**Question 1:**
You have the following table `Sales`:

| SaleID | ProductName | SalesAmount | SaleDate | Region |


|--------|-------------|-------------|-----------|---------|
|1 | Laptop | 1000 | 2023-09-01| North |
|2 | Laptop | 1200 | 2023-09-02| South |
|3 | Smartphone | 800 | 2023-09-01| North |
|4 | Laptop | 1100 | 2023-09-02| East |
|5 | Smartphone | 900 | 2023-09-03| South |

- Write a query to find the total `SalesAmount` for each `ProductName` and filter only those
products that have total sales greater than 2000.
- Sort the results in descending order by the total `SalesAmount`.

```sql
SELECT ProductName, SUM(SalesAmount) AS TotalSales
FROM Sales
GROUP BY ProductName
HAVING SUM(SalesAmount) > 2000
ORDER BY TotalSales DESC;
```

---

### 2. **Set Operations (Union, Intersect, etc.)**


**Question 2:**
You have two tables `NorthCustomers` and `SouthCustomers`:

- **NorthCustomers**:

| CustomerID | CustomerName | City |


|------------|--------------|----------|
|1 | Alice | New York |
|2 | Bob | Boston |
|3 | Charlie | Chicago |

- **SouthCustomers**:

| CustomerID | CustomerName | City |


|------------|--------------|----------|
|1 | David | Miami |
|2 | Eve | Atlanta |
|3 | Charlie | Dallas |

- Write a query to find customers who are present in both the `NorthCustomers` and
`SouthCustomers` tables.

```sql
SELECT CustomerName
FROM NorthCustomers
INTERSECT
SELECT CustomerName
FROM SouthCustomers;
```

- Write a query to find all unique customers from both regions.

```sql
SELECT CustomerName
FROM NorthCustomers
UNION
SELECT CustomerName
FROM SouthCustomers;
```

---

### 3. **Substring Comparison**


**Question 3:**
You have the following table `Employees`:

| EmployeeID | EmployeeName | Department |


|------------|--------------|------------|
|1 | Sarah Jones | IT |
|2 | Tom Brown | HR |
|3 | Emily White | Finance |
|4 | John Smith | IT |
|5 | Jane Smith | HR |

- Write a query to find all employees whose last name is "Smith" (hint: use the `SUBSTRING`
function).

```sql
SELECT EmployeeName
FROM Employees
WHERE SUBSTRING(EmployeeName, CHARINDEX(' ', EmployeeName) + 1,
LEN(EmployeeName)) = 'Smith';
```

---

### 4. **Aggregate Functions**


**Question 4:**
You have the table `Orders`:

| OrderID | CustomerID | OrderAmount | OrderDate |


|---------|------------|-------------|------------|
|1 | 101 | 500 | 2023-09-01 |
|2 | 102 | 1000 | 2023-09-02 |
|3 | 103 | 1500 | 2023-09-03 |
|4 | 101 | 2000 | 2023-09-04 |
|5 | 102 | 2500 | 2023-09-05 |

- Write a query to find the average order amount for each customer.

```sql
SELECT CustomerID, AVG(OrderAmount) AS AverageOrderAmount
FROM Orders
GROUP BY CustomerID;
```

---

### 5. **Basic SQL Query Syntax**


**Question 5:**
Given the `Products` table:

| ProductID | ProductName | Price | Stock |


|-----------|-------------|-------|-------|
|1 | Laptop | 1000 | 50 |
|2 | Smartphone | 800 | 100 |
|3 | Tablet | 600 | 200 |

- Write a query to retrieve all product names and their prices where the stock is greater than 50,
ordered by price in ascending order.

```sql
SELECT ProductName, Price
FROM Products
WHERE Stock > 50
ORDER BY Price ASC;
```

---

These questions cover various SQL topics from your syllabus and will help you practice for your
quiz!

Here are more SQL practice questions to help you prepare for your quiz:

---

### 6. **Group By, Having, and Order By Clauses**


**Question 6:**
You have the following table `Employees`:

| EmployeeID | EmployeeName | Department | Salary |


|------------|--------------|------------|---------|
|1 | John Doe | IT | 5000 |
|2 | Jane Smith | HR | 4500 |
|3 | Mark Johnson | IT | 6000 |
|4 | Lucy Brown | Finance | 7000 |
|5 | David Clark | HR | 4000 |

- Write a query to get the average salary for each department, but only display departments with
an average salary greater than 4500.
- Sort the results by average salary in descending order.

```sql
SELECT Department, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 4500
ORDER BY AverageSalary DESC;
```

---

### 7. **Set Operations (Union, Intersect, etc.)**


**Question 7:**
You have two tables `OnlineOrders` and `InStoreOrders`:

- **OnlineOrders**:

| OrderID | CustomerID | OrderAmount |


|---------|------------|-------------|
|1 | 101 | 1000 |
|2 | 102 | 1500 |
|3 | 103 | 2000 |

- **InStoreOrders**:

| OrderID | CustomerID | OrderAmount |


|---------|------------|-------------|
|4 | 101 | 3000 |
|5 | 104 | 2500 |
|6 | 105 | 4000 |

- Write a query to find customers who made orders both online and in-store.

```sql
SELECT CustomerID
FROM OnlineOrders
INTERSECT
SELECT CustomerID
FROM InStoreOrders;
```

- Write a query to find customers who made orders either online or in-store but not both.

```sql
SELECT CustomerID
FROM OnlineOrders
EXCEPT
SELECT CustomerID
FROM InStoreOrders
UNION
SELECT CustomerID
FROM InStoreOrders
EXCEPT
SELECT CustomerID
FROM OnlineOrders;
```

---

### 8. **Substring Comparison**


**Question 8:**
You have the following table `Books`:

| BookID | Title | Author |


|--------|-----------------------|-------------------|
|1 | Introduction to SQL | John Carter |
|2 | Advanced SQL Techniques| Jane Austen |
|3 | Learning SQL for Beginners | John Smith |
|4 | SQL Mastery | Emily Johnson |

- Write a query to find all books with "SQL" in their title.

```sql
SELECT Title
FROM Books
WHERE Title LIKE '%SQL%';
```

- Write a query to find all books written by authors whose first name is "John."

```sql
SELECT Title
FROM Books
WHERE SUBSTRING(Author, 1, CHARINDEX(' ', Author) - 1) = 'John';
```

---

### 9. **Aggregate Functions**


**Question 9:**
You have the following table `Orders`:

| OrderID | ProductID | Quantity | PricePerUnit | OrderDate |


|---------|-----------|----------|--------------|------------|
|1 | 101 | 10 | 50 | 2024-09-01 |
|2 | 102 |5 | 100 | 2024-09-02 |
|3 | 101 | 20 | 50 | 2024-09-03 |
|4 | 103 | 15 | 200 | 2024-09-04 |
|5 | 101 | 10 | 50 | 2024-09-05 |

- Write a query to calculate the total revenue (Quantity \* PricePerUnit) for each `ProductID`.

```sql
SELECT ProductID, SUM(Quantity * PricePerUnit) AS TotalRevenue
FROM Orders
GROUP BY ProductID;
```

- Write a query to find the average quantity ordered for each product.

```sql
SELECT ProductID, AVG(Quantity) AS AverageQuantity
FROM Orders
GROUP BY ProductID;
```

---

### 10. **Basic SQL Query Syntax**


**Question 10:**
You have the following table `Customers`:

| CustomerID | FirstName | LastName | City |


|------------|-----------|----------|------------|
|1 | Sarah | Johnson | New York |
|2 | Michael | Brown | Chicago |
|3 | Emily | Davis | San Francisco |
|4 | John | Williams | Los Angeles|

- Write a query to display all customers from cities that contain the word "New."

```sql
SELECT *
FROM Customers
WHERE City LIKE '%New%';
```

- Write a query to retrieve customers' full names (FirstName + ' ' + LastName) and sort them in
alphabetical order.

```sql
SELECT FirstName + ' ' + LastName AS FullName
FROM Customers
ORDER BY FullName ASC;
```

---

### 11. **Group By with Aggregate Functions**


**Question 11:**
You have the table `Sales`:

| SaleID | ProductID | Quantity | SaleAmount | SaleDate |


|--------|-----------|----------|------------|-----------|
|1 | 101 | 10 | 500 | 2024-09-01|
|2 | 102 |5 | 250 | 2024-09-02|
|3 | 101 | 20 | 1000 | 2024-09-03|
|4 | 103 | 15 | 750 | 2024-09-04|
|5 | 101 | 10 | 500 | 2024-09-05|

- Write a query to find the total quantity and total sale amount for each `ProductID`, but only
display products with a total quantity greater than 25.

```sql
SELECT ProductID, SUM(Quantity) AS TotalQuantity, SUM(SaleAmount) AS
TotalSaleAmount
FROM Sales
GROUP BY ProductID
HAVING SUM(Quantity) > 25;
```

---

### 12. **Aggregate Functions with Order By**


**Question 12:**
You have the table `Departments`:

| DepartmentID | DepartmentName | Budget |


|--------------|----------------|---------|
|1 | IT | 50000 |
|2 | HR | 30000 |
|3 | Finance | 40000 |
|4 | Sales | 60000 |

- Write a query to calculate the total budget for all departments and order the results in
descending order by department name.

```sql
SELECT DepartmentName, Budget
FROM Departments
ORDER BY DepartmentName DESC;
```

---

These additional questions should give you more practice across all the topics, preparing you for
your quiz!

Key Differences

1. Functionality:
o GROUP BY is used to arrange rows into groups based on one or more columns.
o HAVING is used to filter these groups based on aggregate values.
2. Application:
o GROUP BY is applied before aggregation.
o HAVING is applied after aggregation.
3. Syntax Location:
o GROUP BY is used in the query to group data.
o HAVING follows GROUP BY and is used to filter the result of the aggregation.

In summary, you use GROUP BY to create groups of data and HAVING to filter the results of these

You might also like