Informatics Practices Review of MySQL
Informatics Practices Review of MySQL
Informatics Practices
Class-XII
REVIEW OF MySQL
DBMS: Data Base Management System is a collection of interrelated data and a set of program to
access those data. This collection of data is called the database.
Table: A database table is a collection of rows and columns which describes the basic storage
structure of RDBMS.
Primary Key: Primary Key is a set of one or more attributes that uniquely identifies each row in a
table. The Primary Key column can not contain null value.
Candidate Key: A candidate key is the one that is capable of becoming primary key.
Alternate Key: A candidate key that is not primary key is called alternate key.
Foreign Key: A non key attribute is called foreign key if it is a primary key of another table.
DDL: DDL is the part of SQL. It stands for Data Definition Language. It provides statements for
creation, modification and deletion of the database. For example CREATE, DROP, ALTER etc.
DML: DML is the part of SQL. It stands for Data Manipulation Language. It provides statements for
manipulating the database. For example SELECT, INSERT etc.
Accessing/selecting Database:
Command: USE
Syntax: USE database-name;
Example: USE xiiip;
Create Database:
Command: CREATE DATABASE
Syntax: CREATE DATABASE database-name;
Example: CREATE DATABASE xiiip;
Dropping Database:
Command: DROP DATABASE
Syntax: DROP DATABASE database-name;
Example: DROP DATABSE xiiip;
Creating Table:
Command: CREATE TABLE
Syntax: CREATE TABLE table-name(
column-name data-type<COLUMN CONSTRAINT>,
....
....
PRIMARY KEY(column-name,......));
Example: CREATE TABLE employee(
ecode integer NOT NULL,
ename varchar(20) NOT NULL,
sex char(1),
grade char(2) DEFAULT ‘E1’,
gross decimal,
deptcode char(4),
CHECK(gross>2000),
PRIMARY KEY(ecode),
FOREIGN KEY(deptcode) REFERENCES department(deptcode));
Describing Table:
Command: DESC
Syntax: DESC table-name; or DESCRIBE table-name;
Example: DESC employee; or DESCRIBE employee;
Altering Table:
Command: ALTER TABLE
Syntax for remove column: ALTER TABLE table-name DROP COLUMN column–name;
Example: ALTE TABLE employee DROP COLUMN grade;
Syntax for add column: ALTER TABLE table-name ADD COLUMN column-name datatype(length);
Example: ALTER TABLE employee ADD COLUMN grade char(2);
Syntax for changing an existing column:
ALTER TABLE table-name CHANGE [old column-name] [new column-name] datatype;
Example: ALTER TABLE table-name CHANGE grade score char(2);
Syntax for resize a column: ALTER TABLE table-name MODIFY column-name datatype(length);
Example: ALTER TABLE employee MODIFY enamevarchar(25);
Remove a table:
Command: DROP TABLE
Syntax: DROP TABLE table-name;
Example: DROP TABLE employee;
Page 3 of 16
Use search condition to specify the rows you want to retrieve from the table:
Command: WHERE
Syntax: SELECT * FROM table-name WHERE condition;
Example: SELECT * FROM employee WHERE grade=’A’;
Retrieve information from the table where the values of a column belong to a specified range:
Command: BETWEEN
Syntax: SELECT * FROM table-name WHERE column-name BETWEEN value1 AND value2;
Example: SELECT * FROM employee WHERE ecode BETWEEN 100 AND 123;
Pattern Matching:
Command: LIKE
Syntax: SELECT * FROM table-name WHERE column-name LIKE condition-based-on-pattern;
Example: SELECT * FROM employee WHERE grade LIKE ‘E%’;
Retrieve information from the table where the values of a column belong to a specified list:
Command: IN
Syntax: SELECT * FROM table-name WHERE column-name in (value 1, value 2,...., value n);
Example: SELECT * FROM employee WHERE grade IN (‘E1’,’E3’,’E5’);
SELECT * FROM employee WHERE grade NOT IN (‘E1’,’E3’,’E5’);
Aggregate Functions:
1. Calculate the average of a specified column:
Name of the function: AVG
Syntax: SELECT AVG(column-name) FROM table-name;
Example: SELECT AVG(gross) FROM employee;
Sorting Results:
Command: ORDER BY
Syntax: SELECT column-name1 [,column-name2,...] FROM table-name [WHERE <condition>]
ORDER BY column-name [ASC/DESC];
Example: SELECT * FROM employee;
SELECT ename, gross FROM employee WHERE gross>5000
ORDERBY ename DESC;
Group the rows in the result table by columns that have the same values, so that each group is
reduced to a single row:
Command: GROUP BY
Syntax: SELECT column-name1, column-name2,.... FROM table-name
GROUP BY column-name;
Example: SELECT grade, AVG(gross) FROM employee GROUP BY grade;
Apply condition to restrict grouped rows that appear in the result table:
Command: HAVING
Syntax: SELECT column-name1, column-name2, .... FROM table-name
GROUP BY column-name HAVING column-name CONDITION value;
Example: SELECT grade, AVG(gross) FROM employee GROUP BY grade
HAVING AVG(gross)>5000;
Column Alias:
Command: AS
Syntax: SELECT column-name AS alias-name FROM table-name;
Example: SELECT ename AS EmployeeName FROM employee;
Page 5 of 16
MySQL Functions
LCASE / LOWER:
Description: Converts a string into lower case.
Syntax: LOWER(str) or LCASE(str)
Example: SELECT LOWER(“INDIA”); or SELECT LCASE(“INDIA”);
SELECT LOWER(ename) FROM employee;
SELECT LCASE(ename) FROM employee;
UCASE / UPPER:
Description: Converts a string into upper case.
Syntax: UPPER(str) or UCASE(str)
Example: SELECT UCASE(“india”); or SELECT UPPER(“india”);
SELECT UPPER(ename) FROM employee;
SELECT UCASE(ename) FROM employee;
RIGHT:
Description: Return length number (length is given by the user) of rightmost characters from
the given string.
Syntax: RIGHT(str,length)
Example: SELECT RIGHT(“Informatics”,4); Output: tics
SELECT RIGHT(ename,3) FROM employee;
LEFT:
Description: Return length number (length is given by the user) of leftmost characters from the
given string.
Syntax: LEFT(str,length)
Example: SELECT LEFT(“Informatics”,4); Output: Info
SELECT LEFT(ename,3) FROM employee;
CONCAT:
Description: Concatenates two or more strings.
Syntax: CONCAT(str1,str2,….)
Example: SELECT CONCAT(“In”,”for”,”matics”); Output: Informatics
SELECT CONCAT(“Employee Code Of Mr ”,ename,” is “,ecode) FROM
employee;
SUBSTR:
Description: Returns substring, whose length len characters from a given string str and it is
started at position pos.
Syntax: SUBSTR(str,pos,len)
Example: SELECT SUBSTR(“Informatics”,6,3); Output: mat
SELECT SUBSTR(“Informatics”,6); Output: matics
SELECT SUBSTR(ename,2,3) FROM employee;
MID:
Description: Same as SUBSTR Function.
Syntax: MID(str,pos,len)
Example: MID(str,pos,len)
Example: SELECT MID(“Informatics”,6,3); Output: mat
SELECT MID(“Informatics”,6); Output: matics
SELECT MID(ename,2,3) FROM employee;
LENGTH:
Description: Returns the length of the given string.
Syntax: LENGTH(str)
Example: SELECT LENGTH(“Informatics”); Output: 11
SELECT LENGTH(ename) FROM employee;
Page 6 of 16
LTRIM:
Description: Removes leading spaces from a given string.
Syntax: LTRIM(str)
Example: SELECT LTRIM(“ Informatics”); Output: Informatics
SELECT LTRIM(ename) FROM employee;
RTRIM:
Description: Removes trailing spaces from a given string.
Syntax: RTRIM(str)
Example: SELECT RTRIM(“Informatics ”); Output: Informatics
SELECT RTRIM(ename) FROM employee;
TRIM:
Description: Removes leading and trailing spaces from a given string.
Syntax: TRIM( [ {BOTH | LEADING | TRAILING} [remstr] from] str)
or
TRIM( [remstr FROM] str)
Example: SELECT TRIM(“ India “); Output: India
SELECT TRIM(LEADING “x” FROM “xxxxxIndiaxxxxx”); Output: Indiaxxxxx
SELECT TRIM(TRAILING “x” FROM “xxxxxIndiaxxxxx”); Output: xxxxxIndia
SELECT TRIM(BOTH “x” FROM “xxxxxxIndiaxxxxx”); Output: India
INSTR:
Description: Return the position of first occurrence of a substring in a string.
Syntax: INSTR(str,substr)
Example: SELECT INSTR(“Kendriya Vidyalaya”,”ya”); Output: 7
SELECT INSTR(ename,”a”) FROM employee;
MOD:
Description: Returns modulus (Remainder) of given two numbers.
Syntax: MOD(value, divisor) or value % divisor or value mod divisor
Example: SELECT MOD(15,2); Output: 1
POWER / POW:
Description: Returns mn.
Syntax: POWER(m,n) or POW(m,n)
Example: SELECT POW(5,3); Output: 125
ROUND:
Description: Returns round off value of a given number (e.g. n) and it rounded up to a given
place (e.g. m). If m is omitted, it is considered as 0. m can be negative to round
off digits left of the decimal point. m must be an integer.
Syntax: ROUND(n [,m])
Example: SELECT ROUND(12345.9012); Output: 12346
SELECT ROUND(201.193,1); Output: 201.2
SELECT ROUND(12357.9021,-2); Output: 12400
SELECT ROUND(12347.9021,-2); Output: 12300
SELECT ROUND(12344.9021,-1); Output: 12340
SELECT ROUND(12347.9021,-1); Output: 12350
SQRT:
Description: Returns square root of given number.
Syntax: SQRT(n)
Example: SELECT SQRT(25); Output: 5
TRUNCATE:
Description: Returns a number with some digits truncated.
Syntax: TRUNCATE(n,m)
Page 7 of 16
CURDATE / CURRENT_DATE
Description: Returns the current date as a value in YYYY-MM-DD or YYYYMMDD format,
depending on whether the function is used in a string or numeric context.
Syntax: CURDATE() or CURRENT_DATE() or CURRENT_DATE
Example: SELECT CURDATE(); Output: 2015-01-08
SELECT CURDATE() + 10; Output: 20150118
DATE:
Description: Extracts the date part of date or datetime expression.
Syntax: DATE(expr)
Example: SELECT DATE(‘2015-01-08 01:12:35’); Output: 2015-01-08
MONTH:
Description: Extracts the month part from date.
Syntax: MONTH(date)
Example: SELECT MONTH(‘2015-01-08’); Output: 01
YEAR:
Description: Extracts the year part from date.
Syntax: YEAR(date)
Example: SELECT YEAR(‘2015-01-08’); Output: 2015
DAYNAME:
Description: Returns the name of the weekday from date.
Syntax: DAYNAME(date)
Example: SELECT DAYNAME(‘2015-01-08’); Output: Thursday
DAYOFMONTH:
Description: Returns of the day of the month from date.
Syntax: DAYOFMONTH(date)
Example: SELECT DAYMONTH(‘2015-01-08’); Output: 08
DAYOFWEEK:
Description: Returns of the weekday index for date (1=Sunday, 2=Monday...., 7=Saturday).
Syntax: DAYOFWEEK(date)
Example: SELECT DAYOFWEEK(‘2015-01-08’); Output: 05
DAYOFYEAR:
Description: Returns of the day of the year from date.
Syntax: DAYOFYEAR(date)
Example: SELECT DAYOFYEAR(‘2015-02-08’); Output: 39
NOW:
Description: Returns the current date and time.
Syntax: NOW()
Example: SELECT NOW(); Output:
SYSDATE:
Description: Returns the time at which the function executes.
Syntax: SYSDATE()
Example: SELECT SYSDATE();
Page 8 of 16
1. What MySql command will be used to open an already existing database “LIBRARY”? Delhi-11
Ans: USE LIBRARY;
3. A table “TRAINS” in a database has degree 3 and cardinality 8. What is the number of rows and
columns in it? 2
Ans: Rows=8 and Columns=3.
5. Sarthya, a student of class xi, created a table ‘RESULT’. Grade is one of the column of this
table. To find the details of students whose Grades have not been entered, he wrote the
following MySql query, which did not give the desired result.
SELECT * FROM RESULT WHERE Grade=’Null’;
Help Sarthya to run the query by removing the errors from the query and write the correct
Query. 2
Ans: SELECT * FROM RESULT WHERE Grade IS Null;
6. Write MySql command to display the list of existing databases. Delhi 2012 1
Ans: SHOW DATABASES;
7. Mr. William wants to remove all the rows from Inventory table to release the storage space, but
he does not want to remove the structure of the table. What MySql statement should he use?1
Ans: DELETE FROM Inventory;
8. A table FLIGHT has 4 rows and 2 columns and another table AIRHOSTESS has 3 rows and 4
columns. How many rows and columns will be there if we obtain the Cartesian product of these
two tables? 1
Ans: Rows = 4 rows of FLIGHT × 3 rows of AIRHOSTESS = 12 rows.
Columns = 2 columns of FLIGHT + 4 columns of AIRHOSTESS = 6 columns.
Page 9 of 16
10. Mr. Sondhi created two tables with DEPTNO as primary key in Table1 and foreign key in
Table2. While inserting a row in Table2, Mr. Sondhi is not able to enter a value in the column
DEPTNO. What could be the possible reason for it? 2
Ans: The possible reason could be the DEPTNO being entered in Table2 is not present in
Table1 i.e. the referential integrity is imposed.
11. Write a command to add a NOT NULL constraint on Fees column of a Student table. 1
Ans: ALTER TABLE Student MODIFY Fees INTEGER NOT NULL;
13. Table BANK has 2 rows and 3 columns. Table CUSTOMER has 4 rows and 3 columns. What
will be the cardinality and degree of the Cartesian product of them? 1
Ans: Cardinality = Rows = 2 rows of BANK × 4 rows of CUSTOMER = 8 rows.
Degree = Columns = 3 columns of BANK + 3 columns of CUSTOMER = 6 columns.
14. There is a column HOBBY in a Table CONTACTS. The following two statements are giving
different outputs. what may be the possible reason? 2
SELECT COUNT(*) FROM CONTACTS;
SELECT COUNT(HOBBY) FROM CONTACTS;
Ans: They are giving different values because there exist NULL values in the column HOBBY
of the table CONTACTS.
15. Mr. Tandon is using table EMP with the following columns. 2
ECODE, DEPT, ENAME, SALARY
He wants to display all information of employees (from EMP table) in ascending order of
ENAME and within it in ascending order of DEPT. He wrote the following command, which did
not show the desired output.
SELECT * FROM EMP ORDER BY NAME DESC, DEPT;
Rewrite the above query to get the desired output.
Ans: SELECT * FROM EMP ORDER BY NAME, DEPT;
18. Table ‘Club' has 4 rows and 3 columns. Table ‘Member’ has 2 rows and 05 columns. What will
be the cardinality of the Cartesian product of them? 1
Ans: Cardinality = No of Rows = 4 rows of Club Table × 2 rows of Member Table = 8
19. A numeric data field CHANGER contains 25565.7765. Write a commands round off CHANGER
to (i) up to 2 decimal places (i.e., expected result 25565.78) (ii) whole number (i.e., expected
result 25566) 2
Ans: (i) SELECT ROUND(25565.7765,2);
Page 10 of 16
20. Gopi Krishna is using a table Employee. It has the following columns:
Code, Name, Salary, Deptcode
He wants to display maximum salary department wise. He wrote the following command
SELECT Deptcode, MAX(Salary) FROM Employee;
But he did not get the desired result. Rewrite the above query with necessary changes to help
him get the desired output.
Ans: SELECT Deptcode, MAX(Salary) FROM Employee GROUP BY Deptcode;
1. What is the purpose of DROP TABLE command in MySql? How is it different from DELETE
command? 2
Ans: The DROP TABLE command is used to remove a table from the database, and also
removes all of its data. The DELETE command only deletes rows from a MySQL
database but the table remain in the database.
2. Table Employee has 4 records and Table Dept has 3 records in it. Mr. Jain wants to display all
information stored in both of these related tables. He forgot to specify equi-join condition in the
query. How many rows will get displayed on execution of this query? 1
Ans: 20 rows will get displayed.
Consider the table RESULT given below Write commands in MySql for (i) to (iv) and output for
(v) to (vii):
(i) To list the names of those students, who have obtained Division as FIRST in the ascending
order of Name. 1
(ii) To display a report listing NAME, SUBJECT and Annual stipend received assuming that the
stipend column has monthly stipend. 1
(iii) To count the number of students, who have either Accounts or Informatics as Subject. 1
(iv) To insert a new row in the table Result: 7, "Mohan", 500, "English", 73, "Second"; 1
(v) SELECT AVG (Stipend) FROM Result WHERE DIVISION = "THIRD";
(vi) SELECT COUNT(DISTINCT Subject) FROM Result;
(vii) SELECT MIN(Average) FROM Result WHERE Subject = "English";
Ans: (i) SELECT Name FROM Result WHERE Division=’FIRST’ ORDER BY Name;
(ii) SELECT Name, Subject, Stipend*12 AS ‘Annual Stipend’ FROM Result;
(iii) SELECT COUNT(*) FROM Result WHERE Subject=’Accounts’ OR
Subject=’Informatics’;
(iv) INSERT INTO Result VALUES (7, "Mohan", 500, "English", 73, "Second");
(v) AVG(Stipend)
475
(vi) COUNT(DISTINCT Subject)
6
Page 11 of 16
(vii) MIN(Average)
38
3. Write a MySQL command for creating a table "PAYMENT" whose structure is given below: 2
4. In a database there are two tables "Product" and "Client" as shown below: 2
5. In a Database School there are two tables Member and Division as show below.
6. What is the purpose of of GROUP BY clause in MySQL? How is it different from OREDER BY
clause? 2
Ans: GROUP BY – It is used to combine all those records that have identical value in a
particular field or a group of fields.
ORDER BY – It is used to display the records either in ascending or descending order
based on a particular field.
7. Table Hospital has 4 rows and 5 columns. What is the cardinality and degree of this table?
Ans: Cardinality = Number of rows = 4.
Degree = Number of columns = 5.
8. Consider the table SHOPPE given below. Write command in MySQL for (i) to (iv) and output for
(v) to (vii).
Page 13 of 16
(i) To display names of the items whose name starts with ‘C’ in ascending order of Price? 1
(ii) To display Code, Item name, and City of the products whose quantity is less than 100. 1
(iii) To count distinct Company from the table. 1
(iv) To insert a new row in the table Shoppe
‘110’,’Piza’,’Papa Jones’,120,’Kolkata’,50.0 1
(v) SELECT Item FROM Shoppe WHERE Item IN (‘Jam’,’Coffee’); 1
(vi) SELECT COUNT (DISTINCT (City)) FROM SHOPPE; 1
(vii) SELECT MIN(Qty) FROM SHOPPE WHERE City=’Mumbai’; 1
Ans: (i) SELECT Item FROM SHOPPE WHERE Item LIKE ‘C%’ ORDER BY Price;
(ii) SELECT Item, City FROM SHOPPE WHERE Qty<100;
(iii) SELECT COUNT(DISTINCT(Company)) FROM SHOPPE;
(iv) INSERT INTO SHOPPE VALUES (‘110’,’Piza’,’Papa Jones’,120,’Kolkata’,50.0);
(v) Item
Jam
Coffee
(vi) COUNT(DISTINCT(Company))
6
(vii) MIN(Qty)
56
9. Write MySQL command to create the Table STOCK including its constraints. 2
12. State difference between date functions NOW( ) and SYSDATE( ) of MySql. 2
Ans: SYSDATE( ) returns the time at which it executes. This differs from the behaviour for
NOW(), which returns a constant time that indicates the at which the statement began to
execute.
Example:
13. Name a function of MySql which is used to remove trailing and leading spaces from a string. 1
Ans: TRIM()
Page 15 of 16
14. Consider the following table named “SBOP” with details of account holders. Write commands of
MySQL for (i) to (iv) and output for (v) to (vi). 7
(i) To display Accountno, Name and DateOfopen of account holders having transactions more
than 8.
(ii) To display all information of account holders whose transaction value is not mentioned.
(iii) To add another colurnn Address with datatype and size as VARCHAR(25).
(iv) To display the month day with reference to DateOfopen for all the account holders.
(v) SELECT Count(*) FROM SBOP;
(vi) SELECT Name, Balance FROM SBOP WHERE Name LIKE "%i";
(vii) SELECT ROUND(Balance, -3) FROM SBOP WHERE Accountno=”SB- 5";
Ans: (i) SELECT Accountno, Name, DateOfopen FROM SBOP WHERE Transaction>8;
(ii) SELECT * FROM SBOP WHERE Transaction IS NULL;
(iii) ALTER TABLE SBOP ADD (Address varchar(25));
(iv) SELECT DAYOFMONTH(Dateofopen) FROM SBOP;
(v) COUNT(*)
5
(vi) Name Balance
Mrs.Sakshi 45000.00
(vii) ROUND(Balance, -3)
63000
15. Write MySql command to create the table SHOP with given structure and constraint : 2
16. In a Database Multiplexes, there are two tables with the following data. Write MySQL queries
for (i) to (iii), which are based on TicketDetails and AgentDetails :
(i) To display Tcode, Name and Aname of all the records where the number of tickets sold is
more than 5.
(ii) To display total number of tickets booked by agent “Mr. Ayush”.
(iii) To display Acode, Aname and corresponding Tcode where Aname ends with 'k'.
Ans: (i) SELECT Tcode, Name, Aname FROM TicketDetails t, AgentDetails a WHERE
a.Acode=t.Acode;
(ii) SELECT SUM(Tickets) FROM TicketDetails t, AgentDetails a WHERE
a.Acode=t.Acode AND Aname=’Mr. Ayush’;
(iii) SELECT Acode, Aname, Tcode FROM TicketDetails t, AgentDetails a WHERE
a.Acode=t.Acode and Aname LIKE ‘%K’;
17. With reference to “TicketDetails” table, which column is the primary key ? Which column is the
foreign key? Give reason(s).
Ans: Primary Key: Tcode
Foreign Key: Acode