@G12-SQL QUESTIONS
@G12-SQL QUESTIONS
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.
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:
a)
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 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;
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.
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()