KnowledgeBoat Logo
OPEN IN APP

Chapter 15

Grouping Records, Joins in SQL

Class 12 - Computer Science with Python Sumita Arora



Multiple Choice Questions

Question 1

A ............... is a query that retrieves rows from more than one table or view:

  1. Start
  2. End
  3. Join
  4. All of these

Answer

Join

Reason — A join is a query that combines rows from two or more tables or views. In a join-query, more than one table are listed in FROM clause.

Question 2

The HAVING clause does which of the following ?

  1. Acts EXACTLY like a WHERE clause.
  2. Acts like a WHERE clause but is used for columns rather than groups.
  3. Acts like a WHERE clause but is used for groups rather than rows.
  4. Acts like a WHERE clause but is used for rows rather than columns.

Answer

Acts like a WHERE clause but is used for groups rather than rows.

Reason — The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows.

Question 3

Aggregate functions can be used in the select list or the ............... clause of a select statement. They cannot be used in a ............... clause.

  1. Where, having
  2. Having, where
  3. Group by, having
  4. Group by, where

Answer

Having, where

Reason — Aggregate functions can be used in the select list or the HAVING clause of a select statement. But they cannot be used in a WHERE clause. The reason for this is that the WHERE clause filters rows before any grouping or aggregation occurs, while HAVING clause applies conditions to groups after the data has been grouped using the GROUP BY clause.

Question 4

SQL applies conditions on the groups through ............... clause after groups have been formed.

  1. Group by
  2. With
  3. Where
  4. Having

Answer

Having

Reason — The HAVING clause applies conditions to groups after the data has been grouped using the GROUP BY clause in SQL queries.

Question 5

Which clause is used with "aggregate functions" ?

  1. GROUP BY
  2. SELECT
  3. WHERE
  4. Both (1) and (3)

Answer

GROUP BY, SELECT

Reason — Aggregate functions are used with the GROUP BY clause to perform calculations on groups of rows. However, they are also used in the SELECT clause to display the results of aggregate calculations.

Question 6

What is the meaning of "HAVING" clause in SELECT query ?

  1. To filter out the summary groups
  2. To filter out the column groups
  3. To filter out the row and column values
  4. None of the mentioned

Answer

To filter out the summary groups

Reason — The HAVING clause is used to filter out summary groups in a SELECT query that involves aggregate functions and the GROUP BY clause.

Question 7

Where and Having clauses can be used interchangeably in SELECT queries ?

  1. True
  2. False
  3. Only in views
  4. With order by

Answer

False

Reason — The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can include aggregate functions. Hence, WHERE and HAVING clauses cannot be used interchangeably in SELECT queries.

Question 8

The operation whose result contains all pairs of tuples from the two relations, regardless of whether their attribute values match.

  1. Join
  2. Cartesian product
  3. Intersection
  4. Set difference

Answer

Cartesian product

Reason — In an unrestricted join or Cartesian product of two relations, all possible combinations are formed by pairing each row from the first table with every row from the second table, regardless of whether their attribute values match. This operation returns n1 * n2 rows, where n1 is the number of rows in the first table, and n2 is the number of rows in the second table.

Question 9

Which SQL function is used to count the number of rows in a SQL query ?

  1. COUNT()
  2. NUMBER()
  3. SUM()
  4. COUNT(*)

Answer

COUNT(*)

Reason — The SQL function COUNT(*) is used to count the number of rows in an SQL query, including duplicates and rows with NULL values.

Question 10

Which of the following is not an aggregate function ?

  1. Avg
  2. Sum
  3. With
  4. Min

Answer

With

Reason — Aggregate functions in SQL include AVG, COUNT, MAX, MIN, and SUM.

Question 11

All aggregate functions except ............... ignore null values in their input collection.

  1. Count(attribute)
  2. Count(*)
  3. Avg
  4. Sum

Answer

Count(*)

Reason — All aggregate functions, except for COUNT(*), ignore null values in their input collection. COUNT(*) returns all rows, including duplicates and nulls.

Question 12

Which of the following is a SQL aggregate function ?

  1. LEFT
  2. AVG
  3. JOIN
  4. LEN

Answer

AVG

Reason — Aggregate functions in SQL include AVG, COUNT, MAX, MIN, and SUM.

Question 13

Which of the following group functions ignore NULL values ?

  1. MAX
  2. COUNT
  3. SUM
  4. All of the above

Answer

All of the above

Reason — All aggregate functions, except for COUNT(*), ignore null values in their input collection.

Question 14

The functions which work with individual rows' data are called ............... function.

  1. Single row
  2. Multiple rows
  3. Aggregate
  4. None of these

Answer

Single row

Reason — Single-row functions in SQL work with one row at a time and return a result for every row of a queried table.

Question 15

Function count() is a/an ............... function.

  1. Single row
  2. Multiple rows
  3. Aggregate
  4. None of these

Answer

Aggregate

Reason — The COUNT() function is an aggregate function in SQL.

Question 16

The sum(), if used in a condition, is used with ............... clause.

  1. Group by
  2. With
  3. Where
  4. Having

Answer

Having

Reason — When using the SUM() function in a condition, it is used with the HAVING clause. The HAVING clause is used to apply conditions to groups of rows after the GROUP BY operation has been performed, making it suitable for conditions involving aggregate functions like SUM().

Question 17

Which clause cannot be used with "aggregate functions" ?

  1. GROUP BY
  2. SELECT
  3. WHERE
  4. Both (1) and (3)

Answer

WHERE

Reason — Aggregate functions cannot be used with the WHERE clause in SQL because the WHERE clause filters rows before any grouping or aggregation occurs.

Question 18

What is the meaning of "WHERE" clause in a GROUP BY query ?

  1. To filter out the summary groups
  2. To filter out the column groups
  3. To filter out the row and column values before creating groups
  4. None of the mentioned

Answer

To filter out the row and column values before creating groups

Reason — The WHERE clause is used to filter rows and columns values before any grouping occurs in a query with a GROUP BY clause.

Question 19

The following SQL is which type of join :

SELECT CUSTOMER.CUST_ID, ORDER.CUST_ID, NAME, ORDER_ID 
FROM CUSTOMER, ORDER
WHERE CUSTOMER.CUST_ID = ORDER.CUST_ID?
  1. Equi-join
  2. Natural join
  3. Outer join
  4. Cartesian product

Answer

Equi-join

Reason — An equi-join is a type of join where columns from two or more tables are compared for equality using the "=" operator. In the given SQL query, the WHERE clause specifies the condition CUSTOMER.CUST_ID = ORDER.CUST_ID, which compares the CUST_ID column from the CUSTOMER table with the CUST_ID column from the ORDER table. Therefore, it is an equi-join.

Question 20

The following SQL is which type of join :

SELECT CUSTOMER.CUST_ID, ORDER.CUST_ID, NAME, ORDER_ID
FROM CUSTOMER, ORDER
  1. Equi-join
  2. Natural join
  3. Outer join
  4. Cartesian product

Answer

Cartesian product

Reason — This query uses a comma-separated list of table names in the FROM clause without specifying any join condition. In SQL, when we list multiple tables in the FROM clause separated by commas without specifying a join condition, it results in a Cartesian product.

Question 21

Which product is returned in a join query have no join condition ?

  1. Equijoins
  2. Cartesian product
  3. Both (1) and (2)
  4. None of the mentioned

Answer

Cartesian product

Reason — When a join query has no join condition specified, it results in a Cartesian product. This means that every row from the first table is combined with every row from the second table.

Question 22

Which is a join condition contains an equality operator ?

  1. Equijoins
  2. Cartesian product
  3. Both (1) and (2)
  4. None of the mentioned

Answer

Equijoins

Reason — An equi-join is a type of join where columns from two or more tables are compared for equality using the "=" operator.

Fill in the Blanks

Question 1

To specify condition with a GROUP BY clause, HAVING clause is used.

Question 2

Only aggregate functions are used with GROUP BY.

Question 3

A JOIN is a means for combining fields from two tables by using values common to each.

Question 4

The equi join uses = operator in the join condition.

Question 5

Natural join joins two tables on the basis of a common field.

Question 6

The SQL built-in function SUM totals values in numeric columns.

Question 7

The SQL built-in function AVG computes the average of values in numeric columns.

Question 8

The SQL built-in function MAX obtains the largest value in a numeric column.

Question 9

The SQL built-in function MIN obtains the smallest value in a numeric column.

Question 10

The SQL built-in function COUNT computes the number of rows in a table.

Question 11

The SELECT clause GROUP BY is used to collect those rows that have the same value in a specified column.

Question 12

To compare an aggregate value in a condition, HAVING clause is used.

Question 13

To create a summary of records based on the common value in a field in different rows of the table GROUP BY clause is used.

Question 14

To get data from two or more tables having some common fields, join query is created.

Question 15

In equi-join, the join condition joins the two table using = operator.

True/False Questions

Question 1

The HAVING clause acts like a WHERE clause, but it identifies groups that meet a criterion, rather than rows.

Answer

True

Reason — The HAVING clause in SQL is used to filter groups based on specified conditions, while the WHERE clause filters individual rows. This means that the HAVING clause works with grouped data, applying conditions to groups that meet certain criteria, whereas the WHERE clause applies conditions to individual rows before any grouping occurs.

Question 2

Data manipulation language (DML) commands are used to define a database, including creating, altering, and dropping tables and establishing constraints.

Answer

False

Reason — Data Definition Language (DDL) commands are used to define a database, including creating, altering, and dropping tables and establishing constraints.

Question 3

The SQL keyword GROUP BY instructs the DBMS to group together those rows that have the same value in a column.

Answer

True

Reason — The SQL keyword GROUP BY clause instructs the DBMS to combine all those rows that have identical values in a particular column or a group of columns.

Question 4

Equi join can use any operator for joining two tables.

Answer

False

Reason — An equi-join is a type of join where columns from two or more tables are compared for equality using the "=" operator.

Question 5

Missing join condition in join query produces cartesian product.

Answer

True

Reason — When a join query has no join condition specified, it results in a Cartesian product. This means that every row from the first table is combined with every row from the second table.

Question 6

COUNT(field_name) tallies only those rows that contain a value; it ignores all null values.

Answer

True

Reason — When we use COUNT(field_name), it counts only the rows where the specified field (field_name) is not null. It does ignore null values for that specific field during counting.

Question 7

SUM, AVG, MIN, and MAX can only be used with numeric columns.

Answer

True

Reason — The aggregate functions SUM, AVG, MIN, and MAX are designed to work with numeric columns in SQL. They expect numeric values as arguments and return numeric results.

Question 8

The SQL keyword GROUP BY instructs the DBMS to group together those rows that have the same value in a column.

Answer

True

Reason — The SQL keyword GROUP BY instructs the DBMS to combine all those rows that have identical values in a particular column or a group of columns.

Question 9

The HAVING and WHERE clauses are interchangeable.

Answer

False

Reason — The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can include aggregate functions. Hence, WHERE and HAVING clauses cannot be used interchangeably in queries.

Question 10

The HAVING clauses can take any valid SQL function in its condition.

Answer

False

Reason — The HAVING clause can contain either a simple boolean expression (i.e., an expression or condition that results into true or false) or use aggregate function in the having condition.

Question 11

HAVING clause can only be used if the SELECT query has GROUP BY clause.

Answer

True

Reason — The HAVING clause in SQL works with grouped data, applying conditions to groups that meet certain criteria. Therefore, HAVING clause can only be used if the SELECT query has GROUP BY clause.

Question 12

With GROUP BY, the select-list of the SELECT statement can only take the group-field and/or aggregate function.

Answer

True

Reason — When using the GROUP BY clause in SQL, the select-list of the SELECT statement can only include the grouping columns (group-fields) and/or aggregate functions. MySQL would not produce any error even if we include a non-group field in the select-list. However, it will return the value from first record of the group for that non-group field.

Question 13

A join query without the join condition produces a cartesian product.

Answer

True

Reason — When a join query has no join condition specified, it results in a Cartesian product. This means that every row from the first table is combined with every row from the second table.

Question 14

You can specify any type of condition, using any comparison operator in an equi-join.

Answer

False

Reason — An equi-join is a type of join where columns from two or more tables are compared for equality using the "=" operator.

Question 15

Join can only be created from two tables.

Answer

False

Reason — A join in SQL is a query that combines rows from two or more tables.

Assertions and Reasons

Question 1

Assertion. SQL SELECT's GROUP BY clause is used to divide the result in groups.

Reason. The GROUP BY clause combines all those records that have identical values in a particular field or in group by fields.

Answer

(a)

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.

Explanation
The GROUP BY clause combines all those records that have identical values in a particular field or a group of fields. This clause is utilised in SELECT statements to divide the result set into groups based on the values in the specified columns. Grouping can be done by a column name, or with aggregate functions in which case the aggregate produces a value for each group.

Question 2

Assertion. A GROUP BY query can also include functions.

Reason. ALL SQL functions can be used in a GROUP BY query.

Answer

(c)

Assertion is true but Reason is false.

Explanation
A GROUP BY query can include functions. This is true because SQL allows the use of aggregate functions like COUNT(), SUM(), etc., within a GROUP BY query to perform calculations on grouped data. However, it's important to note that not all SQL functions can be used within a GROUP BY query. Only aggregate functions or functions that operate on grouped data can be used effectively in this context.

Question 3

Assertion. SQL SELECT query can also fetch rows from multiple tables.

Reason. A join is a query that combines rows from two or more tables.

Answer

(a)

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.

Explanation
SQL SELECT queries can fetch rows from multiple tables using JOIN operations. This allows retrieving data from related tables simultaneously in a single query. A join in SQL is a query that combines rows from two or more tables based on a specified condition, such as matching values in a common column.

Question 4

Assertion. Generally, a join query combines rows from multiple tables having some common column(s) and a joining condition, but not always.

Reason. A Cartesian product is an unrestricted join where all possible combinations of rows from multiple tables are created without any condition on them.

Answer

(a)

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.

Explanation
In SQL, a join is a query that combines rows from two or more tables based on a specified condition, such as matching values in a common column. However, this matching condition is not always required; for instance, a Cartesian product is an unrestricted join where all possible combinations of rows from multiple tables are generated without any specific condition. This means that every row from one table is combined with every row from another table.

Question 5

Assertion. The join, in which columns are compared for equality, is called Equi-join.

Reason. The join queries only produce combined rows from tables having some common column, when compared for equality.

Answer

(c)

Assertion is true but Reason is false.

Explanation
The join, in which columns are compared for equality, is called Equi-join. Join queries in SQL can produce combined rows based on various conditions, not just equality comparisons. For example, join conditions can involve inequality comparisons (<, >, <=, >=), as well as other logical operators and functions.

Question 6

Assertion. In the result produced by a join query, there may be multiple identical columns in the final result, but not always.

Reason. The join in which only one of the identical columns (coming from the joined tables) exists, is called a Natural join.

Answer

(a)

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.

Explanation
In the result produced by a join query, there may be multiple identical columns in the final result, but this is not always the case. Depending on the type of join and the columns involved, duplicate columns may or may not appear in the result set. A Natural join is a type of join in SQL where only one of the identical columns (coming from the joined tables) exists in the final result.

Question 7

Assertion. In order to carry out the join operation, there should be a governing condition.

Reason. A join condition may be based on equality, less than, greater than or non-equality.

Answer

(d)

Assertion is false but Reason is true.

Explanation
In order to carry out the join operation, there should be a governing condition is false. This is because a Cartesian join is an example of a join operation that does not require a specific condition; it combines all rows from one table with all rows from another table without any matching condition. A join condition may be based on equality, less than, greater than, or non-equality depending on the requirements of the query.

Type A: Short Answer Questions/Conceptual Questions

Question 1

What is the difference between HAVING and WHERE clause ?

Answer

HAVING clauseWHERE clause
HAVING conditions are applicable to groups formed by GROUP BY clause.WHERE conditions are applicable to individual rows.
HAVING conditions can include aggregate functions.WHERE conditions cannot include aggregate functions.
It allows conditions to be applied to grouped data.It filters rows based on specified conditions.

Question 2

What is the use of GROUP BY clause ?

Answer

The GROUP BY clause in SQL is used to combine all records that have identical values in a particular field or group of fields. This grouping results in one summary record per group if group functions, such as aggregate functions, are used with it.

Question 3

What are aggregate functions? What is their use? Give some examples.

Answer

Aggregate functions in SQL work with data from multiple rows at a time and return a single aggregated value. They are used to perform calculations across multiple rows and return a summary result for that group.

Examples of aggregate functions include SUM(), COUNT(), MAX(), MIN(), AVG() etc.

Question 4

What type of functions can you use with GROUP BY and HAVING clauses ?

Answer

Aggregate functions are used with the GROUP BY and HAVING clauses to apply conditions on grouped data.

Question 5

What is sql join ? How is it useful ?

Answer

A SQL join is a query that combines rows from two or more tables. Join allows retrieving data from related tables simultaneously in a single query. Joins enable the combination of data from different tables to obtain a comprehensive view of the information.

Question 6

What are most common types of SQL joins ?

Answer

The most common types of SQL joins are as follows :

  1. Equi-Join
  2. Non-Equi-Join
  3. Natural join

Type B: Application Based Questions

Question 1

Table BOOK_INFORMATION

Column Name
BOOK_ID
BOOK_TITLE
PRICE

Which SQL statement allows you to find the highest price from the table BOOK_INFORMATION?

  1. SELECT BOOK_ID, BOOK_TITLE, MAX(PRICE) FROM BOOK_INFORMATION;
  2. SELECT MAX(PRICE) FROM BOOK_INFORMATION;
  3. SELECT MAXIMUM(PRICE) FROM BOOK_INFORMATION;
  4. SELECT PRICE FROM BOOK_INFORMATION ORDER BY PRICE DESC;

Answer

SELECT MAX(PRICE) FROM BOOK_INFORMATION;
Explanation
  1. SELECT BOOK_ID, BOOK_TITLE, MAX(PRICE) FROM BOOK_INFORMATION; — This query selects the BOOK_ID, BOOK_TITLE, and maximum PRICE from the BOOK_INFORMATION table. However, the requirement is to find the highest price only.
  2. SELECT MAX(PRICE) FROM BOOK_INFORMATION; — This query selects the maximum PRICE from the BOOK_INFORMATION table using the MAX() aggregate function. This option is correct because it directly retrieves the highest price among all the books listed in the BOOK_INFORMATION table, which is what the question asks for.
  3. SELECT MAXIMUM(PRICE) FROM BOOK_INFORMATION; — There is no MAXIMUM() function in SQL.
  4. SELECT PRICE FROM BOOK_INFORMATION ORDER BY PRICE DESC; — This query selects all prices from the BOOK_INFORMATION table and orders them in descending order using ORDER BY PRICE DESC but it doesn't directly give the highest price.

Question 2

Table SALES

Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT

Which SQL statement lets you find the sales amount for each store?

  1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES;
  2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES ORDER BY STORE_ID;
  3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID;
  4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES HAVING UNIQUE STORE_ID;

Answer

SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID;
Explanation
  1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES; — This statement selects the store_ID and calculates the total sales amount using SUM() aggregate function from the SALES table. It does not group the results by store ID, so it will return a single row with the total sales amount across all stores.
  2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES ORDER BY STORE_ID; — This statement selects the store_ID and calculates the total sales amount using SUM() aggregate function from the SALES table and uses an ORDER BY clause to sort the results by store ID. However, it still doesn't group the results by store_ID.
  3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID; — This statement selects the store_ID and calculates the total sales amount using SUM() aggregate function from the SALES table and uses the GROUP BY clause to group the results by store ID. It calculates the total sales amount for each store ID separately. As a result, it calculates the total sales amount for each unique store ID separately, providing a breakdown of sales amounts for each store in the dataset.
  4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES HAVING UNIQUE STORE_ID; — This statement is incorrect because the HAVING clause is used for filtering grouped data based on a condition, not for identifying unique values. Also, "UNIQUE STORE_ID" is not a valid condition in SQL.

Question 3

Table SALES

Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT

Which SQL statement lets you list all stores whose total sales amount is over 5000 ?

  1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING SUM(SALES_AMOUNT) > 5000;
  2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING SALES_AMOUNT > 5000;
  3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
    WHERE SUM(SALES_AMOUNT) > 5000 GROUP BY STORE_ID;
  4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
    WHERE SALES_AMOUNT > 5000 GROUP BY STORE_ID;

Answer

SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
GROUP BY STORE_ID HAVING SUM(SALES_AMOUNT) > 5000;
Explanation
  1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING SUM(SALES_AMOUNT) > 5000; — This statement selects the store ID and calculates the total sales amount for each store using the SUM() aggregate function. The GROUP BY STORE_ID clause ensures that the results are grouped by store ID. The HAVING SUM(SALES_AMOUNT) > 5000 condition then filters the grouped data, selecting only those stores whose total sales amount is over 5000.
  2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING SALES_AMOUNT > 5000; — This option is incorrect because the HAVING clause cannot directly reference SALES_AMOUNT without an aggregate function like SUM() since SUM(SALES_AMOUNT) is used in the SELECT statement.
  3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE SUM(SALES_AMOUNT) > 5000 GROUP BY STORE_ID; — This option is incorrect because aggregate functions like SUM(SALES_AMOUNT) cannot be used directly in the WHERE clause. The WHERE clause is used for filtering individual rows before grouping.
  4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE SALES_AMOUNT > 5000 GROUP BY STORE_ID; — This option is incorrect because it tries to filter individual sales amounts (SALES_AMOUNT) directly without using the SUM() aggregate function to calculate the total sales amount for each store. The GROUP BY STORE_ID clause is used for grouping after the filtering, which is not the correct approach for filtering based on the total sales amount.

Question 4

Table SALES

Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT

Which SQL statement lets you find the total number of stores in the SALES table?

  1. SELECT COUNT(STORE_ID) FROM SALES;
  2. SELECT COUNT(DISTINCT STORE_ID) FROM SALES;
  3. SELECT DISTINCT STORE_ID FROM SALES;
  4. SELECT COUNT(STORE_ID) FROM SALES GROUP BY STORE_ID;

Answer

SELECT COUNT(DISTINCT STORE_ID) FROM SALES;
Explanation
  1. SELECT COUNT(STORE_ID) FROM SALES; — This query uses the COUNT() aggregate function with the STORE_ID column in the SELECT statement. It counts the number of non-null values in the STORE_ID column, and this count includes duplicates.
  2. SELECT COUNT(DISTINCT STORE_ID) FROM SALES; — This option uses COUNT(DISTINCT STORE_ID) to count the number of unique store IDs in the SALES table. The DISTINCT keyword ensures that only distinct (unique) values are counted, avoiding overcounting due to duplicates.
  3. SELECT DISTINCT STORE_ID FROM SALES; — This option selects distinct (unique) store IDs from the SALES table but does not count or provide the total number of stores.
  4. SELECT COUNT(STORE_ID) FROM SALES GROUP BY STORE_ID; — This option attempts to count the number of occurrences of each store ID by using COUNT(STORE_ID) and grouping by store ID with GROUP BY STORE_ID. However, this results in a count for each unique store ID separately, not the total number of stores in the table.

Question 5

Table SALES

Column Name
STORE_ID
SALES_DATE
SALES_AMOUNT

Which SQL statement allows you to find the total sales amount for Store ID 25 and the total sales amount for Store ID 45?

  1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
    WHERE STORE_ID IN (25, 45) GROUP BY STORE_ID;
  2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
    GROUP BY STORE_ID HAVING STORE_ID IN (25, 45);
  3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID IN (25, 45);
  4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
    WHERE STORE_ID = 25 AND STORE_ID = 45 GROUP BY STORE_ID;

Answer

SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES   
WHERE STORE_ID IN (25, 45) GROUP BY STORE_ID;
Explanation
  1. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID IN (25, 45) GROUP BY STORE_ID; — This query uses the IN operator to filter rows where the STORE_ID is either 25 or 45. It then calculates the total sales amount for each store ID using SUM(SALES_AMOUNT) and groups the results by STORE_ID. This query correctly finds the total sales amount for Store ID 25 and Store ID 45 separately.
  2. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES GROUP BY STORE_ID HAVING STORE_ID IN (25, 45); — This query will also give the required output but it is inefficient because it first retrieves all rows from the "SALES" table, then groups the results by store ID, and finally filters the result set to include only store IDs 25 and 45. The inefficiency arises from the fact that it processes all rows in the "SALES" table before filtering out the unnecessary data. This means that it processes more data than necessary, which can be wasteful in terms of computational resources and time. A more efficient approach would be to select only the rows having store IDs 25 and 45 first (using WHERE clause), and then perform the aggregation.
  3. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID IN (25, 45); — This query filters rows where the STORE_ID is either 25 or 45 and calculates the total sales amount for these store IDs using SUM(SALES_AMOUNT). However, it doesn't include a GROUP BY clause, so it would return a single row with the total sales amount for both Store ID 25 and Store ID 45 combined.
  4. SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES WHERE STORE_ID = 25 AND STORE_ID = 45 GROUP BY STORE_ID; — This query filter rows where the STORE_ID is both 25 and 45 simultaneously using STORE_ID = 25 AND STORE_ID = 45. However, this condition is impossible to satisfy because a single value cannot be both 25 and 45 at the same time. Therefore, this query would not return any results.

Question 6

Table EXAM_RESULTS

STU IDFNAMELNAMEEXAM IDEXAM_SCORE
10LAURALYNCH190
10LAURALYNCH285
11GRACEBROWN178
11GRACEBROWN272
12JAYJACKSON195
12JAYJACKSON292
13WILLIAMBISHOP170
13WILLIAMBISHOP2100
14CHARLESPRADA285

What SQL statement do we use to find the average exam score for EXAM_ID = 1?

  1. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS;
  2. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID WHERE EXAM_ID = 1;
  3. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING EXAM_ID = 1;
  4. SELECT COUNT(EXAM_SCORE) FROM EXAM_RESULTS WHERE EXAM_ID = 1;

Answer

SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING EXAM_ID = 1;
Output
+-----------------+
| AVG(EXAM_SCORE) |
+-----------------+
|         83.2500 |
+-----------------+
Explanation
  1. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS; — This statement calculates the average exam score across all exam IDs in the EXAM_RESULTS table.
  2. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID WHERE EXAM_ID = 1; — This statement is incorrect because the WHERE clause should come before the GROUP BY clause. Additionally, grouping by EXAM_ID and then trying to filter by EXAM_ID = 1 within the GROUP BY clause will result in an error because grouping should be done before filtering.
  3. SELECT AVG(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING EXAM_ID = 1; — This query groups the exam results by EXAM_ID and then calculates the average exam score for each group. The HAVING clause filters the groups and returns only those where the EXAM_ID is equal to 1, giving us the average exam score for the exam with EXAM_ID equal to 1.
  4. SELECT COUNT(EXAM_SCORE) FROM EXAM_RESULTS WHERE EXAM_ID = 1; — This statement calculates the count of exam scores for EXAM_ID = 1, but it doesn't calculate the average score.

Question 7

Table EXAM_RESULTS

STU IDFNAMELNAMEEXAM IDEXAM_SCORE
10LAURALYNCH190
10LAURALYNCH285
11GRACEBROWN178
11GRACEBROWN272
12JAYJACKSON195
12JAYJACKSON292
13WILLIAMBISHOP170
13WILLIAMBISHOP2100
14CHARLESPRADA285

Which SQL statement do we use to find out how many students took each exam?

  1. SELECT COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
  2. SELECT EXAM_ID, MAX(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
  3. SELECT EXAM_ID, COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
  4. SELECT EXAM_ID, MIN(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;

Answer

SELECT EXAM_ID, COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID;
Output
+---------+------------------------+
| EXAM_ID | COUNT(DISTINCT STU_ID) |
+---------+------------------------+
|       1 |                      4 |
|       2 |                      5 |
+---------+------------------------+
Explanation
  1. SELECT COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID; — It groups the EXAM_RESULTS table by EXAM_ID and uses the COUNT(DISTINCT STU_ID) function to count the number of distinct student IDs for each exam. However, the result set does not include EXAM_ID.
  2. SELECT EXAM_ID, MAX(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID; — This query groups the results by EXAM_ID and then selects the maximum STU_ID for each exam. However, this doesn't provide the count of students who took each exam, as it gives the maximum student ID instead of counting the distinct student IDs.
  3. SELECT EXAM_ID, COUNT(DISTINCT STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID; — It groups the EXAM_RESULTS table by EXAM_ID and uses the COUNT(DISTINCT STU_ID) function to count the number of distinct student IDs for each exam. The result set includes the EXAM_ID and the count of students who took each exam.
  4. SELECT EXAM_ID, MIN(STU_ID) FROM EXAM_RESULTS GROUP BY EXAM_ID; — This query groups the results by EXAM_ID and selects the minimum STU_ID for each exam. It does not provide information about the number of students who took each exam.

Question 8

Table EXAM_RESULTS

STU IDFNAMELNAMEEXAM IDEXAM_SCORE
10LAURALYNCH190
10LAURALYNCH285
11GRACEBROWN178
11GRACEBROWN272
12JAYJACKSON195
12JAYJACKSON292
13WILLIAMBISHOP170
13WILLIAMBISHOP2100
14CHARLESPRADA285

What SQL statement do we use to print out the record of all students whose last name starts with 'L'?

  1. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L%' ;
  2. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L';
  3. SELECT * FROM EXAM_RESULTS WHERE LNAME 'L';
  4. SELECT * FROM EXAM_RESULTS WHERE LNAME <> 'L';

Answer

SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L%' ;
Output
+--------+-------+-------+---------+------------+
| stu_id | fname | lname | exam_id | exam_score |
+--------+-------+-------+---------+------------+
|     10 | LAURA | LYNCH |       1 |         90 |
|     10 | LAURA | LYNCH |       2 |         85 |
+--------+-------+-------+---------+------------+
Explanation
  1. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L%'; — The LIKE operator is used for pattern matching in SQL. '%' is a wildcard character that matches zero or more characters. 'L%' specifies that the last name (LNAME) should start with 'L' followed by zero or more characters. The SELECT * statement retrieves all columns from the EXAM_RESULTS table for the matching records.
  2. SELECT * FROM EXAM_RESULTS WHERE LNAME LIKE 'L'; — This query attempts to select all columns (*) from the EXAM_RESULTS table where the last name (LNAME) is exactly equal to 'L'. However, when using the LIKE operator in SQL for pattern matching, we use wildcard characters (%) to represent unknown parts of a string.
  3. SELECT * FROM EXAM_RESULTS WHERE LNAME 'L'; — This statement contains a syntax error. In SQL, when using the WHERE clause to filter records based on a specific condition, we need to use comparison operators or functions to define the condition properly.
  4. SELECT * FROM EXAM_RESULTS WHERE LNAME <> 'L'; — This query retrieves records where the last name is not equal to 'L'. It does not specifically look for last names starting with 'L', so it's not the correct option for the given requirement.

Question 9

Table EXAM_RESULTS

STU IDFNAMELNAMEEXAM IDEXAM_SCORE
10LAURALYNCH190
10LAURALYNCH285
11GRACEBROWN178
11GRACEBROWN272
12JAYJACKSON195
12JAYJACKSON292
13WILLIAMBISHOP170
13WILLIAMBISHOP2100
14CHARLESPRADA285

What is the result of the following SQL statement ?

SELECT MAX(EXAM_SCORE) FROM EXAM_RESULTS GROUP BY EXAM_ID HAVING EXAM_ID = 1;
  1. 90
  2. 85
  3. 100
  4. 95

Answer

Output
+-----------------+
| MAX(EXAM_SCORE) |
+-----------------+
|              95 |
+-----------------+
Explanation

The above SQL query calculates the maximum exam score for EXAM_ID 1 from the EXAM_RESULTS table, by grouping results based on EXAM_ID and filtering using HAVING.

Question 10

Given the following table :

Table : CLUB

COACH-IDCOACHNAMEAGESPORTSDATOFAPPPAYSEX
1KUKREJA35KARATE27/03/19961000M
2RAVINA34KARATE20/01/19981200F
3KARAN34SQUASH19/02/19982000M
4TARUN33BASKETBALL01/01/19981500M
5ZUBIN36SWIMMING12/01/1998750M
6KETAKI36SWIMMING24/02/1998800F
7ANKITA39SQUASH20/02/19982200F
8ZAREEN37KARATE22/02/19981100F
9KUSH41SWIMMING13/01/1998900M
10SHAILYA37BASKETBALL19/02/19981700M

Give the output of following SQL statements :

  1. SELECT COUNT(DISTINCT SPORTS) FROM Club ;
  2. SELECT MIN(Age) FROM CLUB WHERE Sex = 'F' ;
  3. SELECT AVG(Pay) FROM CLUB WHERE Sports = 'KARATE' ;
  4. SELECT SUM(Pay) FROM CLUB WHERE Datofapp > '1998-01-31' ;

Answer

1.

Output
+------------------------+
| COUNT(DISTINCT SPORTS) |
+------------------------+
|                      4 |
+------------------------+
Explanation

The SQL query SELECT COUNT(DISTINCT SPORTS) FROM Club ; calculates the count of unique values in the 'SPORTS' column of the 'Club' table. This query helps us to get information about the number of sports offered by the club.

2.

Output
+----------+
| MIN(Age) |
+----------+
|       34 |
+----------+
Explanation

The SQL query SELECT MIN(Age) FROM CLUB WHERE Sex = 'F' ; retrieves the minimum Age from the 'CLUB' table where the 'Sex' column has the value 'F'. This query gives us the age of the youngest female coach in the club.

3.

Output
+-----------+
| AVG(Pay)  |
+-----------+
| 1100.0000 |
+-----------+
Explanation

The SQL query SELECT AVG(Pay) FROM CLUB WHERE Sports = 'KARATE' ; calculates the average value of the 'Pay' column from the 'CLUB' table where the 'Sports' column has the value 'KARATE'. This query helps us to get information about the average pay of karate coaches in the club.

4.

Output
+----------+
| SUM(Pay) |
+----------+
|     7800 |
+----------+
Explanation

The SQL query SELECT SUM(Pay) FROM CLUB WHERE Dateofapp > '1998-01-31'; calculates the sum of the 'Pay' column from the 'CLUB' table where the 'Dateofapp' column has a date value greater than '1998-01-31'. This query gives us the total pay of all the coaches who joined after 31/01/1998.

Question 11

In a Database, there are two tables given below :

Table : EMPLOYEE

EMPLOYEEIDNAMESALESJOBID
E1SUMIT SINHA1100000102
E2VIJAY SINGH TOMAR1300000101
E3AJAY RAJPAL1400000103
E4MOHIT RAMNANI1250000102
E5SHAILJA SINGH1450000103

Table : JOB

JOBIDJOBTITLESALARY
101President200000
102Vice President125000
103Administration Assistant80000
104Accounting Manager70000
105Accountant65000
106Sales Manager80000

Write SQL Queries for the following :

  1. To display employee ids, names of employees, job ids with corresponding job titles.
  2. To display names of employees, sales and corresponding job titles who have achieved sales more than 1300000.
  3. To display names and corresponding job titles of those employees who have 'SINGH' (anywhere) in their names.
  4. Identify foreign key in the table EMPLOYEE.
  5. Write SQL command to change the JOBID to 104 of the EMPLOYEE with ID as E4 in the table 'EMPLOYEE'.

Answer

1.

SELECT EMPLOYEE.EMPLOYEEID, EMPLOYEE.NAME, EMPLOYEE.JOBID, JOB.JOBTITLE
FROM EMPLOYEE, JOB
WHERE EMPLOYEE.JOBID = JOB.JOBID;
Output
+------------+-------------------+-------+--------------------------+
| EMPLOYEEID | NAME              | JOBID | JOBTITLE                 |
+------------+-------------------+-------+--------------------------+
| E1         | SUMIT SINHA       |   102 | VICE PRESIDENT           |
| E2         | VIJAY SINGH TOMAR |   101 | PRESIDENT                |
| E3         | AJAY RAJPAL       |   103 | ADMINISTARTION ASSISTANT |
| E4         | MOHIT RAMNANI     |   102 | VICE PRESIDENT           |
| E5         | SHAILJA SINGH     |   103 | ADMINISTARTION ASSISTANT |
+------------+-------------------+-------+--------------------------+

2.

SELECT EMPLOYEE.NAME, EMPLOYEE.SALES, JOB.JOBTITLE
FROM EMPLOYEE, JOB 
WHERE EMPLOYEE.JOBID = JOB.JOBID
AND EMPLOYEE.SALES > 1300000;
Output
+---------------+---------+--------------------------+
| NAME          | SALES   | JOBTITLE                 |
+---------------+---------+--------------------------+
| AJAY RAJPAL   | 1400000 | ADMINISTARTION ASSISTANT |
| SHAILJA SINGH | 1450000 | ADMINISTARTION ASSISTANT |
+---------------+---------+--------------------------+

3.

SELECT EMPLOYEE.NAME, JOB.JOBTITLE
FROM EMPLOYEE, JOB 
WHERE EMPLOYEE.JOBID = JOB.JOBID
AND EMPLOYEE.NAME LIKE '%SINGH%';
Output
+-------------------+--------------------------+
| NAME              | JOBTITLE                 |
+-------------------+--------------------------+
| VIJAY SINGH TOMAR | PRESIDENT                |
| SHAILJA SINGH     | ADMINISTARTION ASSISTANT |
+-------------------+--------------------------+

4. In the given tables, EMPLOYEE and JOB, the JOBID column in the EMPLOYEE table is a foreign key referencing the JOBID column in the JOB table.

5.

UPDATE EMPLOYEE
SET JOBID = 104
WHERE EMPLOYEEID = 'E4';
Output
SELECT * FROM EMPLOYEE ;
+------------+-------------------+---------+-------+
| EMPLOYEEID | NAME              | SALES   | JOBID |
+------------+-------------------+---------+-------+
| E1         | SUMIT AINHA       | 1100000 |   102 |
| E2         | VIJAY SINGH TOMAR | 1300000 |   101 |
| E3         | AJAY RAJPAL       | 1400000 |   103 |
| E4         | MOHIT RAMNANI     | 1250000 |   104 |
| E5         | SHAILJA SINGH     | 1450000 |   103 |
+------------+-------------------+---------+-------+

Question 12

Consider the following tables Employee and Salary. Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (vii)

Table : Employee

EidNameDepidQualificationSec
1Deepali Gupta101MCAF
2Rajat Tyagi101BCAM
3Hari Mohan102B.A.M
4Harry102M.A.M
5Sumit Mittal103B.Tech.M
6Jyoti101M.Tech.F

Table : Salary

EidBasicD.AHRABonus
1600020002300200
2200030030030
3100030030040
4150039049030
5800090090080
61000030049089
  1. To display the frequency of employees department wise.
  2. To list the names of those employees only whose name starts with 'H'
  3. To add a new column in salary table. The column name is Total_Sal.
  4. To store the corresponding values in the Total_Sal column.
  5. Select max(Basic) from Salary where Bonus > 40 ;
  6. Select count(*) from Employee group by Sex ;
  7. Select Distinct Depid from Employee ;

Answer

1.

SELECT Depid, COUNT(*) AS Frequency 
FROM Employee 
GROUP BY Depid;

2.

SELECT Name
FROM Employee
WHERE Name LIKE 'H%';

3.

ALTER TABLE Salary
ADD COLUMN Total_Sal FLOAT;

4.

UPDATE Salary
SET Total_Sal = Basic + `D.A.` + HRA + Bonus;

5.

SELECT MAX(Basic)
FROM Salary
WHERE Bonus > 40;
Output
+------------+
| MAX(Basic) |
+------------+
|      10000 |
+------------+

6.

SELECT Sec as sex, COUNT(*) AS Count 
FROM Employee 
GROUP BY Sec ;
Output
+-----+-------+
| sex | Count |
+-----+-------+
| F   |     2 |
| M   |     4 |
+-----+-------+

7.

SELECT DISTINCT Depid FROM Employee ;
Output
+-------+
| Depid |
+-------+
|   101 |
|   102 |
|   103 |
+-------+

Question 13

With reference to following relations PERSONAL and JOB answer the questions that follow :

Create following tables such that Empno and Sno are not null and unique, date of birth is after '12-Jan-1960', name is never blank, Area and Native place is valid, hobby, dept is not empty, salary is between 4000 and 10000.

Table : Personal

EmpnoNameDobirthNative-placeHobby
123Amit23-Jan-1965DelhiMusic
127Manoj12-dec-1976MumbaiWriting
124Abhai11-aug-1975AllahabadMusic
125Vinod04-apr-1977DelhiSports
128Abhay10-mar-1974MumbaiGardening
129Ramesh28-oct-1981PuneSports

Table : Job

SnoAreaApp_dateSalaryRetd_dateDept
123Agra25-jan-2006500025-jan-2026Marketing
127Mathura22-dec-2006600022-dec-2026Finance
124Agra19-aug-2007550019-aug-2027Marketing
125Delhi14-apr-2004850014-apr-2018Sales
128Pune13-mar-2008750013-mar-2028Sales
129Bangalore21-july-2003700021-july-2023Finance

(a) Show empno, name and salary of those who have Sports as hobby.

(b) Show name of the eldest employee.

(c) Show number of employee area wise.

(d) Show youngest employees from each Native place.

(e) Show Sno, Name, Hobby and Salary in descending order of Salary.

(f) Show the hobbies of those whose name pronounces as 'Abhay'.

(g) Show the appointment date and native place of those whose name starts with 'A' or ends in 'd'.

(h) Show the salary expense with suitable column heading of those who shall retire after 20-jan-2006.

(i) Show additional burden on the company in case salary of employees having hobby as sports, is increased by 10%.

(j) Show the hobby of which there are 2 or more employees.

(k) Show how many employee shall retire today if maximum length of service is 20 years.

(l) Show those employee name and date of birth who have served more than 17 years as on date.

(m) Show names of those who earn more than all of the employees of Sales dept.

(n) Increase salary of the employees by 5 % of their present salary with hobby as Music or they have completed atleast 3 years of service.

(o) Write the output of :

  1. Select distinct hobby from personal ;
  2. Select avg(salary) from personal, job where Personal.Empno = Job.Sno and Area in ('Agra','Delhi') ;
  3. Select count(distinct Native_place) from personal.
  4. Select name, max(salary) from Personal, Job where Personal.Empno = Job.Sno;

(p) Add a new tuple in the table Personal essentially with hobby as Music.

(q) Insert a new column email in Job table

(r) Create a table with values of columns empno, name, and hobby.

(s) Create a view of Personal and Job details of those who have served less than 15 years.

(t) Erase the records of employee from Job table whose hobby is not Sports.

(u) Remove the table Personal.

Answer

(a)

SELECT P.EMPNO, P.NAME, J.Salary 
FROM PERSONAL P, JOB J
WHERE P.EMPNO = J.Sno AND P.Hobby = 'Sports';
Output
+-------+--------+--------+
| EMPNO | NAME   | Salary |
+-------+--------+--------+
|   125 | Vinod  |   8500 |
|   129 | Ramesh |   7000 |
+-------+--------+--------+

(b)

SELECT name
FROM personal
WHERE dobirth = (
    SELECT MIN(dobirth)
    FROM personal
);
Output
+------+
| name |
+------+
| Amit |
+------+

(c)

SELECT Area, COUNT(Sno) AS Employee_Count
FROM Job
GROUP BY Area;
Output
+-----------+----------------+
| Area      | Employee_Count |
+-----------+----------------+
| Agra      |              2 |
| Delhi     |              1 |
| Mathura   |              1 |
| Pune      |              1 |
| Bangalore |              1 |
+-----------+----------------+

(d)

SELECT Name, `Native-place`, dobirth  
FROM personal  
WHERE dobirth = (SELECT MAX(dobirth)         
FROM personal p2          
WHERE personal.`Native-place` = p2.`Native-place` ) ;
Output
+--------+--------------+------------+
| Name   | Native-place | dobirth    |
+--------+--------------+------------+
| Abhai  | Allahabad    | 1975-08-11 |
| Vinod  | Delhi        | 1977-04-04 |
| Manoj  | Mumbai       | 1976-12-12 |
| Ramesh | Pune         | 1981-10-28 |
+--------+--------------+------------+

(e)

SELECT SNO, NAME, HOBBY, SALARY 
FROM PERSONAL, JOB 
WHERE PERSONAL.EMPNO = JOB.SNO 
ORDER BY SALARY DESC;
Output
+-----+--------+-----------+--------+
| SNO | NAME   | HOBBY     | SALARY |
+-----+--------+-----------+--------+
| 125 | Vinod  | Sports    |   8500 |
| 128 | Abhay  | Gardening |   7500 |
| 129 | Ramesh | Sports    |   7000 |
| 127 | Manoj  | Writing   |   6000 |
| 124 | Abhai  | Music     |   5500 |
| 123 | Amit   | Music     |   5000 |
+-----+--------+-----------+--------+

(f)

SELECT HOBBY 
FROM PERSONAL 
WHERE Name = 'abhay' or Name = 'abhai' ;
Output
+-----------+
| HOBBY     |
+-----------+
| Music     |
| Gardening |
+-----------+

(g)

SELECT App_date, nativeplace 
FROM personal, job 
WHERE personal.empno = job.sno 
AND (Name LIKE 'A%' OR Name LIKE '%d') ;
Output
+------------+--------------+
| App_date   | native-place |
+------------+--------------+
| 2006-01-25 | Delhi        |
| 2007-08-19 | Allahabad    |
| 2004-04-14 | Delhi        |
| 2008-03-13 | Mumbai       |
+------------+--------------+

(h)

SELECT Salary AS "Salary Expense" 
FROM Job
WHERE `Retd_date` > '2006-01-20';
Output
+----------------+
| Salary Expense |
+----------------+
|           5000 |
|           5500 |
|           8500 |
|           6000 |
|           7500 |
|           7000 |
+----------------+

(i)

SELECT SUM(Salary * 0.1) AS "Additional Burden" 
FROM PERSONAL, JOB
WHERE PERSONAL.EMPNO = JOB.SNO AND HOBBY = 'SPORTS' ;
Output
+-------------------+
| Additional Burden |
+-------------------+
|            1550.0 |
+-------------------+

(j)

SELECT Hobby 
FROM PERSONAL 
GROUP BY Hobby 
HAVING COUNT(*) >= 2;
Output
+--------+
| Hobby  |
+--------+
| Music  |
| Sports |
+--------+

(k)

SELECT COUNT(*)  
FROM Job
WHERE DATEDIFF(CURDATE(), App_date) >= 20 * 365;
Output
+----------+
| COUNT(*) |
+----------+
|        0 |
+----------+

(l)

SELECT P.Name, P.Dobirth 
FROM Personal P, Job J 
WHERE P.Empno = J.Sno AND J.Retd_date > CURDATE() AND DATEDIFF(CURDATE(), J.App_date) > 17 * 365;
Output
+-------+------------+
| Name  | Dobirth    |
+-------+------------+
| Amit  | 1965-01-23 |
| Manoj | 1976-12-12 |
+-------+------------+

(m)

SELECT Name 
FROM Personal, job
where personal.Empno = job.Sno 
and job.Salary > ( select max(salary) 
from job
where dept = 'sales');
Explanation

There will be no output because there are no employees whose salary is greater than the highest salary in the Sales department.

(n)

UPDATE Job J, Personal P
SET J.Salary = (J.Salary * 0.05 ) + J.Salary
WHERE J.Sno = P.Empno
AND (P.Hobby = 'Music' 
OR DATEDIFF(CURDATE(), J.App_date) >= 3 * 365);
Output
+-----+-----------+------------+--------+------------+-----------+
| sno | area      | app_date   | salary | retd_date  | dept      |
+-----+-----------+------------+--------+------------+-----------+
| 123 | Agra      | 2006-01-25 |   5250 | 2026-01-25 | Marketing |
| 124 | Agra      | 2007-08-19 |   5775 | 2027-08-19 | Marketing |
| 125 | Delhi     | 2004-04-14 |   8925 | 2018-04-14 | Sales     |
| 127 | Mathura   | 2006-12-22 |   6300 | 2026-12-22 | Finance   |
| 128 | Pune      | 2008-03-13 |   7875 | 2028-03-13 | Sales     |
| 129 | Bangalore | 2003-07-21 |   7350 | 2023-07-21 | Finance   |
+-----+-----------+------------+--------+------------+-----------+

(o)

1.

Select distinct hobby from personal ; 
Output
+-----------+
| hobby     |
+-----------+
| Music     |
| Sports    |
| Writing   |
| Gardening |
+-----------+

2.

Select avg(salary) from personal, job where Personal.Empno = Job.Sno and Area in ('Agra','Delhi') ;  
Output
+-------------+
| AVG(SALARY) |
+-------------+
|   6650.0000 |
+-------------+

3.

Select count(distinct Native_place) from personal;
Output
+--------------------------------+
| COUNT(DISTINCT `NATIVE-PLACE`) |
+--------------------------------+
|                              4 |
+--------------------------------+

4.

Select name, max(salary) 
from Personal, Job where Personal.Empno = Job.Sno ;
Output
+------+-------------+
| name | max(salary) |
+------+-------------+
| Amit |        8500 |
+------+-------------+
Explanation

The given query retrieves the maximum salary from the 'Job' table and pairs it with the corresponding employee name from the 'Personal' table based on the matching Empno and Sno values. However, including a non-group field like 'name' in the select-list means it will return the value from the first record of the group for the 'name' field. Therefore, 'Amit' is the first record in the 'Personal' table, the query returns 'Amit' as the value for the 'name' field.

(p)

INSERT INTO Personal (Empno, Name, Dobirth, `Native-place`, Hobby)
VALUES (130, 'Amruta', '1990-05-15', 'Chennai', 'Music');
Output
select * from personal;
+-------+--------+------------+--------------+-----------+
| empno | name   | dobirth    | native-place | hobby     |
+-------+--------+------------+--------------+-----------+
|   123 | Amit   | 1965-01-23 | Delhi        | Music     |
|   124 | Abhai  | 1975-08-11 | Allahabad    | Music     |
|   125 | Vinod  | 1977-04-04 | Delhi        | Sports    |
|   127 | Manoj  | 1976-12-12 | Mumbai       | Writing   |
|   128 | Abhay  | 1974-03-10 | Mumbai       | Gardening |
|   129 | Ramesh | 1981-10-28 | Pune         | Sports    |
|   130 | Amruta | 1990-05-15 | Chennai      | Music     |
+-------+--------+------------+--------------+-----------+

(q)

ALTER TABLE Job
ADD COLUMN Email VARCHAR(55); 

(r)

insert into empdetails(empno, name, hobby)
select empno, name, hobby
from personal ;
Output
select * from empdetails ;
+-------+--------+-----------+
| Empno | Name   | Hobby     |
+-------+--------+-----------+
|   123 | Amit   | Music     |
|   124 | Abhai  | Music     |
|   125 | Vinod  | Sports    |
|   127 | Manoj  | Writing   |
|   128 | Abhay  | Gardening |
|   129 | Ramesh | Sports    |
|   130 | Amruta | Music     |
+-------+--------+-----------+

(s)

CREATE VIEW LessThan15YearsView AS
SELECT * FROM Personal p, Job j   
WHERE p.Empno = j.Sno AND 
DATEDIFF(CURDATE(), J.App_date) < 15 * 365;

(t)

DELETE j
FROM Job j, Personal p 
WHERE j.Sno = p.Empno AND p.Hobby <> 'Sports';

(u)

DROP TAbLE Personal;

Question 14a

With reference to the table below, answer the questions that follow :

Table : Employees

EmpidFirstnameLastnameAddressCity
010RaviKumarRaj nagarGZB
105HarryWaltorGandhi nagarGZB
152SamTones33 Elm St.Paris
215SarahAckerman440 U.S. 110Upton
244ManilaSengupta24 Friends streetNew Delhi
300RobertSamuel9 Fifth CrossWashington
335RituTondonShastri NagarGZB
400RachelLee121 Harrison St.New York
441PeterThompson11 Red RoadParis

Table : EmpSalary

EmpidSalaryBenefitsDesignation
0107500015000Manager
1056500015000Manager
1528000025000Director
2157500012500Manager
2445000012000Clerk
3004500010000Clerk
3354000010000Clerk
400320007500Salesman
441280007500Salesman

Write the SQL commands for the following using above tables :

(i) To show firstname, lastname, address and city of all employees living in Pairs.

(ii) To display the content of Employees table in descending order of Firstname.

(iii) To display the firstname, lastname and total salary of all managers from the tables Employes and EmpSalary, where total salary is calculated as Salary + Benefits.

(iv) To display the maximum salary among managers and clerks from the table EmpSalary.

Answer

(i)

SELECT Firstname, Lastname, Address, City
FROM Employees
WHERE City = 'Paris';
Output
+-----------+----------+-------------+-------+
| Firstname | Lastname | Address     | City  |
+-----------+----------+-------------+-------+
| SAM       | TONES    | 33 ELM ST.  | PARIS |
| PETER     | THOMPSON | 11 RED ROAD | PARIS |
+-----------+----------+-------------+-------+

(ii)

SELECT *
FROM Employees
ORDER BY Firstname DESC;
Output
+-------+-----------+----------+-------------------+------------+
| empid | FIRSTNAME | LASTNAME | ADDRESS           | CITY       |
+-------+-----------+----------+-------------------+------------+
|   215 | SARAH     | ACKERMAN | 440 U.S. 110      | UPTON      |
|   152 | SAM       | TONES    | 33 ELM ST.        | PARIS      |
|   300 | ROBERT    | SAMUEL   | 9 FIFTH CROSS     | WASHINGTON |
|   335 | RITU      | TONDON   | SHASTRI NAGAR     | GZB        |
|    10 | RAVI      | KUMAR    | RAJ NAGAR         | GZB        |
|   400 | RACHEL    | LEE      | 121 HARRISON ST.  | NEW YORK   |
|   441 | PETER     | THOMPSON | 11 RED ROAD       | PARIS      |
|   244 | MANILA    | SENGUPTA | 24 FRIENDS STREET | NEW DELHI  |
|   105 | HARRY     | WALTOR   | GANDHI NAGAR      | GZB        |
+-------+-----------+----------+-------------------+------------+

(iii)

SELECT e.Firstname, e.Lastname, 
(s.Salary + s.Benefits) AS TotalSalary
FROM Employees e, EmpSalary s  
WHERE e.Empid = s.Empid AND s.Designation = 'Manager';
Output
+-----------+----------+-------------+
| Firstname | Lastname | TotalSalary |
+-----------+----------+-------------+
| RAVI      | KUMAR    |       90000 |
| HARRY     | WALTOR   |       80000 |
| SARAH     | ACKERMAN |       87500 |
+-----------+----------+-------------+

(iv)

SELECT Designation, MAX(Salary) 
FROM EmpSalary 
WHERE Designation IN ('Manager', 'Clerk') 
group by designation;
Output
+-------------+-------------+
| Designation | MAX(Salary) |
+-------------+-------------+
| MANAGER     |       75000 |
| CLERK       |       50000 |
+-------------+-------------+

Question 14b

With reference to the table below, answer the questions that follow :

Table : Employees

EmpidFirstnameLastnameAddressCity
010RaviKumarRaj nagarGZB
105HarryWaltorGandhi nagarGZB
152SamTones33 Elm St.Paris
215SarahAckerman440 U.S. 110Upton
244ManilaSengupta24 Friends streetNew Delhi
300RobertSamuel9 Fifth CrossWashington
335RituTondonShastri NagarGZB
400RachelLee121 Harrison St.New York
441PeterThompson11 Red RoadParis

Table : EmpSalary

EmpidSalaryBenefitsDesignation
0107500015000Manager
1056500015000Manager
1528000025000Director
2157500012500Manager
2445000012000Clerk
3004500010000Clerk
3354000010000Clerk
400320007500Salesman
441280007500Salesman

Give the Output of following SQL commands :

(i) Select firstname, Salary from Employees, Empsalary where Designation = 'Salesman' and Employees.Empid = Empsalary.Empid ;

(ii) Select count(distinct designation) from EmpSalary ;

(iii) Select designation, sum(salary) from EmpSalary group by designation having count(*) > 2 ;

(iv) Select sum(Benefits) from EmpSalary where Designation = 'Clerk' ;

Answer

(i)

Output
+-----------+--------+
| FIRSTNAME | SALARY |
+-----------+--------+
| RACHEL    |  32000 |
| PETER     |  28000 |
+-----------+--------+

(ii)

Output
+-----------------------------+
| COUNT(DISTINCT DESIGNATION) |
+-----------------------------+
|                           4 |
+-----------------------------+

(iii)

Output
+-------------+-------------+
| DESIGNATION | SUM(SALARY) |
+-------------+-------------+
| MANAGER     |      215000 |
| CLERK       |      135000 |
+-------------+-------------+

(iv)

Output
+---------------+
| SUM(BENEFITS) |
+---------------+
|         32000 |
+---------------+

Question 15

Show the average salary for all departments with more than 3 people for a job.

Answer

SELECT job, AVG(Sal) AS AvgSalary 
FROM Empl 
GROUP BY job HAVING COUNT(*) > 3;
Output
+----------+-----------+
| job      | AvgSalary |
+----------+-----------+
| CLERK    |    1037.5 |
| SALESMAN |      1400 |
+----------+-----------+

Question 16

Display only the jobs with maximum salary greater than or equal to 3000.

Answer

SELECT Job 
FROM Empl 
GROUP BY Job HAVING MAX(Sal) >= 3000;
Output
+-----------+
| Job       |
+-----------+
| PRESIDENT |
| ANALYST   |
+-----------+

Question 17

Find out number of employees having "Manager" as Job.

Answer

SELECT COUNT(*) AS NumManagers
FROM EmpSalary
WHERE Designation = 'Manager';
Output
+-------------+
| NumManagers |
+-------------+
|           3 |
+-------------+

Question 18

List the count of employees grouped by deptno. (table EMPL)

Answer

SELECT deptno, COUNT(*) AS employee_count
FROM EMPL
GROUP BY deptno;
Output
+--------+----------------+
| deptno | employee_count |
+--------+----------------+
|     20 |              5 |
|     30 |              6 |
|     10 |              3 |
+--------+----------------+

Question 19

List the sum of employees' salaries grouped by department. (table EMPL)

Answer

SELECT deptno, SUM(sal) AS total_salary
FROM EMPL
GROUP BY deptno;
Output
+--------+--------------+
| deptno | total_salary |
+--------+--------------+
|     20 |        10885 |
|     30 |         9400 |
|     10 |         8750 |
+--------+--------------+

Question 20

List the maximum salary of employee grouped by their department number.

Answer

SELECT deptno, MAX(sal) AS max_salary
FROM EMPL
GROUP BY deptno;
Output
+--------+------------+
| deptno | max_salary |
+--------+------------+
|     20 |       3000 |
|     30 |       2850 |
|     10 |       5000 |
+--------+------------+

Question 21

Below are the customer and order tables :

Customers

customer id (PK)
first_name
last_name
email
address
city
state
zip

Orders

order id (PK)
order_date
amount
customer_id (FK)

List the total of customers' orders grouped by customer (id).

Answer

SELECT c.customer_id, COUNT(o.order_id) AS total_orders
FROM Customers c, orders o
WHERE c.customer_id = o.customer_id
GROUP BY c.customer_id;

Question 22

Below are the customer and order tables :

Customers

customer id (PK)
first_name
last_name
email
address
city
state
zip

Orders

order id (PK)
order_date
amount
customer_id (FK)

List the sum of the totals of orders grouped by customer and state.

Answer

SELECT c.customer_id, c.state, SUM(o.amount) AS total_order_amount
FROM Customers c, orders o
WHERE c.customer_id = o.customer_id
GROUP BY c.customer_id, c.state;

Question 23

Below are the customer and order tables :

Customers

customer id (PK)
first_name
last_name
email
address
city
state
zip

Orders

order id (PK)
order_date
amount
customer_id (FK)

List the customers (name) and the total amount of all their orders.

Answer

SELECT CONCAT(c.first_name, ' ', c.last_name) AS customer_name,
SUM(o.amount) AS total_order_amount
FROM Customers c, Orders o 
WHERE c.customer_id = o.customer_id
GROUP BY c.customer_id;

Question 24

Schemas of tables EMPL, Dept, SalaryGrade are being shown below :

EMPL (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)

SALARYGRADE (Lowsal, Highsal, Grade)

DEPT (Deptno, DeptName, Location)

List the department names and the number of their employees.

Answer

SELECT d.DeptName AS Department_Name, COUNT(e.EMPNO) AS Number_of_Employees
FROM DEPT d, EMPL e
WHERE d.Deptno = e.DEPTNO
GROUP BY d.DeptName;

Question 25

Schemas of tables EMPL, Dept, SalaryGrade are being shown below :

EMPL (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)

SALARYGRADE (Lowsal, Highsal, Grade)

DEPT (Deptno, DeptName, Location)

List the employee names and the name of their departments.

Answer

SELECT e.ENAME AS Employee_Name, d.DeptName AS Department_Name
FROM EMPL e, DEPT d
WHERE e.DEPTNO = d.Deptno;
PrevNext