KnowledgeBoat Logo
OPEN IN APP

Chapter 7

Querying Using SQL

Class 12 - Informatics Practices Sumita Arora



Checkpoint 7.1

Question 1

Can you arrange the result set of an SQL query on multiple columns ?

Answer

Yes, we can arrange the result set of an SQL query on multiple columns. We should specify the multiple column names in the ORDER BY clause along with the desired sort order.

For example, the following statement will sort the records in the data table first by the section column in ascending order and then by the marks column in descending order.

SELECT * FROM data
ORDER BY section ASC, marks DESC;

Question 2

What is the significance of "ORDER BY" in the given query?

SELECT emp_id, fname, lname
FROM person
ORDER BY emp_id;

(a) Data of table person on the basis of column emp_id will be sorted in descending order

(b) Data of table person on the basis of column emp_id will be sorted in ascending order

(c) Only data of column emp_id will be sorted in descending order

(d) Only data of column emp_id will be sorted in ascending order

Answer

Data of table person on the basis of column emp_id will be sorted in ascending order

Reason — The significance of the ORDER BY clause in the given query is to sort the result set based on the values in the emp_id column in ascending order by default.

Question 3

What will be the order of sorting in the given query?

SELECT emp_id, emp_name 
FROM person
ORDER BY emp_id, emp_name;

(a) Firstly on emp_id and then on emp_name

(b) Firstly on emp_name and then on emp_id

(c) Firstly on emp_id but not on emp_name

(d) None of the mentioned

Answer

Firstly on emp_id and then on emp_name

Reason — The ORDER BY emp_id, emp_name clause sorts the result set firstly by the emp_id column. If there are rows with the same emp_id, those rows are further sorted by the emp_name column.

Question 4

If column emp_id contains the following set {9, 7, 6, 4, 3, 1, 2}, what will be the output on execution of the given query?

SELECT emp_id 
FROM person 
ORDER BY emp_id;

(a) {9, 7, 6, 4, 3, 1, 2}

(b) {1, 2, 3, 4, 6, 7, 9}

(c) {2, 1, 4, 3, 7, 9, 6}

(d) None of these

Answer

{1, 2, 3, 4, 6, 7, 9}

Reason — The ORDER BY clause in SQL sorts the result set based on the specified column(s) in ascending order by default. In the given query, the emp_id column is specified in the ORDER BY clause. Therefore, the query will sort the emp_id values in ascending order.

Question 5

Which function can you use with ORDER BY clause to specify custom sort order ?

(a) SORT()

(b) CUSTOM()

(c) FIELD()

(d) All of these

Answer

FIELD()

Reason — The FIELD() function in SQL allows to specify a custom sort order by listing the values in the order we want them to appear.
For example, the following statement selects column fruit_name from the fruits table and orders the result set based on the custom sort order specified by the FIELD() function.

SELECT * FROM fruits
ORDER BY FIELD(fruit_name, 'Apple', 'Banana', 'Orange', 'Grapes');

Multiple Choice Questions

Question 1

By default, ORDER BY clause lists the results in ............... order.

  1. Descending
  2. Any
  3. Same
  4. Ascending

Answer

Ascending

Reason — By default, ORDER BY clause lists the results in ascending order.

Question 2

Which one of the following would arrange the rows in ascending order in SQL ?

  1. SORT BY
  2. ALIGN BY
  3. GROUP BY
  4. ORDER BY

Answer

ORDER BY

Reason — The ORDER BY clause in SQL is used to sort the result set in either ascending or descending order.

Question 3

To create summary results, ............... clause is used.

  1. SORT BY
  2. SUMMARY BY
  3. GROUP BY
  4. ORDER BY

Answer

GROUP BY

Reason — The GROUP BY clause in SQL is used to create summary results by grouping together all records that share identical values in a particular field or a group of fields.

Question 4

Consider the following query

SELECT * FROM employee ORDER BY salary ............... , name ............... ;

To display the salary from greater to smaller and name in alphabetical order which of the following options should be used ?

  1. Ascending, Descending
  2. Asc, Desc
  3. Desc, Asc
  4. Descending, Ascending

Answer

Desc, Asc
Descending, Ascending

Reason — To display the salary from greater to smaller i.e., in descending order we use DESC or descending keyword and to sort name in alphabetical order i.e., in ascending order we use ASC or ascending keyword.

Question 5

Select correct SQL query from below to find the temperature in increasing order of all cities.

  1. SELECT city FROM weather ORDER BY temperature ;

  2. SELECT city, temperature FROM weather ;

  3. SELECT city, temperature FROM weather ORDER BY temperature ;

  4. SELECT city, temperature FROM weather ORDER BY city ;

Answer

SELECT city, temperature FROM weather ORDER BY city ;

Reason — The query SELECT city, temperature FROM weather ORDER BY city ; selects the city and temperature columns from the weather table and sorts the result set by the city column in ascending order.

Question 6

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 7

Which SQL statement do we use to find out the total number of records present in the table ORDERS ?

  1. SELECT * FROM ORDERS;
  2. SELECT COUNT(*) FROM ORDERS ;
  3. SELECT FIND (*) FROM ORDERS ;
  4. SELECT SUM() FROM ORDERS ;

Answer

SELECT COUNT(*) FROM ORDERS ;

Reason — The COUNT() function in SQL counts the number of rows or records in a table. When used with the asterisk (*), it counts all rows in the table, including duplicates and nulls. Therefore, SELECT COUNT(*) FROM ORDERS will return the total number of records in the ORDERS table.

Question 8

With SQL, how can you return the number of not null records in the Project field of "Students" table ?

  1. SELECT COUNT(Project) FROM Students
  2. SELECT COLUMNS(Project) FROM Students
  3. SELECT COLUMNS(*) FROM Students
  4. SELECT COUNT(*) FROM Students

Answer

SELECT COUNT(Project) FROM Students

Reason — The COUNT() function in SQL counts the number of non-null records in a column. By using COUNT(Project), we are counting the number of rows where the Project column is not null in the student table.

Question 9

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 10

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 11

Which of the following group functions ignore NULL values ?

  1. MAX
  2. COUNT
  3. SUM
  4. All of these

Answer

All of these

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

Question 12

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 13

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 14

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 15

Which clause is used with "aggregate functions" ?

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

Answer

GROUP BY

Reason — Aggregate functions (such as COUNT, SUM, AVG, MAX, MIN) are used with the GROUP BY clause to perform operations on each group of rows. The GROUP BY clause groups rows that have the same values in specified columns into summary rows.

Question 16

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 group

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 17

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 18

Raj, a Database Administrator, needs to display the average pay of workers from those departments which have more than five employees. He is experiencing a problem while running the following query :

SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5 GROUP BY DEPT;

Which of the following is a correct query to perform the given task ?

  1. SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5 GROUP BY DEPT;
  2. SELECT DEPT, AVG(SAL) FROM EMP HAVING COUNT(*) > 5 GROUP BY DEPT;
  3. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT WHERE COUNT(*) > 5;
  4. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING COUNT(*) > 5;

Answer

SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING COUNT(*) > 5;

Reason — In the above query, the WHERE clause cannot be used with aggregate functions like COUNT(*) because it is meant to filter individual rows before the aggregation. On the other hand, the HAVING clause filters the groups created by the GROUP BY clause to include only those departments (DEPT) that have more than five employees.

Fill in the Blanks

Question 1

To sort the rows of the result table, the ORDER BY clause is specified.

Question 2

Columns can be sorted in descending sequence by using the SQL keyword DESC.

Question 3

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

Question 4

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

Question 5

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

Question 6

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

Question 7

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

Question 8

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

Question 9

With GROUP BY queries, aggregate functions are used.

Question 10

To specify a condition on groups created by GROUP BY, HAVING clause is used.

True/False Questions

Question 1

The rows of the result relation produced by a SELECT statement can be sorted, but only by one column.

Answer

False

Reason — In SQL, the ORDER BY clause is used to sort the rows of the result relation produced by a SELECT statement. It allows sorting by one or more columns in ascending or descending order.

Question 2

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 3

The qualifier DISTINCT must be used in an SQL statement when we want to eliminate duplicate rows.

Answer

True

Reason — The DISTINCT keyword in SQL is used to eliminate duplicate rows from the results of a query. Therefore, when a user wants to ensure that only unique rows are returned, they must use the DISTINCT qualifier in their SQL statement.

Question 4

DISTINCT and its counterpart, ALL, can be used more than once in a SELECT statement.

Answer

False

Reason — In SQL, both DISTINCT and ALL keywords can be specified only once in a given SELECT clause.

Question 5

DISTINCT and its counterpart, ALL, can be used together on single field in a SELECT statement.

Answer

False

Reason — In SQL, DISTINCT and ALL cannot be used together on a single field in a SELECT statement. As DISTINCT eliminates duplicate rows from the results, while ALL includes all rows, including duplicates. Therefore, attempting to use them together on the same field would result in a syntax error.

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(fieldname), it counts only the rows where the specified field (fieldname) 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 statement : SELECT Salary + Comm AS Total FROM Emp; adds two fields salary and comm from each row together and lists the results in a column named Total.

Answer

True

Reason — The SQL statement SELECT Salary + Comm AS Total FROM Emp; adds the values of the Salary and Comm columns from each row together and lists the results in a column named Total. This is achieved by using the "+" operator to perform arithmetic addition on the values of the specified fields.

Question 9

ORDER BY can be combined with the SELECT statements.

Answer

True

Reason — The ORDER BY can be combined with the SELECT statements in SQL to sort query results based on one or more columns.

Question 10

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.

Assertions and Reasons

Question 1

Assertion. The ORDER BY clause of SELECT statement is carried out in the last after executing other clauses of the SELECT statement.

Reason. The ORDER BY clause is carried out on the final result of the SELECT query.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In SQL, the execution order of a SELECT statement is such that the ORDER BY clause is processed last, after all other clauses like FROM, WHERE, GROUP BY, HAVING, and SELECT have been executed. This is because the ORDER BY clause sorts the final result set produced by these earlier steps.

Question 2

Assertion. MOD() and MIN() are numeric functions, yet they are different types of functions.

Reason. MOD() is a single-row function and MIN() is a group function.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
MOD() and MIN() are numeric functions, but they are different types. MOD() is a single-row function, meaning it operates on individual rows and returns a result for each row. In contrast, MIN() is a group function (an aggregate function), which operates on a set of rows and returns a single result for the entire set.

Question 3

Assertion. The GROUP BY clause can use any type of function.

Reason. The GROUP BY clause combines a number of rows in a group and applies functions on it.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is false but R is true.

Explanation
The GROUP BY clause uses aggregate functions. It combines all those records that have identical values in a particular field or a group of fields and applies group-functions, resulting in one summary record per group.

Question 4

Assertion. The GROUP BY clause yields summary results using group functions.

Reason. The GROUP BY clause combines a number of rows in a group and applies functions on it.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The GROUP BY clause yields summary results using group functions because it combines all records that have identical values in a particular field or a group of fields. This grouping results in one summary record per group if group functions are used with it.

Question 5

Assertion. Both WHERE and HAVING clauses work with GROUP BY in a SELECT statement.

Reason. The WHERE clause is applied before forming groups of rows and HAVING clause is applied after forming the groups.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
Both the WHERE and HAVING clauses can be used with the GROUP BY clause in a SELECT statement to filter and specify conditions for rows and groups, respectively. The WHERE clause filters rows before they are grouped, while the HAVING clause filters groups of rows after they have been grouped by the GROUP BY clause. This is because WHERE conditions cannot include aggregate functions, whereas HAVING conditions can include them.

Question 6

Assertion. Both WHERE and HAVING clauses are used for specifying conditions.

Reason. WHERE and HAVING clauses of the SELECT query can be used interchangeably.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true but R is not the correct explanation of A.

Explanation
Both WHERE and HAVING clauses are used to specify conditions in a SELECT query, they operate at different levels. The WHERE clause filters rows based on conditions applied to individual rows before grouping, while the HAVING clause filters groups based on conditions applied to the result of aggregation functions after grouping. Hence, they are not interchangeable.

Question 7

Assertion. Both WHERE and HAVING clauses are used for specifying conditions.

Reason. The WHERE condition is applicable on individual rows and HAVING condition is applicable on a group of rows.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true but R is not the correct explanation of A.

Explanation
Both WHERE and HAVING clauses are used to specify conditions in a SELECT query, they operate at different levels. The WHERE clause filters rows based on conditions applied to individual rows before grouping, while the HAVING clause filters groups based on conditions applied to the result of aggregation functions after grouping.

Type A: Short Answer Questions/Conceptual Questions

Question 1

Anjali writes the following commands with respect to a table employee having fields, empno, name, department, commission :

Command1: Select count(*) from employee;
Command2: Select count(commission) from employee;

She gets the output as 4 for the first command but gets an output 3 for the second command. Explain the output with justification.

Answer

The difference in output is due to how COUNT() function behaves with different types of data in the specified column.

Command1: Select count(*) from employee; : This command counts all rows in the employee table, regardless of whether any column contains NULL values or not. When we specify an asterisk (*) with COUNT(), it returns the total number of rows in the table, including duplicates and NULL values. So, it returns the total number of rows in the table, which is 4.

Command2: Select count(commission) from employee; : If we specify argument (expr) in COUNT() function, it returns rows where expr is not null. This command counts the number of non-NULL values in the commission column. Therefore, it returns a count of 3 instead of 4 due to the presence of a NULL value in that column in one of the rows.

Question 2

What is the use of ORDER BY clause ?

Answer

In SQL, the ORDER BY clause is used to sort the rows of the result set produced by a SELECT statement. We can specify one or more columns in the ORDER BY clause to sort the result set either in ascending (default) or descending order.

Question 3

What is the default sort order of ORDER BY clause ?

Answer

The default sort order of ORDER BY clause is ascending order.

Question 4

Write an example query that sorts on three columns.

Answer

SELECT * FROM DATA
ORDER BY marks ASC, section DESC, term ASC; 

Question 5

Write a query that sorts the data of table student on the basis of Project-Group (in ascending order), section (in descending order), Marks (in descending order).

Answer

SELECT *
FROM student
ORDER BY Project_Group ASC, Section DESC, Marks DESC;

Question 6

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 7

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 8

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 9

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 10

Harjat has created the table EMP in his database.

Table : EMP

E_IDNameDeptComm
E001DityaAdmin35000
E002UzairProduction42500
E003RajnikantAdmin21000
E004MoushamiSales23575
E005SamanthaSales37000
E006SunderAdmin43000

Now he wants to find the sum of commission earned by each department. He has executed the following query :

SELECT dept, sum(comm)
GROUP BY dept
FROM EMP;

But, he got an error. Rewrite the correct query after identifying the error(s).

Answer

The error in Harjat's query is the order of the clauses. The GROUP BY clause should come after the FROM clause. The corrected query is as follows :

SELECT dept, sum(comm)
FROM EMP
GROUP BY dept;

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

Given the following table :

Table : STUDENT

No.NameStipendStreamAvgMarkGradeClass
1Karan400.00Medical78.5B12B
2Divakar450.00Commerce89.2A11C
3Divya300.00Commerce68.6C12C
4Arun350.00Humanities73.1B12C
5Sabina500.00Nonmedical90.6A11A
6John400.00Medical75.4B12B
7Robert250.00Humanities64.4C11A
8Rubina450.00Nonmedical88.5A12A
9Vikas500.00Nonmedical92.0A12A
10Mohan300.00Commerce67.5C12C

Give the output of following SQL statements :

(i) SELECT MIN(AvgMark) FROM STUDENT WHERE AvgMark < 75 ;

(ii) SELECT SUM(Stipend) FROM Student WHERE Grade = 'B' ;

(iii) SELECT AVG(Stipend) FROM Student WHERE Class = '12A' ;

(iv) SELECT COUNT(DISTINCT) FROM Student ;

Answer

(i)

Output
+--------------+
| MIN(AvgMark) |
+--------------+
| 64.4         |
+--------------+

(ii)

Output
+--------------+
| SUM(Stipend) |
+--------------+
|         1150 |
+--------------+

(iii)

Output
+--------------+
| AVG(Stipend) |
+--------------+
|          475 |
+--------------+

(iv) It will give an error because the COUNT function requires an argument specifying what to count. Additionally, the DISTINCT keyword is followed by a column name to count the distinct values of that column.

Question 12

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 13

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 14

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 15

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

Answer

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

Question 16

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 17

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 18

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 19

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 20

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 all customers (name) who have orders (use EXISTS).

Answer

SELECT first_name, last_name
FROM Customers c
WHERE EXISTS (
    SELECT first_name, last_name
    FROM Orders o
    WHERE o.customer_id = c.customer_id
);

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 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 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 where this sum is greater than $1000 grouped by customer (id) and state and ordered by state.

Answer

SELECT c.customer_id, c.state, SUM(o.amount)
FROM Customers c, orders o
WHERE c.customer_id = o.customer_id
GROUP BY c.customer_id, c.state
HAVING SUM(o.amount) > 1000
ORDER BY 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 their orders' details.

Answer

SELECT c.first_name, c.last_name, o.order_id, o.order_date, o.amount
FROM Customers c, Orders o
WHERE c.customer_id = o.customer_id;

Question 24

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 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 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 26

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;

Question 27

Give output for following SQL queries as per given table(s) :

Table : GARMENT

GCODEDescriptionPriceFCODEREADYDATE
10023PENCIL SKIRT1150F0319-DEC-08
10001FORMAL SHIRT1250F0112-JAN-08
10012INFORMAL SHIRT1550F0206-JUN-08
10024BABY TOP750F0307-APR-07
10090TULIP SKIRT850F0231-MAR-07
10019EVENING GOWN850F0306-JUN-08
10009INFORMAL PANT1500F0220-OCT-08
10017FORMAL PANT1350F0109-MAR-08
10020FROCK850F0409-SEP-07
10089SLACKS750F0331-OCT-08

Table : FABRIC

FCODETYPE
F04POLYSTER
F02COTTON
F03SILK
F01TERELENE

(i) SELECT SUM(PRICE) FROM GARMENT WHERE FCODE = 'F01' ;

(ii) SELECT DESCRIPTION, TYPE FROM GARMENT, FABRIC
WHERE GARMENT.FCODE = FABRIC.FCODE AND GARMENT.PRICE >= 1260 ;

(iii) SELECT MAX(FCODE) FROM FABRIC ;

(iv) SELECT COUNT(DISTINCT PRICE) FROM GARMENT ;

Answer

(i)

Output
+------------+
| SUM(PRICE) |
+------------+
|       2600 |
+------------+

(ii)

Output
+----------------+----------+
| DESCRIPTION    | TYPE     |
+----------------+----------+
| INFORMAL PANT  | COTTON   |
| INFORMAL SHIRT | COTTON   |
| FORMAL PANT    | TERELENE |
+----------------+----------+

(iii)

Output
+------------+
| MAX(FCODE) |
+------------+
| F04        |
+------------+

(iv)

Output
+-----------------------+
| COUNT(DISTINCT PRICE) |
+-----------------------+
|                     7 |
+-----------------------+

Question 28

Give output for following SQL queries as per given table(s) :

Table : PRODUCT

P_IDProductNameManufacturerPrice
TPO1Talcom PowderLAK40
FW05Face WashABC45
BS01Bath SoapABC55
SHO6ShampooXYZ120
FW12Face WashXYZ95

Table : CLIENT

C_IDClientNameCityP_ID
01Cosmetic ShopDelhiFW05
06Total HealthMumbaiBS01
12Live LifeDelhiSHO6
15Pretty WomanDelhiFW12
16DreamsBangaloreTP01

(i) SELECT DISTINCT City FROM Client ;

(ii) SELECT Manufacturer, MAX(Price), Min(Price), Count(*)
FROM Product GROUP BY Manufacturer ;

(iii) SELECT ClientName, ProductName
FROM Product, Client
WHERE Client.P_Id = Product.P_Id ;

(iv) SELECT ProductName, Price * 4 FROM Product ;

Answer

(i)

Output
+-----------+
| City      |
+-----------+
| Delhi     |
| Mumbai    |
| Bangalore |
+-----------+

(ii)

Output
+--------------+------------+------------+----------+
| Manufacturer | MAX(Price) | Min(Price) | Count(*) |
+--------------+------------+------------+----------+
| ABC          |         55 |         45 |        2 |
| XYZ          |        120 |         95 |        2 |
| LAK          |         40 |         40 |        1 |
+--------------+------------+------------+----------+

(iii)

Output
+---------------+---------------+
| ClientName    | ProductName   |
+---------------+---------------+
| Cosmetic Shop | Face Wash     |
| Total Health  | Bath Soap     |
| Live Life     | Shampoo       |
| Pretty Woman  | Face Wash     |
| Dreams        | Talcum Powder |
+---------------+---------------+

(iv)

Output
+---------------+-----------+
| ProductName   | Price * 4 |
+---------------+-----------+
| Bath Soap     |       220 |
| Face Wash     |       180 |
| Face Wash     |       380 |
| Shampoo       |       480 |
| Talcum Powder |       160 |
+---------------+-----------+

Question 29

Give output for following SQL queries as per given table(s) :

Table : ITEM

I_IDItemNameManufacturerPrice
PC01Personal ComputerABC35000
LC05LaptopABC55000
PC03Personal ComputerXYZ32000
PC06Personal ComputerCOMP37000
LC03LaptopPQR57000

Table : CUSTOMER

C_IDCustomerNameCityI_ID
01N RoyDelhiLC03
06H SinghMumbaiPC03
12R PandeyDelhiPC06
15C SharmaDelhiLC03
16K AgarwalBangalorePC01

(i) SELECT DISTINCT City FROM Customer ;

(ii) SELECT ItemName, MAX(Price), Count(*)
FROM Item GROUP BY ItemName ;

(iii) SELECT CustomerName, Manufacturer
FROM Item, Customer
WHERE Item.I_ID = Customer.I_ID ;

(iv) SELECT ItemName, Price * 100
FROM Item WHERE Manufacturer = 'ABC' ;

Answer

(i)

Output
+-----------+
| City      |
+-----------+
| DELHI     |
| MUMBAI    |
| BANGALORE |
+-----------+

(ii)

Output
+-------------------+------------+----------+
| ItemName          | MAX(Price) | Count(*) |
+-------------------+------------+----------+
| LAPTOP            |      57000 |        2 |
| PERSONAL COMPUTER |      37000 |        3 |
+-------------------+------------+----------+

(iii)

Output
+--------------+--------------+
| CustomerName | Manufacturer |
+--------------+--------------+
| N ROY        | PQR          |
| H SINGH      | XYZ          |
| R PANDEY     | COMP         |
| C SHARMA     | PQR          |
| K AGARWAL    | ABC          |
+--------------+--------------+

(iv)

Output
+-------------------+-------------+
| ItemName          | Price * 100 |
+-------------------+-------------+
| LAPTOP            |     5500000 |
| PERSONAL COMPUTER |     3500000 |
+-------------------+-------------+

Question 30

Give output for following SQL queries as per given table(s) :

Table : SENDER

SenderIDSenderNameSenderAddressSenderCity
ND01R Jain2, ABC ApptsNew Delhi
MU02H Sinha12, NewtownMumbai
MU15S Jha27/A, Park StreetMumbai
ND50T Prasad122-K, SDANew Delhi

Table : RECIPIENT

RecIDSenderIDRecNameRecAddressRecCity
KO05ND01R Bajpayee5, Central AvenueKolkata
ND08MU02S Mahajan116, A ViharNew Delhi
MU19ND01H Singh2A, Andheri EastMumbai
MU32MU15P K SwamyB5, C S TerminusMumbai
ND48ND50S Tripathi13, B1 D, Mayur ViharNew Delhi

(i) SELECT DISTINCT SenderCity FROM Sender ;

(ii) SELECT A.SenderName, B.RecName
FROM Sender A, Recipient B
WHERE A.SenderID = B.SenderID AND B.RecCity = 'Mumbai' ;

(iii) SELECT RecName, RecAddress FROM Recipient
WHERE RecCity NOT IN('Mumbai', 'Kolkata') ;

(iv) SELECT RecID, RecName FROM Recipient
WHERE SenderID = 'MU02' OR SenderID = 'ND50' ;

Answer

(i)

Output
+------------+
| SenderCity |
+------------+
| MUMBAI     |
| NEW DELHI  |
+------------+

(ii)

Output
+------------+-----------+
| SenderName | RecName   |
+------------+-----------+
| R JAIN     | H SINGH   |
| S JHA      | P K SWAMY |
+------------+-----------+

(iii)

Output
+------------+-----------------------+
| RecName    | RecAddress            |
+------------+-----------------------+
| S MAHAJAN  | 116, A VIHAR          |
| S TRIPATHI | 13, B1 D, MAYUR VIHAR |
+------------+-----------------------+

(iv)

Output
+-------+------------+
| RecID | RecName    |
+-------+------------+
| ND08  | S MAHAJAN  |
| ND48  | S TRIPATHI |
+-------+------------+
PrevNext