0% found this document useful (0 votes)
37 views

@G12-SQL QUESTIONS

The document contains a series of SQL questions and answers covering various SQL concepts, including the use of clauses like WHERE, HAVING, and ORDER BY, as well as functions for string manipulation and aggregate calculations. It includes practical examples of SQL queries for creating tables, inserting data, and retrieving information from databases. The content is structured as a quiz format, testing knowledge on SQL syntax and functionality.

Uploaded by

shaashu240309
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

@G12-SQL QUESTIONS

The document contains a series of SQL questions and answers covering various SQL concepts, including the use of clauses like WHERE, HAVING, and ORDER BY, as well as functions for string manipulation and aggregate calculations. It includes practical examples of SQL queries for creating tables, inserting data, and retrieving information from databases. The content is structured as a quiz format, testing knowledge on SQL syntax and functionality.

Uploaded by

shaashu240309
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

G12-SQL QUESTIONS

1. The purpose of WHERE clause in a SQL statement is to:


(A) Create a table
(B) Filter rows based on a specific condition
(C)Specify the columns to be displayed
(D)Sort the result based on a column
(B). Filter rows based on a specific condition
2. Identify the SQL command used to delete a relation (table) from a
relational Database.
(A) DROP TABLE
(B) REMOVE TABLE
(C)DELETE TABLE
(D)ERASE TABLE
(A). DROP TABLE
3. State whether the following statement is true or false:
In SQL, the HAVING clause is used to apply filter on groups formed by the
GROUP BY clause.
True
4. Match the following SQL functions/clauses with their descriptions:

(A) P-2, Q-4, R-3, S-1


(B) P-2, Q-4, R-1, S-3
(C)P-4, Q-3, R-2, S-1
(D)P-4, Q-2, R-1, S-3
(B). P-2, Q-4, R-1, S-3
5. Assertion (A): In SQL, INSERT INTO is a Data Definition Language (DDL)
Command.
Reason (R): DDL commands are used to create, modify, or remove database
structures, such as tables.
(D). Assertion (A) is False, but Reason (R) is True
6. Consider the string: "Database Management System". Write suitable SQL
queries for the following:
I. To extract and display "Manage" from the string.
II. Display the position of the first occurrence of "base" in the given string
I. SELECT SUBSTRING('Database Management System', 10, 6);
II. SELECT INSTR('Database Management System', 'base');
7. I. Write an SQL statement to create a table named STUDENTS, with the
following specifications:

II. Write SQL Query to insert the following data in the Students Table 1,
Supriya, Singh, 2010-08-18, 75.5
I. CREATE TABLE STUDENTS (StudentID NUMERIC PRIMARY
KEY,FirstName VARCHAR(20),LastName VARCHAR(10),DateOfBirth
DATE,Percentage FLOAT(10,2));
II. INSERT INTO STUDENTS VALUES (1, 'Supriya', 'Singh', '2010-08-
18',75.5);
8. Consider the following tables:
Table 1:
EMPLOYEE which stores Employee ID (EMP_ID), Employee Name (EMP_NAME),
Employee City (EMP_CITY)
Table 2:
PAYROLL which stores Employee ID (EMP_ID), Department (DEPARTMENT),
Designation (DESIGNATION), and Salary (SALARY) for various employees.
Note: Attribute names are written within brackets.
Table: EMPLOYEE
Write appropriate SQL queries for the following:
I. Display department-wise average Salary.
II. List all designations in the decreasing order of Salary.
III. Display employee name along with their corresponding departments
I. SELECT DEPARTMENT, AVG(SALARY) FROM PAYROLL GROUP BY
DEPARTMENT;
II. SELECT DESIGNATION FROM PAYROLL ORDER BY SALARY DESC;
III. SELECT EMP_NAME, DEPARTMENT FROM EMPLOYEE E, PAYROLL P
WHERE E.EMP_ID=P.EMP_ID;
9.

.
Write appropriate SQL queries for the following:
I. Display the sports-wise total number of medals won.
II. Display the names of all the Indian athletes in uppercase.
III. Display the athlete name along with their corresponding sports
I. SELECT SPORT,SUM(Medals) FROM MEDALS GROUP BY SPORT;
II. SELECT UPPER(Name) FROM ATHLETE WHERE COUNTRY = 'INDIA';
III. SELECT NAME, SPORT FROM ATHLETE A, MEDALS M WHERE
A.AthleteID= M.AthleteID;
10. Rahul, who works as a database designer, has developed a database for
a bookshop. This database includes a table BOOK whose column (attribute)
names are mentioned below:
BCODE: Shows the unique code for each book.
TITLE: Indicates the book’s title.
AUTHOR: Specifies the author’s name.
PRICE: Lists the cost of the book.

I. Write SQL query to display book titles in lowercase.


II. Write SQL query to display the highest price among the books.
III. Write SQL query to display the number of characters in each book title.
VI. Write SQL query to display the Book Code and Price sorted by Price in
descending order.
I. SELECT LOWER(TITLE) FROM BOOK;
II. SELECT MAX(PRICE) FROM BOOK;
III. SELECT LENGTH(TITLE) FROM BOOK;
IV. SELECT BCODE, PRICE FROM BOOK ORDER BY PRICE DESC;
11. Dr. Kavita has created a database for a hospital's pharmacy. The
database includes a table named MEDICINE whose column (attribute) names
are mentioned below:
MID: Shows the unique code for each medicine.
MED_NAME: Specifies the medicine name
SUPP_CITY: Specifies the city where the supplier is located.
STOCK: Indicates the quantity of medicine available.
DEL_DATE: Specifies the date when the medicine was delivered.
Write the output of the following SQL Queries.
I. Select LENGTH(MED_NAME) from MEDICINE where STOCK >100;
II. Select MED_NAME from MEDICINE where month(DEL_DATE)= 4;
III. Select MED_NAME from MEDICINE where STOCK between 120 and 200;
IV. Select max(DEL_DATE) from MEDICINE

12. Write suitable SQL query for the following:


I. To display the average score from the test_results column (attribute) in the
Exams table
II. To display the last three characters of the registration_number column
(attribute) in the Vehicles table. (Note: The registration numbers are stored in
the format DL-01-AV-1234)
III. To display the data from the column (attribute) username in the Users
table, after eliminating any leading and trailing spaces.
IV. To display the maximum value in the salary column (attribute) of the
Employees table.
V. To determine the count of rows in the Suppliers table.
I. SELECT AVG(test_results) FROM Exams;
II. SELECT RIGHT(registration_number, 3) FROM Vehicles;
III. SELECT TRIM(username) FROM Users;
IV. SELECT MAX(salary) FROM Employees;
V. SELECT COUNT(*) FROM Suppliers;
13. Write suitable SQL query for the following:
I. Round the value of pi (3.14159) to two decimal places.
II. Calculate the remainder when 125 is divided by 8.
III. Display the number of characters in the word 'NewDelhi'.
IV. Display the first 5 characters from the word 'Informatics Practices'.
V. Display details from 'email' column (attribute), in the 'Students' table, after
removing any leading and trailing spaces
I. SELECT ROUND(3.14159, 2);
II. SELECT MOD(125, 8);
III. SELECT LENGTH('NewDelhi');
IV. SELECT LEFT('Informatics Practices', 5);
V. SELECT TRIM(email) FROM Students;
14. Which of the following SQL functions does not belong to the Math
functions category?
i. POWER()
ii. ROUND()
iii. LENGTH()
iv. MOD()
iii. LENGTH ()
15. Predict the output of the following query: SELECT MOD (9,0);
i. 0
ii. NULL
iii. NaN
iv. 9
ii. NULL
16. 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?
i. SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5 GROUP BY DEPT;
ii. SELECT DEPT, AVG(SAL) FROM EMP HAVING COUNT(*) >5 GROUP BY DEPT;
iii. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT WHERE COUNT(*) > 5;
iv. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING COUNT(*) >
5;
iv. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING
COUNT(*) > 5;
17. Predict the output of the following query:
SELECT LCASE (MONTHNAME ('2023-03-05'));
i. May
ii. March
iii. may
iv. march
iv. march
18. With reference to SQL, identify the invalid data type.
i. Date
ii. Integer
iii. Varchar
iv. Month
iv. Month
19. In SQL, the equivalent of UCASE() is:
i. UPPERCASE ()
ii. CAPITALCASE()
iii. UPPER()
iv. TITLE ()
iii. UPPER( )
20. Consider the given SQL string:
“12#All the Best!”
Write suitable SQL queries for the following:
i. Returns the position of the first occurrence of the substring “the” in the
given string.
ii. To extract last five characters from the string
i. SELECT INSTR("12#All the Best!","the");
ii. SELECT RIGHT("12#All the Best!",5);
21. What are aggregate functions in SQL? Name any two.
Aggregate functions: These are also called multiple row functions.
These functions work on a set of records as a whole, and return a
single value for each column of the records on which the function is
applied. Max(), Min(), Avg(), Sum(), Count() and Count(*) are few
examples of multiple row functions
22.

i. Display fuel wise average sales in the first quarter.


ii. Display segment wise highest sales in the second quarter.
iii. Display the records in the descending order of sales in the second quarter.
Predict the output of the following queries based on the table CAR_SALES
given above:
i. SELECT LEFT(SEGMENT,2) FROM CAR_SALES WHERE FUEL= "PETROL";
ii.SELECT (QT2-QT1)/2 "AVG SALE" FROM CAR_SALES WHERE SEGMENT=
"SUV";
iii. SELECT SUM(QT1) "TOT SALE" FROM CAR_SALES WHERE FUEL= "DIESEL";
i. SELECT FUEL, AVG(QT1) FROM CAR_SALES GROUP BY FUEL;
ii. SELECT SEGMENT, MAX(QT2) FROM CAR_SALES GROUP BY
SEGMENT;
iii.SELECT * FROM CAR_SALES ORDER BY QT2 DESC;
23. Write MySQL statements for the following:
i. To create a database named FOOD.
ii. To create a table named Nutrients based on the following specification:

i. CREATE DATABASE FOOD;


ii. CREATE TABLE NUTRIENTS(NAME VARCHAR(20) PRIMARY
KEY,CALORIES INTEGER);
24. Preeti manages database in a blockchain start-up. For business purposes,
she created a table named BLOCKCHAIN. Assist her by writing the following
queries:

i. Write a query to display the year of oldest transaction.


ii. Write a query to display the month of most recent transaction.
iii. Write a query to display all the transactions done in the month of May.
iv. Write a query to count total number of transactions in the year 2022
i. SELECT YEAR(MIN(TRANSACTION_DATE)) FROM BLOCKCHAIN;
ii. SELECT MONTH(MAX(TRANSACTION_DATE)) FROM BLOCKCHAIN;
iii. SELECT * FROM BLOCKCHAIN WHERE
MONTHNAME(TRANSACTION_DATE)='MAY';
iv. SELECT COUNT(ID) FROM BLOCKCHAIN WHERE
YEAR(TRANSACTION_DATE)=2022;
25. Write suitable SQL queries for the following:
i. To calculate the exponent for 3 raised to the power of 4.
ii. To display current date and time.
iii. To round off the value -34.4567 to 2 decimal place.
iv. To remove all the probable leading and trailing spaces from the column
userid of the table named user.
v. To display the length of the string ‘FIFA World Cup’
i. SELECT POWER(3,4);
ii. SELECT NOW();
iii.SELECT ROUND(-34.4567,2);
iv. SELECT TRIM(USERID) FROM USER;
v. SELECT LENGTH("FIFA World Cup");
26. Kabir has created following table named exam:

Help him in writing SQL queries to the perform the following task:
i. Insert a new record in the table having following values: [6,'Khushi','CS',85]
ii. To change the value “IP” to “Informatics Practices” in subject column.
iii. To remove the records of those students whose marks are less than 30 .
iv. To add a new column Grade of suitable datatype.
v. To display records of “Informatics Practices” subject.
i. insert into exam values(6,'khushi','cs',85);
ii. update exam set subject= "informatics practices" where subject =
"ip";
iii. delete from exam where marks<30;
iv. alter table exam add column grade varchar(2);
v. select * from exam where subject="informatics practices";
27. Which type of values will not be considered by SQL while executing the
following statement? SELECT COUNT(column name) FROM inventory;
i. Numeric value
ii. text value
iii. Null value
iv. Date value
iii. Null value
28. If column “Fees” contains the data set (5000, 8000, 7500, 5000, 8000),
what will be the output after the execution of the given query?
SELECT SUM (DISTINCT Fees) FROM student;
i. 20500
ii. 10000
iii. 20000
iv. 33500
i. 20500
29. Which SQL statement do we use to find out the total number of records
present in the table ORDERS?
i. SELECT * FROM ORDERS;
ii. SELECT COUNT (*) FROM ORDERS;
iii. SELECT FIND (*) FROM ORDERS;
iv. SELECT SUM () FROM ORDERS;
ii. SELECT COUNT (*) FROM ORDERS;
30. Which one of the following is not an aggregate function?
i. ROUND()
ii. SUM()
iii. COUNT()
iv. AVG()
i. ROUND( )
31. Which one of the following functions is used to find the largest value from
the given data in MySQL?
i. MAX( )
ii. MAXIMUM( )
iii. BIG( )
iv. LARGE( )
i. MAX ()
32. In SQL, which function is used to display current date and time?
i. Date ()
ii. Time ()
iii. Current ()
iv. Now ()
iv. Now()
33. Rashmi, a database administrator needs to display house wise total
number of records of ‘Red’ and ‘Yellow’ house. She is encountering an error
while executing the following query:
SELECT HOUSE, COUNT (*) FROM STUDENT GROUP BY HOUSE WHERE
HOUSE=’RED’ OR HOUSE= ‘YELLOW’;
Help her in identifying the reason of the error and write the correct query by
suggesting the possible correction (s).
The problem with the given SQL query is that WHERE clause should
not be used with Group By clause.
To correct the error, HAVING clause should be used instead of
WHERE.
Corrected Query:
SELECT HOUSE, COUNT(*) FROM STUDENT GROUP BY HOUSE HAVING
HOUSE= ‘RED’ OR HOUSE=’YELLOW’;
34. What is the purpose of Order By clause in SQL? Explain with the help of
suitable example.
Order By clause:
The ORDER BY command is used to sort the result set in ascending
or descending order.
The following SQL statement displays all the customer’s names in
alphabetical order:
SELECT Cname FROM Customers ORDER BY Cname;
35. Write outputs for SQL queries (i) to (iii) which are based on the given table
PURCHASE:
i. 8
ii. No Output
iii. 0
15
36. Based on table STUDENT given here, write suitable SQL queries for the
following:

i. Display gender wise highest marks.


ii. Display city wise lowest marks.
iii. Display total number of male and female students.
i. select max(marks) from student group by gender;
ii. select min(marks) from student group by city;
iii. select gender,count(gender) from student group by gender;
37. Discuss the significance of Group by clause in detail with the help of
suitable example
GROUP BY clause is used in a SELECT statement in combination with
aggregate functions to group the result based on distinct values in a
column.
For example: To display total number of male and female students
from the table STUDENT, we need to first group records based on the
gender then we should count records with the help of count()
function.

38. Write suitable SQL query for the following:


i. Display 7 characters extracted from 7th left character onwards from the
string ‘INDIA SHINING’.
ii. Display the position of occurrence of string ‘COME’ in the string ‘WELCOME
WORLD’.
iii. Round off the value 23.78 to one decimal place.
iv. Display the remainder of 100 divided by 9.
v. Remove all the expected leading and trailing spaces from a column userid
of the table ‘USERS’.
i. select mid('INDIA SHINING',7,7);
ii. select INSTR('WELCOME WORLD','COME');
iii. select round(23.78,1);
iv. select mod(100,9);
v. select trim(userid) from users;
39. Explain the following SQL functions using suitable examples.
i. UCASE()
ii. TRIM()
iii. MID()
iv. DAYNAME()
v. POWER()
1. UCASE(): It converts the string into upper case.
Example:
SELECT UCASE(‘welcome world’);
Output:
WELCOME WORLD
2. TRIM(): It removes the leading and trailing spaces from the given
string.
Example:
SELECT TRIM(‘ Welcome world ‘ );
Output:
Welcome world
3. MID(): It extracts the specified number of characters from given
string.
Example:
SELECT MID(‘ Welcome world,4,,4);
Output:
Come
4. DAYNAME(): It returns the weekday name for a given date
Example:
SELECT DAYNAME(‘2022-07-22’);
Output:
Friday
5. POWER(): It returns the value of a number raised to the power of
another
number.
Example:
SELECT POW(6,2);
Output:
36
40. Shreya, a database administrator has designed a database for a clothing
shop. Help her by writing answers of the following questions based on the
given table:
TABLE: CLOTH

i. Write a query to display cloth names in lower case.


ii. Write a query to display the lowest price of the cloths.
iii. Write a query to count total number of cloths purchased of medium size.
iv. Write a query to count year wise total number of cloths purchased.
i. SELECT LOWER(CNAME) FROM CLOTH;
ii. SELECT MIN(PRICE) FROM CLOTH;
iii. SELECT COUNT(*) FROM CLOTH GROUP BY SIZE HAVING SIZE='M';
iv. SELECT YEAR(DOP),COUNT(*) FROM CLOTH GROUP BY YEAR(DOP)
41. Predict the output of the following queries:
i. Select power(5,3);
ii. Select mod(5,3);
Output:
i. 125
ii. 2
42. Briefly explain the purpose of the following SQL functions:
i. power()
ii. mod()
i. power(): It returns the value of a number raised to the power of
another number.
For example:
Select power(5,3);
Output: 125
ii. mod(): It returns the remainder of a number divided by another
number.
For example:
Select mod(5,3);
Output: 2
43. Help Reshma in predicting the output of the following queries:
i) select round(8.72,3);
ii) select round(9.8);
Output:
i) 8.720
ii) 10
44. Aryan, a database administrator, has grouped records of a table with the
help of group by clause.
He needs to further filter groups of records generated through group by
clause.
Suggest suitable clause for it and properly explain its usage with the help of
an example.
Having clause is used to further filter those groups of records which
will be generated through group by clause.
For example: Select max(marks) from student group by classes
having classes in (10,12);
Above given query will arrange records in groups according to the
classes. Further filtering on these groups will happen through having
clause, which will finally display the highest marks from classes 10
and 12.
45. Mr. Som, a HR Manager in a multinational company “Star-X world” has
created the following table to store the records of employees:

Predict the output


i) 2001 ii) Melinda
46. Based on the table given above, help Mr. Som writing queries for the
following task:
i) To display the name of eldest employee and his/her date of birth.
ii) To display the name of those employees whose joining month is May.
i) select ENAME,min(year(DOB)) from emp;
ii) select ENAME from emp where month(DOJ)=5;
47.Predict the output of the following queries:
i. select instr('[email protected]','.');
ii. select substr('[email protected]',7,4);
iii. select left('[email protected]',5);
i. 11
ii. cbse
iii. exams
48. Ms.Saumya is working on a MySQL table named ‘Hotel’ having following
structure:

She need to perform following task on the table:


i. To fetch last 2 characters from the user_id column.
ii. To display the values of name column in lower case.
iii. To display 3 characters from 3rd place from the column city.
Suggest suitable SQL function for the same. Also write the query to achieve
the desired task.
i. right()
select right(user_id,2) from hotel;
ii. lower()
select lower(name) from hotel;
iii. mid()/substr()/substring()
Select mid(city,3,3) from hotel;
49. Reena is working with functions of MySQL. Explain her following:
i. What is the purpose of now () function?
ii. How many parameters does it accept?
iii. What is the general format of its return type?
i. It returns the current date and time.
ii. None
iii. The return type for NOW() function is either in ‘YYYYMM-DD
HH:MM:SS’ format or YYYYMMDDHHMMSS.uuuuuu format,
depending on whether the function is used in a string or numeric
context.
50. While dealing with string data type in MySQL, its observed that
sometimes unnecessary space character comes in between which hampers
the successful execution of a string manipulation module. Name the suitable
MySQL function (s) to remove leading, trailing and both type of space
characters from a string. Also give MySQL queries to depict the same.
i. To remove leading space characters: ltrim()
ii. To remove trailing space characters: rtrim()
iii. To remove both type of space characters: trim()
MySQL Queries:
Select ltrim(‘ Hello ’);
Select rtrim(‘ Hello ’);
Select trim(‘ Hello ’);
Output:
Hello
51. Carefully observe the following table named ‘stock’:

Write SQL queries for the following:


(a) To display the records in decreasing order of price.
(b) To display category and category wise total quantities of products.
(c) To display the category and its average price.
(d) To display category and category wise highest price of the products.
(a) select * from stock order by price desc;
(b) select category, sum(qty) from stock group by category;
(c) select category,avg(price) from stock group by category;
(d) select category, max(price) from stock group by category;
52. Satyam, a database analyst has created the following table:
He has written following queries:
(a) select sum(MARKS) from student where OPTIONAL= ‘IP’ and STREAM=
‘Commerce’;
(b) select max(MARKS)+min(MARKS) from student where OPTIONAL= ‘CS’;
(c) select avg(MARKS) from student where OPTIONAL= ‘IP’;
(d) select length(SNAME) from student where MARKS is NULL;
Help him in predicting the output of the above given queries
Output: (a) 193
(b) 194
(c) 93.75
(d) 6
53. Based on the above given table named ‘Student’, Satyam has executed
following queries:
Select count(*) from student;
Select count(MARKS) from student;
Predict the output of the above given queries. Also give proper justifications
of the output generated through each query.
First query will produce the output 7.
Justification: count (*) will count and display total number of rows
(irrespective of any null value present in any of the column).
Second query will produce the output 6.
Justification: count (col_name) will count and display total number of
not null values in the specified column.
54. The avg() function in MySql is an example of ___________________.
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
Aggregate Function
55. The ____________command can be used to makes changes in the rows of a
table in SQL.
Update
56. Write the SQL command that will display the current time and date
Select now();
57.

a)

i. select name from student where class=’XI’ and class=’XII’;


ii. select name from student where not class=’XI’ and class=’XII’;
iii. select name from student where city=”Agra” OR city=”Mumbai”;
iv. select name from student where city IN(“Agra”,“Mumbai”);
Choose the correct option:
a. Both (i) and (ii).
b. Both (iii) and (iv).
c. Any of the options (i), (ii) and (iv)
d. Only (iii)
b) What will be the output of the following command? Select * from student
where gender =”F” order by marks;
c) Prachi has given the following command to obtain the highest marks Select
max(marks) from student where group by class;
but she is not getting the desired result. Help her by writing the correct
command.
a. Select max(marks) from student where group by class;
b. Select class, max(marks) from student group by marks;
c. Select class, max(marks) group by class from student;
d. Select class, max(marks) from student group by class;
d) State the command to display the average marks scored by students of each
gender who are in class XI?
i. Select gender, avg(marks) from student where class= “XI”group by gender;
ii Select gender, avg(marks) from student group by gender where class=”XI”;
iii. Select gender, avg(marks) group by gender from student having class=”XI”;
iv. Select gender, avg(marks) from student group by gender having class = “XI”;
Choose the correct option:
a. Both (ii) and (iii)
b. Both (ii) and (iv)
c. Both (i) and (iii)
d. Only (iii)
e) Help Ritesh to write the command to display the name of the
youngeststudent?
a. select name,min(DOB) from student ;
b. select name,max(DOB) from student ;
c. select name,min(DOB) from student group by name ;
d. select name,maximum(DOB) from student;
a) b. Both (iii) and (iv)
b) b.
c) d. Select class, max(marks) from student group by class;
d) b. Both (ii) and (iv)
e) b. select name,max(DOB) from student ;
58. State any two differences between single row functions and multiple row
functions.

59. What is the difference between the order by and group by clause when used
along with the select statement. Explain with an example.
The order by clause is used to show the contents of a table/relation in a
sorted manner with respect to the column mentioned after the order by
clause. The contents of the column can be arranged in ascending or
descending order.
The group by clause is used to group rows in a given column and then
apply an aggregate function eg max(), min() etc on the entire group.
60. Consider the decimal number x with value 8459.2654. Write commands in
SQL to:
i. round it off to a whole number
ii. round it to 2 places before the decimal.
i. select round(8459.2654);
ii.select round(8459.2654,-2);
61. 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.

This is because the column commission contains a NULL value and the
aggregate functions do not take into account NULL values. Thus
Command1 returns the total number of records in the table whereas
Command2 returns the total number of non NULL values in the column
commission.
62. Consider the following SQL string: “Preoccupied”
Write commands to display:
a. “occupied”
b. “cup”
a. select substr("Preoccupied", 4);
(or) select substring("Preoccupied", 4);
(Or) select mid("Preoccupied",4);
(or) select right(("Preoccupied"”, 8);
b. select substr("Preoccupied" ,6,3);
(or) select substring("Preoccupied", 6,3);
(Or) select mid(("Preoccupied" ,6,3);
63. Considering the same string “Preoccupied”
Write SQL commands to display:
a. the position of the substring ‘cup’ in the string “Preoccupied”
b. the first 4 letters of the string
a. select instr 'Preoccupied' , ‘ 'cup'));
b. select left 'Preoccupied',4);
64. A relation Vehicles is given below:

Write SQLcommands to:


a. Display the average price of each type of vehicle having quantity more than
20.
b. Count the type of vehicles manufactured by each company.
c. Display the total price of all the types of vehicles.
a. select Type, avg(Price) from Vehicle group by Type having Qty>20;
b. select Company, count(distinct Type) from Vehicle group by
Company;
c. Select Type, sum(Price* Qty) from Vehicle group by Type;
65. Write the SQL functions which will perform the following operations:
i) To display the name of the month of the current date .
ii) To remove spaces from the beginning and end of a string, “ Panorama “.
iii) To display the name of the day eg, Friday or Sunday from your date of birth,
dob.
iv) To display the starting position of your first name(fname) from your whole
name (name).
v) To compute the remainder of division between two numbers, n1 and n2
i) monthname(date(now()))
ii) trim(“ Panaroma “)
iii) dayname(date(dob))
iv)instr(name, fname)
v) mod(n1,n2)
66.

Write SQL queries using SQL functions to perform the following operations:
a) Display salesman name and bonus after rounding off to zero decimal places.
b) Display the position of occurrence of the string “ta” in salesman names.
c) Display the four characters from salesman name starting from second
character.
d) Display the month name for the date of join of salesman
e) Display the name of the weekday for the date of join of salesman
i) Select sname, round(bonus,0) from Salesman;
ii) Select instr(Sname, “ta”) from Salesman;
iii) Select mid(Sname,2,4) from Salesman; (or) iii) Select
Substring(Sname,2,4) from Salesman;
iv) Select monthname(DateofJoin) from Salesman;
v) Select dayname(DateofJoin) from Salesman;
67. What do you understand by Primary Key?
The attribute(column) or set of attributes(columns) which is used to
identify a tuple/ row uniquely is known as Primary Key
68. Write the command to delete a table STUDENT.
DROP TABLE STUDENT
69. NULL value means :
(i) 0 value
(ii) 1 value
(iii) None value
(iv) None of the above
(iii) None value
70. Shewani has recently started working in MySQL. Help her in understanding
the difference between the following :
(i) Where and having clause
(ii) Count(column_name) and count(*)
(i)Where clause is used to show data set for a table based on a
condition and having clause is used to put condition on the result set
that comes after using Group by clause.
(ii)COUNT(*) returns the number of items in a group, including NULL
values and duplicates. COUNT(expression) evaluates expression for
each row in a group and returns the number of non null values.
Candidate Key – A Candidate Key can be any column or a combination of
columns that can qualify as unique key in database. There can be
multiple Candidate Keys in one table. Each Candidate Key can qualify as
Primary Key. Primary Key – A Primary Key is a column or a combination
of columns that uniquely identify a record. Only one Candidate Key can
be Primary Key. A table can have multiple Candidate Keys that are
unique as single column or combined multiple columns to the table.
They are all candidates for Primary Key.
71. On the basis of following table answer the given questions:
(i) DELETE FROM CUSTOMER_DETAILS WHERE
CUST_NAME=’Manpreet’;
(ii) max(DOJ)
1998-02-
21
(iii)Delete from Customer_Details where Accumlt_Amt is NULL;
72. Write commands in SQL for (i) to (iii) and output for (iv) and (v).

(i) To display names of stores along with Sales Amount of those stores that are
located in Mumbai.
(ii) To display the details of store in alphabetical order of name.
(iii) To display the City and the number of stores located in that City, only if
number of stores is more than 2.
(iv) SELECT MIN(DATEOPEN) FROM STORE;
(v) SELECT COUNT(STOREID), NOOFEMP FROM STORE GROUP BY NOOFEMP
HAVING MAX(SALESAMT)<60000;
(i) SELECT NAME,SALESAMT FROM STORE WHERE CITY=’MUMBAI’;
(II) SELECT * FROM STORE ORDER BY NAME;
(III) SELECT CITY, COUNT(*) FROM STORE GROUP BY STORE HAVING
COUNT(*)>2;

73. Consider the table FANS and answer the following

Write MySQL queries for the following:


i. To display the details of fans in decending order of their DOB
ii. To display the details of FANS who does not belong to AJMER
iii. To count the total number of fans of each fan mode
iv. To display the dob of the youngest fan.
i. SELECT * FROM FANS ORDER BY FAN_DOB DESC;
ii. SELECT * FROM FANS WHERE FAN_CITY<>’AJMER’;
iii. SELECT FAN_MODE, COUNT(*) FROM FANS GROUP BY FAN_MODE;
iv. SELECT MAX(FAN_DOB) FROM FANS;
74. What is the purpose of SQL?
SQL is structured query language. It is a standard language of all the
RDBMS.
75. Mr. Manav, a database administrator in “Global Educational and Training
Institute” has created following table named “Training” for the upcoming training
schedule:
Help him in writing SQL query for the following purpose:
i. To count how many female candidates will be attending the training.
ii. To display list of free trainings.
iii. To display all the cities where Cyber Security training is scheduled along with
its fee.
iv. To add a column feedback with suitable data type
i. Select count(name) from training where name like ‘Ms.%’;
ii. Select * from training where fee is NULL;
iii. Select city, fee from training where topic = ‘Cyber Security’;
iv. Alter table training add feedback varchar(20);
76. Observe the table named “Training” given above carefully and predict the
output
of the following queries:
i. select city from training where topic = 'Cyber Security';
ii. select count(Training_Id) from training where email_id like '%gmail% ';
iii. select AVG (Fee) from training where Topic = 'Cyber Security';
iv. select name from training where INSTR (Email_Id, '@’)=0;
i. New Delhi
Faridabad
Gurugram
ii. 2
iii. 11000
iv. Ms. Neena
77. What is the degree and cardinality of the above given table named ‘Training’.
Degree: 6 , Cardinality: 5
77. Write any one similarity and one difference between primary key and unique
Constraint
Similarity: Column with both the constraints will only take unique values.
Difference: Column with Primary key constraints will not be able to hold NULL
values while Column with Unique constraints will be able to hold NULL values.
78. Consider the following tables Library given below:

i. Suggest the suitable data type for Issue_Date column.


ii. Suggest the suitable SQL command to change the size of column name from
30 character to 50 characters.
iii. Mention the significance of Bid column in table Library.
iv. Suggest the suitable command to display a list of the books in a sequence so
that first all the book’s name should be displayed which has been returned and
after that all the book’s name which has not been returned should be displayed.
i. Date
ii. alter table library modify name varchar(50);
iii. Bid column will always have a unique value which will help uniquely identify
each
record of Library table.
iv. Select name from library order by status desc;
79. Rishi, a class XII student has given following commands for the given
purposes:
i. To add a new column “Rating” :
update table library add column rating varchar(20);
ii. To give an increase of 50 Rs. to all the books:
alter library set price=price+50;
Check if above given SQL commands will be able to achieve desired task or not.
Justify your answer. Suggest the correction (s) if required.
Ans: No, above commands will not be able to achieve desired task as update and
alter commands have been interchanged.
In order to achieve desired result, following corrections should be incorporated in
the previously used commands:
i. To add a new column “Rating” :
Alter table library add column rating varchar(20);
ii. To give an increase of 50 Rs. to all the books:
Update library set price=price+50;
80. Write SQL query to create a table “BOOKS” with the following structure:

Create table Books ( BOOK_ID Integer (2) Primary Key, BOOK_NAME Varchar (20),
CATEGORY Varchar (20), ISSUE_DATE Date );
81. Help Ramesh in identifying any two columns for a table named student along
with their suitable data type.
Column Name Data Type
RollNo Integer
Name Varchar(20)
82.
(i) Identify the candidate keys of Customer table.
(ii) Briefly explain the concept of Candidate keys.
(i)Acc_No, Cust_Phone
(ii)All the columns having capability to become Primary Key are known
as Candidate Keys.
(iii) Which column can be considered as foreign key column in Transaction table?
(iv)Identify Primary Key column of Transaction table.
(iii)Acc_No
(iv)Trans_Id
83. Mention any two example of common Database Management System.
MySQL, Ingres, Postgres, Oracle etc.
84. Write the full forms of the following: i. DDL ii. DML
i. DDL-Data Definition Language ii. DML-Data Manipulation Language
85. Ms. Archana, a class XI student has just started learning MySQL. Help her in
understanding the basic difference between Alter and Update command with
suitable example.
Also suggest her suitable command for the following purpose:
i. To display the list of the databases already existing in MySQL.
ii. To use the database named City.
iii. To remove the pre-existing database named Clients.
iv. To remove all the records of the table named “Club” at one go along with its
structure permanently.
Suitable command:
i. Show Databases
ii. Use City
iii. Drop Database Clients
iv. Drop table Club
86. Observe the given table named “Loan” carefully and predict the output of the
following queries:
87. While creating a table named “Employee”, Mr. Rishi got confused as which
data type he should chose for the column “EName” out of char and varchar. Help
him in choosing the right data type to store employee name. Give valid
justification for the same.
Varchar would be the suitable data type for EName column as char data
type is a fixed length data type while varchar is a variable length data
type. Any employee‟s name will be of variable length so it‟s advisable
to choose varchar over char data type.
88. Ms. Shalini has just created a table named “Employee” containing columns
Ename, Department, Salary. After creating the table, she realized that she has
forgotten to add a primary key column in the table. Help her in writing SQL
command to add a primary key column empid. Also state the importance of
Primary key in a table.
SQL command to add a primary key column:
Alter table employee add empid int primary key;
Importance of Primary key in a table:
Primary key column is used to uniquely identify each record of the
table. A column defined as primary key cannot have a duplicate entry
and can‟t be left blank.
89.
i. To display the details of all those students who have IP as their optional
subject.
ii. To display name, stream and optional of all those students whose name starts
with „A‟.
iii. To give an increase of 3 in the average of all those students of humanities
section who have Maths as their optional subject.
iv. To display a name list of all those students who have average more than 75.
i. select * from student where optional=‟IP‟;
ii. select name, stream, optional from student where name like „A%‟;
iii. update student set average=average+3 where stream=‟Humanities‟
and optional=‟Maths‟;
iv. select name from student where average>75;
90. On the basis of the Table Student, write the output(s) produced by executing
the following queries:
i. Select max(average), min(average) from students group by stream having
stream like „Science‟;
ii. Select name from students where optional IN („CS‟,‟IP‟);

91.
Create table Registration ( Reg_Id Integer(2) Primary Key, Name
varchar(20), Course varchar(10), Join_Dt date );
92.

(i) Identify the primary key column of Train and Reservation.


Train-TrainId
Reservation-RefNo
(ii) Help Mr. Sajal in identifying the wrong statement with reference to UNION
clause:
a. Each SELECT statement within UNION must have the same number of columns
b. The columns must also have similar data types
c. The columns in each SELECT statement must also be in the same order
d. By default, the UNION operator selects all the values.
d. By default, the UNION operator selects all the values.
93. With reference to the above given tables, write commands in SQL for (i) and
(ii) and output for (iii) below:
i. To display the Train name along with its passenger name.
ii. To display Train detail which has no reservation yet.
iii. SELECT T.* from Train T, Reservation R where T.TrainId=R.TrainId AND Source
LIKE “%Delhi” OR Destination LIKE “%Delhi”;
i. select TName, Passenger from Train T, Reservation R where
T.TrainId=R.TrainId;
ii. i. select T.* from Train T, Reservation R where T.TrainId!=R.TrainId;

94. You have a table called "sales" that contains sales data for a retail store.
Which SQL aggregate function can be used to calculate the total number of rows
or records in the "sales" table?
a. MAX()
b. MIN()
c. AVG()
d. COUNT()
d. COUNT()
95. Attempt the following questions:
(i) Write a SQL query to calculate the remainder when 15 is divided by 4.
(ii) Write a SQL query to retrieve the current year.
(iii) Write a SQL query to extract the first three characters from the string 'Hello,
World!'.
(iv) Write a SQL query to convert the text in the 'description' column of the
'product' table to uppercase.
(v) Write a SQL query to display the position of '-' in values of ACC_NO column of
table Bank.
i. SELECT MOD(15, 4) AS Remainder;
ii. SELECT YEAR(NOW()) AS CurrentYear;
iii. SELECT LEFT('Hello, World!', 3) AS ExtractedString;
iv. SELECT UPPER(description) AS UppercaseDescription FROM product;
v. SELECT INSTR(acc_no, '-') FROM bank;
96.
i) ACC_NO as it is present in both the tables having related values.
ii) SELECT C.CUSTOMER_NAME, B.AMOUNT FROM CUSTOMER C
JOIN BANK B ON C.ACC_NO = B.ACC_NO ORDER BY B.AMOUNT ASC;
iii) SELECT SUM(AMOUNT) AS TOTAL_AMOUNT FROM BANK;
iv) SELECT COUNT(*) from CUSTOMER;
v) SELECT MIN(AMOUNT) from BANK;
97. Imagine you are assigned a task to manage the inventory of an online store.
The store uses an SQL database to track product information in a table named
'Products.' The 'Products' table has columns for 'ProductID' (Primary Key),
‘ProductName', ‘Category’, 'QuantityInStock,' and 'PricePerUnit.' The following
scenarios represent different inventory management tasks:
i) Restocking: Due to a recent sale, the 'QuantityInStock' of a product
with 'ProductID' 101, named "Laptop," needs to be increased by 10 units.
ii) Product Availability Check: You need to check the availability of a product
named "Wireless Mouse" in the 'Electronics' category.
iii) Product Update: The price of all products in the 'Electronics' category should
be increased by 5% to account for market changes.
iv) Out of Stock: Identify and list the products that are currently out of stock
(QuantityInStock is 0).
For each scenario, provide the SQL statements to perform the necessary action.
i) UPDATE Products SET QuantityInStock = QuantityInStock + 10 WHERE
ProductID = 101;
ii) SELECT * FROM Products WHERE ProductName = 'Wireless Mouse'
AND Category = 'Electronics';
iii) UPDATE Products SET PricePerUnit = PricePerUnit * 1.05 WHERE
Category = 'Electronics';
iv) SELECT ProductName FROM Products WHERE QuantityInStock = 0;
98. Suppose you already have “Nutrients" table in the "FOOD" database, as
described
below:
Table Name: Nutrients
Column Name: Food_Item (VARCHAR)
Column Name: Calorie (INT)
Write SQL statements to perform the following tasks:
i. Add a new column named “Plan_Start_Date” (Date) to the "Nutrients" table.
ii. ii. Modify the "Calorie" column to change its data type to Float
i: ALTER TABLE Nutrients ADD Plan_Start_Date DATE;
ii: ALTER TABLE Nutrients MODIFY Calorie FLOAT;
99. Clarify the role of the HAVING clause highlighting its distinctions from the
WHERE clause in SQL.
HAVING clause in SQL is used to filter the results of a GROUP BY query
based on aggregated values. Distinction of having clause from where
clause: The WHERE clause is applied to individual rows in the original
dataset before any grouping is performed. It filters rows based on
specific column conditions. While HAVING clause is applied to grouped
results after the GROUP BY operation. Itfilters groups based on
aggregated values,such as SUM, COUNT, AVG, etc.
100. Consider the given SQL QUERIES:
i. To retrieve the length of the given string "CBSE BOARD SQP @ 2023!", which
SQL function should you use?
a. LCASE()
b. MID()
c. LENGTH()
d. TRIM()
ii. To findout if ‘@’ symbol is present in the values of email id column or not,
which function out of the following should be used?
a. Find()
b. Instr()
c. FindStr()
d. OnStr()
i. c. LENGTH() ii. b. Instr()

You might also like