2nd pu notes

2nd PUC Computer Science Chapter 9 SQL Notes | Structured Query Language

Venkatesh A September 6, 2026 32 min read
2nd PUC Computer Science Chapter 9 SQL Notes | Structured Query Language
2nd PUC / Class XII Computer Science

Complete Short Notes & Exam Preparation Guide

Based on the NCERT textbook

verakworld.com

Table of Contents

  1. 9.1 Introduction
  2. 9.2 Structured Query Language (SQL)
  3. 9.3 Data Types and Constraints in MySQL
  4. 9.4 SQL for Data Definition
  5. 9.5 SQL for Data Manipulation
  6. 9.6 SQL for Data Query
  7. 9.7 Data Updation and Deletion
  8. 9.8 Functions in SQL
  9. 9.9 GROUP BY Clause in SQL
  10. 9.10 Operations on Relations
  11. 9.11 Using Two Relations in a Query
  12. Chapter Summary
  13. Questions & Answers
  14. Important Questions
  15. Quick Revision
verakworld.com

9.1 Introduction

Relational Database Management Systems (RDBMS) are used to create databases consisting of relations. Examples mentioned in the textbook include MySQL, Microsoft SQL Server, PostgreSQL and Oracle.

These systems allow users to store, retrieve and manipulate data in a database through queries. This chapter explains how to create, populate and query databases using MySQL.

Exam Point: The chapter focuses on creating databases, storing data, manipulating data and retrieving data through SQL queries.
verakworld.com

9.2 Structured Query Language (SQL)

SQL: Structured Query Language (SQL) is a query language used with database management systems to access and manipulate data from a database.

In a file system, application programs are required to access data. Database management systems provide special languages called query languages for accessing and manipulating database data.

SQL is widely used with relational database management systems such as MySQL, ORACLE and SQL Server.

Important Features of SQL

  • SQL statements comprise descriptive English words.
  • SQL is not case sensitive.
  • It allows us to create and interact with a database.
  • We specify what data is to be retrieved rather than how to retrieve it.
  • SQL provides statements for defining data structure.
  • SQL provides statements for manipulating data.
  • SQL supports declaration of constraints.
  • SQL provides different ways of retrieving data according to requirements.

9.2.1 Installing MySQL

MySQL is an open source RDBMS software. The textbook states that it can be downloaded from the MySQL official website. After installing MySQL, the MySQL service is started. The appearance of the mysql> prompt indicates that MySQL is ready to accept SQL statements.

SQL Rules to Remember
  • SQL is case insensitive. For example, salary and SALARY are treated as the same column name.
  • SQL statements should end with a semicolon ;.
  • For multiline statements, the semicolon is placed after the final line. The prompt changes from mysql> to -> while continuing the statement.
verakworld.com

9.3 Data Types and Constraints in MySQL

A database consists of one or more relations. A relation or table consists of attributes or columns. Each attribute has a data type, and constraints can also be specified for attributes.

9.3.1 Data Type of Attribute

The data type of an attribute indicates the type of data value that the attribute can have. It also determines the operations that can be performed on that data.

For example, arithmetic operations can be performed on numeric data but not on character data.

Commonly Used MySQL Data Types

Data Type Description
CHAR(n) Character type data of length n. n can be from 0 to 255. CHAR is fixed length. For example, CHAR(10) reserves space for 10 characters.
VARCHAR(n) Variable-length character data. n can be from 0 to 65535. VARCHAR(30) can store a maximum of 30 characters, while actual storage depends on the entered string length.
INT Stores integer values. Each INT value occupies 4 bytes. The unsigned 4-byte range given in the textbook is 0 to 4,294,967,295. For larger values, BIGINT is used and occupies 8 bytes.
FLOAT Stores numbers with decimal points. Each FLOAT value occupies 4 bytes.
DATE Stores dates in YYYY-MM-DD format. The supported range given is 1000-01-01 to 9999-12-31.

CHAR and VARCHAR

CHAR VARCHAR
Fixed-length data type. Variable-length data type.
For CHAR(10), space for 10 characters is reserved. For VARCHAR(30), maximum 30 characters can be stored and actual storage depends on the entered string.
Remaining positions can be padded with spaces. Only space needed for the entered string is allocated.

9.3.2 Constraints

Constraints are restrictions on the data values that an attribute can have. They are used to ensure correctness of data.
Constraint Description
NOT NULL Ensures that a column cannot have NULL values. NULL means a missing, unknown or not applicable value.
UNIQUE Ensures that all values in a column are distinct or unique.
DEFAULT Specifies a default value for a column if no value is provided.
PRIMARY KEY A column that can uniquely identify each row or record in a table.
FOREIGN KEY A column that refers to the value of an attribute defined as a primary key in another table.
Exam Point: Learn the exact meaning and purpose of NOT NULL, UNIQUE, DEFAULT, PRIMARY KEY and FOREIGN KEY.
verakworld.com

9.4 SQL for Data Definition

Before storing data, the relation schema has to be defined. This includes creating a relation, naming it, identifying attributes, deciding data types and specifying constraints.

SQL statements used for defining, modifying and deleting relation schemas are part of Data Definition Language (DDL).

DDL statements covered in this chapter: CREATE, ALTER and DROP.

9.4.1 CREATE Database

The CREATE DATABASE statement is used to create a database.

Syntax
CREATE DATABASE databasename;
Example from the textbook
mysql> CREATE DATABASE StudentAttendance;
Query OK, 1 row affected (0.02 sec)

To select a database for use:

mysql> USE StudentAttendance;
Database changed

To know the names of existing databases:

SHOW DATABASES;

To see the tables in the selected database:

SHOW TABLES;
Important Note: In Linux, names for databases and tables are case-sensitive, whereas in Windows there is no such differentiation. The textbook recommends using database/table names in the same letter case used during creation as a good practice.

9.4.2 CREATE Table

After creating the database, relations are created by specifying attributes, data types and constraints.

Syntax
CREATE TABLE tablename(
attributename1 datatype constraint,
attributename2 datatype constraint,
:
attributenameN datatype constraint);

Important Points

  • The number of columns defines the degree of the relation, denoted by N.
  • Attribute name specifies the name of a column.
  • Datatype specifies the type of data an attribute can hold.
  • Constraint specifies restrictions on attribute values.
  • By default, an attribute can take NULL values except for a primary key.

STUDENT, GUARDIAN and ATTENDANCE Tables

Attribute Data Expected Data Type Constraint
RollNumber Numeric value, maximum 3 digits INT PRIMARY KEY
SName Variable-length string, maximum 20 characters VARCHAR(20) NOT NULL
SDateofBirth Date value DATE NOT NULL
GUID Numeric value consisting of 12 digits CHAR(12) FOREIGN KEY
GUARDIAN Attribute Data Type Constraint
GUID CHAR(12) PRIMARY KEY
GName VARCHAR(20) NOT NULL
GPhone CHAR(10) NULL, UNIQUE
GAddress VARCHAR(30) NOT NULL
ATTENDANCE Attribute Data Type Constraint
AttendanceDate DATE PRIMARY KEY*
RollNumber INT PRIMARY KEY*, FOREIGN KEY
AttendanceStatus CHAR(1) NOT NULL

*AttendanceDate and RollNumber together form the composite primary key.

Example 9.1 — Create STUDENT

mysql> CREATE TABLE STUDENT(
 -> RollNumber INT,
 -> SName VARCHAR(20),
 -> SDateofBirth DATE,
 -> GUID CHAR (12),
 -> PRIMARY KEY (RollNumber));
A comma separates attributes and every SQL statement ends with a semicolon. The -> symbol is the interactive continuation prompt.

9.4.3 DESCRIBE Table

The structure of an already created table can be viewed using the DESCRIBE or DESC statement.

Syntax
DESCRIBE tablename;
mysql> DESCRIBE STUDENT;
Field Type Null Key Default Extra
RollNumberintNOPRINULL
SNamevarchar(20)YESNULL
SDateofBirthdateYESNULL
GUIDchar(12)YESNULL

9.4.4 ALTER Table

ALTER TABLE is used when the structure of a table has to be changed. It can be used to add or remove attributes, modify data types and add or remove constraints.

A. Add Primary Key

ALTER TABLE GUARDIAN ADD PRIMARY KEY (GUID);

The ATTENDANCE table has a composite primary key:

ALTER TABLE ATTENDANCE
-> ADD PRIMARY KEY(AttendanceDate,
RollNumber);

B. Add Foreign Key

Important conditions:

  • The referenced relation must already be created.
  • The referenced attribute(s) must be part of the primary key of the referenced relation.
  • The data types and sizes of referenced and referencing attributes must be the same.
Syntax
ALTER TABLE table_name ADD FOREIGN KEY(attribute name)
REFERENCES referenced_table_name(attribute name);
Example
ALTER TABLE STUDENT
-> ADD FOREIGN KEY(GUID) REFERENCES
-> GUARDIAN(GUID);

C. Add UNIQUE Constraint

Syntax
ALTER TABLE table_name ADD UNIQUE (attribute name);
Example
ALTER TABLE GUARDIAN
-> ADD UNIQUE(GPhone);

D. Add an Attribute

Syntax
ALTER TABLE table_name ADD attribute name DATATYPE;
Example
ALTER TABLE GUARDIAN
-> ADD income INT;

E. Modify Data Type

Syntax
ALTER TABLE table_name MODIFY attribute DATATYPE;
Example
ALTER TABLE GUARDIAN
-> MODIFY GAddress VARCHAR(40);

F. Modify Constraint

Syntax
ALTER TABLE table_name MODIFY attribute DATATYPE NOT NULL;
Example
ALTER TABLE STUDENT
-> MODIFY SName VARCHAR(20) NOT NULL;

G. Add Default Value

Syntax
ALTER TABLE table_name MODIFY attribute DATATYPE
DEFAULT default_value;
Example
ALTER TABLE STUDENT
-> MODIFY SDateofBirth DATE DEFAULT '2000-05-15';

H. Remove an Attribute

Syntax
ALTER TABLE table_name DROP attribute;
Example
ALTER TABLE GUARDIAN DROP income;

I. Remove Primary Key

Syntax
ALTER TABLE table_name DROP PRIMARY KEY;
Example
ALTER TABLE GUARDIAN DROP PRIMARY KEY;
Caution: After dropping the primary key, the textbook notes that each table should have a primary key to maintain uniqueness. The primary key can be added again using ALTER TABLE.

9.4.5 DROP Statement

DROP is used to permanently remove a table or database. The textbook specifically cautions that the operation cannot be undone.

Drop a table
DROP TABLE table_name;
Drop a database
DROP DATABASE database_name;

Dropping a database ultimately removes all the tables within it.

verakworld.com

9.5 SQL for Data Manipulation

When a table is created, only its structure is created and it initially contains no data. SQL statements are used to insert, delete and update records.

Data Manipulation Language (DML): The SQL statements used for insertion, removal and modification of data are part of DML.

9.5.1 Insertion of Records

INSERT INTO is used to insert new records into a table.

Syntax
INSERT INTO tablename
VALUES(value 1, value 2,....);

Each value corresponds to the corresponding attribute. Attribute names need not be specified when the number of values exactly matches the total number of attributes.

Caution: When populating a table containing a foreign key, records in the referenced tables should already be populated.

Insert Record into GUARDIAN

INSERT INTO GUARDIAN
-> VALUES (444444444444, 'Amit Ahuja',
5711492685, 'G-35,Ashok vihar, Delhi' );

To insert values only into selected attributes:

Syntax
INSERT INTO tablename (column1, column2, ...)
VALUES (value1, value2, ...);
Example
INSERT INTO GUARDIAN(GUID, GName, GAddress)
-> VALUES (333333333333, 'Danny Dsouza',
'S -13, Ashok Village, Daman' );
Text and date values must be enclosed in single quotes.

STUDENT Table Example

RollNumber SName SDateofBirth GUID
1Atharv Ahuja2003-05-15444444444444
2Daizy Bhutia2002-02-28111111111111
3Taleem Shah2002-02-28NULL
4John Dsouza2003-08-18333333333333
5Ali Shah2003-07-05101010101010
6Manika P.2002-03-10466444444666
Insert all attributes
INSERT INTO STUDENT
-> VALUES(1,'Atharv Ahuja','2003-05-15',
444444444444);
OR
INSERT INTO STUDENT (RollNumber, SName,
SDateofBirth, GUID)
-> VALUES (1,'Atharv Ahuja','2003-05-15',
444444444444);

Dates are stored in YYYY-MM-DD format.

If GUID is NULL and column names are not specified:

INSERT INTO STUDENT
-> VALUES(3, 'Taleem Shah','2002-02-28', NULL);

Alternatively, when only selected attributes are being inserted:

INSERT INTO STUDENT (RollNumber, SName,
-> SDateofBirth) VALUES (3, 'Taleem Shah','2002-02-28');
verakworld.com

9.6 SQL for Data Query

The SELECT statement is used to retrieve data from tables. It is also called a query statement. The output is displayed in tabular form.

9.6.1 SELECT Statement

Syntax
SELECT attribute1, attribute2, ...
FROM table_name
WHERE condition;
  • The attributes are the column names to be retrieved.
  • The FROM clause specifies the table from which data is retrieved.
  • The WHERE clause is optional and specifies conditions for retrieval.

Select All Data

SELECT * FROM table_name;

Example 9.2

Retrieve the name and date of birth of the student with roll number 1:

SELECT SName, SDateofBirth
FROM STUDENT
WHERE RollNumber = 1;

9.6.2 Querying Using Database OFFICE

The textbook introduces an OFFICE database containing related tables such as EMPLOYEE and DEPARTMENT. An employee is assigned to a department and the department number, DeptId, is stored as a foreign key in EMPLOYEE.

EmpNo Ename Salary Bonus DeptId
101Aaliya10000234D02
102Kritika60000123D01
103Shabbir45000566D01
104Gurpreet19000565D04
105Joseph34000875D03
106Sanya48000695D02
107Vergese15000NULLD01
108Nachaobi29000NULLD05
109Daribha42000NULLD04
110Tanya50000467D05

A. Retrieve Selected Columns

SELECT EmpNo FROM EMPLOYEE;
SELECT EmpNo, Ename FROM EMPLOYEE;

B. Renaming Columns Using AS

The AS keyword can be used to rename a column while displaying query output.

SELECT EName as Name FROM EMPLOYEE;

Example 9.3

SELECT EName as Name, Salary*12 FROM EMPLOYEE;

The result can use an alias for the calculated column:

SELECT Ename AS Name, Salary*12 AS 'Annual Income'
FROM EMPLOYEE;
The aliased Annual Income is only for displaying the query result. It does not create a new column in the database table.

C. DISTINCT Clause

DISTINCT eliminates repetition from the retrieved result.

SELECT DISTINCT DeptId FROM EMPLOYEE;

D. WHERE Clause

WHERE retrieves records that satisfy specified conditions.

Relational operators mentioned in the chapter are:

< <= > >= != =

Logical operators:

AND OR NOT

Example 9.4

SELECT * FROM EMPLOYEE
WHERE Salary > 5000 AND DeptId = 'D04';

Example 9.5

SELECT * FROM EMPLOYEE
WHERE NOT Ename = 'Aaliya';

Example 9.6 — Salary Range

SELECT Ename, DeptId
FROM EMPLOYEE
WHERE Salary>=20000 AND Salary<=50000;

The same range can be checked using BETWEEN:

SELECT Ename, DeptId
FROM EMPLOYEE
WHERE Salary BETWEEN 20000 AND 50000;
Remember: BETWEEN defines a range of values inclusive of the boundary values.

Example 9.7 — OR

SELECT *
FROM EMPLOYEE
WHERE DeptId = 'D01' OR DeptId = 'D02' OR
DeptId = 'D04';

E. Membership Operator IN

The IN operator compares a value with a set of values and returns true if the value belongs to that set.
SELECT * FROM EMPLOYEE
WHERE DeptId IN ('D01', 'D02' , 'D04');

NOT can be combined with IN:

SELECT * FROM EMPLOYEE
WHERE DeptId NOT IN('D01', 'D02');

F. ORDER BY Clause

ORDER BY displays data in an ordered form according to a specified column.

  • By default, the order is ascending.
  • DESC is used for descending order.
SELECT * FROM EMPLOYEE
ORDER BY Salary;
SELECT * FROM EMPLOYEE
ORDER BY Salary DESC;

G. Handling NULL Values

NULL represents a missing or unknown value. NULL is different from zero.

Arithmetic operations involving NULL result in NULL. For example, the textbook gives:

5 + NULL = NULL

To test for NULL:

SELECT * FROM EMPLOYEE
WHERE Bonus IS NULL;

To test for non-NULL values:

SELECT EName FROM EMPLOYEE
WHERE Bonus IS NOT NULL
AND DeptID = 'D01';

H. Substring Pattern Matching

Sometimes exact matching is not required. SQL provides the LIKE operator with WHERE for pattern matching.

Wildcard Meaning
% Represents zero, one or multiple characters.
_ Represents exactly one character.

Example 9.13

SELECT * FROM EMPLOYEE
WHERE Ename like 'K%';

Example 9.14

SELECT * FROM EMPLOYEE
WHERE Ename like '%a'
AND Salary > 45000;

Example 9.15

SELECT * FROM EMPLOYEE
WHERE Ename like '_ANYA';

Example 9.16

SELECT Ename FROM EMPLOYEE
WHERE Ename like '%se%';

Example 9.17

SELECT EName FROM EMPLOYEE
WHERE Ename like '_a%';
Exam Point: Learn the difference between %, which represents zero or more characters, and _, which represents exactly one character.
verakworld.com

9.7 Data Updation and Deletion

Updation and deletion are also part of SQL Data Manipulation Language (DML).

9.7.1 Data Updation

UPDATE is used to modify values in one or more columns of existing records.
Syntax
UPDATE table_name
SET attribute1 = value1, attribute2 = value2, ...
WHERE condition;

Example

UPDATE STUDENT
-> SET GUID = 101010101010
-> WHERE RollNumber = 3;
Very Important: If the WHERE clause is omitted in UPDATE, the value can be changed for all records.

Updating More Than One Column

UPDATE GUARDIAN
-> SET GAddress = 'WZ - 68, Azad Avenue,
-> Bijnour, MP', GPhone = 9010810547
-> WHERE GUID = 466444444666;

9.7.2 Data Deletion

DELETE is used to remove one or more records from a table.
Syntax
DELETE FROM table_name
WHERE condition;

Example

DELETE FROM STUDENT WHERE RollNumber = 2;
Very Important: If the WHERE clause is omitted with DELETE, all records in the table can be deleted.
verakworld.com

9.8 Functions in SQL

A function performs a particular task and returns zero or more values as a result. SQL functions can work on single records or multiple records.

Categories of Single-Row Functions

Single Row Functions
Numeric / Math Functions
String Functions
Date and Time Functions
verakworld.com

9.8.1 Single Row Functions

Single row functions, also called scalar functions, operate on a single value and return a single value.

Math functions accept numeric values and return numeric values. String functions accept character values and return character or numeric values. Date and Time functions accept date and time values and return numeric, string, or date/time values.

A. Math Functions

Function Description Example Output
POWER(X,Y) / POW(X,Y) Calculates X to the power Y. SELECT POWER(2,3); 8
ROUND(N,D) Rounds N to D decimal places. If D=0, it rounds to the nearest integer. SELECT ROUND(2912.564,1); 2912.6
MOD(A,B) Returns the remainder after dividing A by B. SELECT MOD(21,2); 1

Example 9.18 — GST

SELECT ROUND(12/100*Price,1) "GST" FROM INVENTORY;

To add FinalPrice:

ALTER TABLE INVENTORY ADD(FinalPrice Numeric(10,1));

To calculate it:

UPDATE INVENTORY SET
FinalPrice=Price+Round(Price*12/100,1);

EMI and Remaining Amount

SELECT CarId, FinalPrice,
ROUND(FinalPrice-MOD(FinalPrice,1000)/10,0) "EMI",
MOD(FinalPrice,10000) "Remaining Amount"
FROM INVENTORY;

Example 9.19 — Commission

ALTER TABLE SALE ADD(Commission Numeric(7,2));
UPDATE SALE SET
Commission=12/100*SalePrice;
SELECT * FROM SALE WHERE Commission > 73000;
SELECT InvoiceNo, SalePrice,
Round(Commission,0) FROM SALE;

B. String Functions

String functions operate on alphanumeric data. They can change case, extract substrings, calculate string length and perform other operations.

Function Description Textbook Example
UCASE(string) / UPPER(string) Converts a string to uppercase. SELECT UCASE("Informatics Practices"); → INFORMATICS PRACTICES
LOWER(string) / LCASE(string) Converts a string to lowercase. SELECT LOWER("Informatics Practices"); → informatics practices
MID(string,pos,n) Returns n characters starting from position pos. MID("Informatics",3,4) → form
SUBSTRING / SUBSTR Alternative forms of MID. MID('Informatics',7) → atics
LENGTH(string) Returns the number of characters. LENGTH("Informatics") → 11
LEFT(string,N) Returns N characters from the left. LEFT("Computer",4) → Comp
RIGHT(string,N) Returns N characters from the right. RIGHT("SCIENCE",3) → NCE
INSTR(string,substring) Returns the position of the first occurrence. Returns 0 if not present. INSTR("Informatics","ma") → 6
LTRIM(string) Removes leading whitespace. Leading spaces are removed.
RTRIM(string) Removes trailing whitespace. Trailing spaces are removed.
TRIM(string) Removes both leading and trailing whitespace. Both sides are trimmed.

Example 9.20

SELECT LOWER(CustName), UPPER(Email) FROM CUSTOMER;

Find email length and the portion before @:

SELECT LENGTH(Email), LEFT(Email, INSTR(Email, "@")-1)
FROM CUSTOMER;

Find the area code from the customer in Rohini:

SELECT MID(Phone,3,4) FROM CUSTOMER
WHERE CustAdd like '%Rohini%';

Remove .com from email addresses:

SELECT TRIM(".com" from Email) FROM CUSTOMER;

Display customers having Yahoo email:

SELECT * FROM CUSTOMER WHERE Email LIKE "%yahoo%";

C. Date and Time Functions

Function Description Example / Output
NOW() Returns current system date and time. 2019-07-11 19:41:17
DATE() Returns the date part from a date/time expression. 2019-07-11
MONTH(date) Returns the month number. 7
MONTHNAME(date) Returns the month name. November
YEAR(date) Returns the year. 2003
DAY(date) Returns the day part. 24
DAYNAME(date) Returns the day name. Thursday

Example 9.21

SELECT DAY(DOJ), MONTH(DOJ), YEAR(DOJ)
FROM EMPLOYEE;

To display information for employees whose joining day is not Sunday:

SELECT DAYNAME(DOJ), DAY(DOJ),
MONTHNAME(DOJ), YEAR(DOJ)
FROM EMPLOYEE
WHERE DAYNAME(DOJ)!='Sunday';

9.8.2 Aggregate Functions

Aggregate functions, also called Multiple Row functions, operate on a set of records as a whole and return a single value for the group of records.
Single Row Function Multiple Row Function
Operates on a single row at a time. Operates on groups of rows.
Returns one result per row. Returns one result for a group of rows.
Can be used in SELECT, WHERE and ORDER BY clauses. Can be used in SELECT clause only, according to the textbook table.
Math, String and Date functions are examples. MAX(), MIN(), AVG(), SUM(), COUNT() and COUNT(*) are examples.
Function Description
MAX(column)Returns the largest value from the specified column.
MIN(column)Returns the smallest value from the specified column.
AVG(column)Returns the average of values in the specified column.
SUM(column)Returns the sum of values in the specified column.
COUNT(*)Returns the number of records in a table.
COUNT(column)Returns the number of values in the specified column, ignoring NULL values.

COUNT Examples

SELECT COUNT(*) FROM INVENTORY
WHERE Model="VXI";
SELECT COUNT(DISTINCT Model) FROM INVENTORY;
SELECT AVG(Price) FROM INVENTORY
WHERE Model="LXI";
Exam Point: Remember that COUNT(column) ignores NULL values, whereas COUNT(*) counts records.
verakworld.com

9.9 GROUP BY Clause in SQL

GROUP BY is used when rows need to be grouped according to common values in a specified column.

GROUP BY groups rows containing the same values in a specified column. Aggregate functions such as COUNT, MAX, MIN, AVG and SUM can be applied to grouped values.

The HAVING clause is used to specify conditions on rows with GROUP BY.

Example 9.23

Number of cars purchased by each customer:

SELECT CustID, COUNT(*) "Number of Cars"
FROM SALE GROUP BY CustID;

Customers who purchased more than one car:

SELECT CustID, COUNT(*) FROM SALE GROUP BY
CustID HAVING Count(*)>1;

Number of people in each payment mode:

SELECT PaymentMode, COUNT(PaymentMode)
FROM SALE GROUP BY Paymentmode
ORDER BY Paymentmode;

Payment modes used more than once:

SELECT PaymentMode, Count(PaymentMode)
FROM SALE
GROUP BY Paymentmode
HAVING COUNT(*)>1
ORDER BY Paymentmode;
GROUP BY + HAVING: GROUP BY forms groups; HAVING applies a condition to those grouped results.
verakworld.com

9.10 Operations on Relations

The textbook describes operations such as UNION, INTERSECT, MINUS and Cartesian Product.

UNION, INTERSECTION and Set Difference are binary operations because they operate on two tables. These operations can be applied when both relations have the same number of attributes and corresponding attributes have the same domain.

9.10.1 UNION (∪)

UNION combines selected rows from two tables. If some rows are common to both tables, they appear only once in the result.

SNo Name Class
1Aastha7A
2Mahira6A
3Mohit7B
4Sanjay7A
1Mehak8A
3Lavanya7A
5Abhay8A

9.10.2 INTERSECT (∩)

INTERSECT returns the common tuples from two tables.

SNoNameClass
2Mahira6A
4Sanjay7A

9.10.3 MINUS (-)

MINUS returns rows that are present in the first table but not in the second table.

SNoNameClass
1Mehak8A
3Lavanya7A
5Abhay8A

9.10.4 Cartesian Product (X)

Cartesian Product combines tuples from two relations and produces all pairs of rows from the two input relations, irrespective of whether their common attributes have the same values.

The degree of the resulting relation is the sum of the degrees of the two relations.

The cardinality of the resulting relation is the product of the cardinalities of the two relations.

For DANCE and MUSIC in the textbook:

  • Degree of DANCE = 3
  • Degree of MUSIC = 3
  • Cardinality of DANCE = 4
  • Cardinality of MUSIC = 5
  • Resulting degree = 3 + 3 = 6
  • Resulting cardinality = 4 × 5 = 20
DANCE
Degree = 3
Cardinality = 4
×
MUSIC
Degree = 3
Cardinality = 5
Cartesian Product
Degree = 6
Cardinality = 20
verakworld.com
verakworld.com

9.11 Using Two Relations in a Query

Queries can use more than one relation.

9.11.1 Cartesian Product on Two Tables

When more than one table is used in a query, table names are separated by commas in the FROM clause.

Example 9.24

SELECT * FROM DANCE, MUSIC;

The result has degree 6 and cardinality 20.

To display only rows where the Name attribute has the same value in both tables:

SELECT * FROM DANCE D, MUSIC M
WHERE D.Name = M.Name;
The textbook uses table aliases D for DANCE and M for MUSIC. A table alias is valid only for the current query. If an alias is given in the FROM clause, the original table name cannot be used in that query.

9.11.2 JOIN on Two Tables

JOIN combines tuples from two tables according to specified conditions.

Unlike Cartesian Product, which creates all possible combinations, JOIN combines related tuples based on conditions.

The related attribute is usually a primary key in one table and a foreign key in another.

UNIFORM and COST

UCode UName UColor
1ShirtWhite
2PantGrey
3TieBlue
UCode Size Price
1L580
1M500
2L890
2M810

UCode is the primary key in UNIFORM. UCode and Size together form the composite key in COST. UCode is the common attribute.

Example 9.25 — JOIN in Three Ways

a) Using condition in WHERE clause

SELECT * FROM UNIFORM U, COST C
WHERE U.UCode = C.UCode;

b) Explicit JOIN clause

SELECT * FROM UNIFORM U JOIN COST C ON
U.Ucode=C.Ucode;

c) NATURAL JOIN

SELECT * FROM UNIFORM NATURAL JOIN COST;

NATURAL JOIN removes the repeated common UCode column from the result.

Important JOIN Points

  • If two tables are joined using equality on a common attribute, JOIN with ON or NATURAL JOIN can be used.
  • If three tables are joined using equality conditions, two JOIN or NATURAL JOIN operations are required.
  • In general, N-1 joins are needed to combine N tables on equality conditions.
  • With JOIN, relational operators can be used to combine tuples from two tables.
Exam Point: Know the difference between Cartesian Product, JOIN and NATURAL JOIN.
verakworld.com

Chapter Summary

  • A database is a collection of related tables. MySQL is a relational DBMS.
  • DDL includes statements such as CREATE TABLE, ALTER TABLE and DROP TABLE.
  • DML includes INSERT, SELECT, UPDATE and DELETE statements as presented in the chapter summary.
  • A table contains rows and columns. Each row is a record and columns describe features of records.
  • ALTER TABLE changes the structure of a table, including adding, removing or changing columns.
  • UPDATE modifies existing data.
  • WHERE applies conditions in an SQL query.
  • DISTINCT removes repetition from query results.
  • BETWEEN defines a range inclusive of boundary values.
  • IN selects values matching any value in a given list.
  • IS NULL and IS NOT NULL are used to test NULL values.
  • ORDER BY displays query results in ascending or descending order. Ascending is the default.
  • LIKE performs pattern matching.
  • % represents zero or more characters.
  • _ represents exactly one character.
  • A function performs a particular task and returns a value.
  • Single Row functions operate on one row and return one value.
  • Multiple Row functions operate on a set of records and return a single value.
  • COUNT, MAX, MIN, AVG and SUM are examples of multiple-row functions.
  • GROUP BY groups rows having the same values in a specified column.
  • JOIN combines rows from two or more tables using common fields and conditions.
verakworld.com

Questions & Answers

1-Mark Questions

1. What is SQL?
SQL stands for Structured Query Language and is used to access and manipulate data in databases.
2. Is SQL case sensitive?
No. SQL is case insensitive.
3. Which statement is used to create a database?
CREATE DATABASE.
4. Which statement is used to retrieve data?
SELECT.
5. Which clause is used for conditions?
WHERE.
6. Which operator is used to search a pattern?
LIKE.
7. What does % represent in LIKE?
Zero, one or multiple characters.
8. What does _ represent in LIKE?
Exactly one character.
9. Which function returns the largest value?
MAX().
10. Which clause groups rows?
GROUP BY.

2-Mark Questions

1. What is a constraint? Name commonly used SQL constraints.
A constraint is a restriction on the data values that an attribute can have. The commonly used constraints given in the chapter are NOT NULL, UNIQUE, DEFAULT, PRIMARY KEY and FOREIGN KEY.
2. Differentiate between CHAR and VARCHAR.
CHAR is a fixed-length data type, whereas VARCHAR is a variable-length data type. CHAR reserves the specified length, while VARCHAR uses storage according to the actual string length.
3. What is the purpose of ORDER BY?
ORDER BY displays query results in an ordered form with respect to a specified column. Ascending order is the default and DESC is used for descending order.
4. What is NULL?
NULL represents a missing or unknown value. It is different from zero.
5. What is the purpose of DISTINCT?
DISTINCT removes repeated values from the query result and displays distinct records or values.

3-Mark Questions

1. Explain the three conditions for adding a foreign key.
  • The referenced relation must already be created.
  • The referenced attribute(s) must be part of the primary key of the referenced relation.
  • The data types and sizes of referenced and referencing attributes must be the same.
2. Explain BETWEEN and IN operators.
BETWEEN checks whether a value lies within a specified range, including the boundary values. IN compares a value with a list of values and returns true when it matches any value in the list.
3. Explain the two wildcards used with LIKE.
The percent symbol (%) represents zero, one or multiple characters. The underscore (_) represents exactly one character.

4/5-Mark Questions

1. Explain the ALTER TABLE operations discussed in the chapter with syntax.
The chapter discusses adding a primary key, adding a foreign key, adding UNIQUE, adding an attribute, modifying a datatype, modifying a constraint, adding a default value, removing an attribute and removing a primary key using ALTER TABLE.
2. Explain Single Row Functions and Aggregate Functions.
Single Row functions operate on a single value and return a single value. Math, String and Date functions are examples. Aggregate or Multiple Row functions operate on a group of records and return one value for the group. MAX(), MIN(), AVG(), SUM(), COUNT() and COUNT(*) are examples.
3. Explain JOIN and NATURAL JOIN.
JOIN combines tuples from two tables according to specified conditions, usually using related attributes. NATURAL JOIN works similarly but removes the redundant common attribute from the result when there is one common attribute.
verakworld.com

Important Questions

1 Mark

  • Define RDBMS.
  • Name any two RDBMS software.
  • What is SQL?
  • What is the purpose of DISTINCT?
  • What does LIKE do?
  • What are the two wildcard characters used with LIKE?
  • What is NULL?
  • Name any two aggregate functions.
  • What is GROUP BY?
  • What is JOIN?

2 Marks

  • Differentiate CHAR and VARCHAR.
  • Explain PRIMARY KEY and FOREIGN KEY.
  • Explain ORDER BY.
  • Explain BETWEEN and IN.
  • Explain IS NULL and IS NOT NULL.
  • Write the purpose of UPDATE and DELETE.
  • State the purpose of the WHERE clause.

3 Marks

  • Explain the conditions required while adding a foreign key.
  • Differentiate Single Row and Multiple Row functions.
  • Explain the wildcard characters of LIKE.
  • Explain the purpose of GROUP BY and HAVING.
  • Explain UNION, INTERSECT and MINUS.

4/5 Marks

  • Explain ALTER TABLE operations with suitable SQL syntax.
  • Explain SQL data types and constraints given in the chapter.
  • Explain Single Row functions with examples.
  • Explain Aggregate functions with examples.
  • Explain Cartesian Product and its degree and cardinality.
  • Explain JOIN using two tables.
  • Explain the three methods of joining UNIFORM and COST.
  • Write SQL queries based on the PRODUCT, SPORTS and CARSHOWROOM exercises given in the chapter.
These questions are selected from the concepts and exercises contained in the uploaded textbook chapter. They are not claimed to be officially repeated board questions.
verakworld.com

⚡ Quick Revision

Important Definitions

  • SQL: Structured Query Language used to access and manipulate database data.
  • Constraint: Restriction on data values of an attribute.
  • NULL: Represents a missing or unknown value.
  • Single Row Function: Operates on a single value and returns a single value.
  • Aggregate Function: Operates on a set of records and returns one value for the group.
  • GROUP BY: Groups rows having common values in a specified column.
  • JOIN: Combines tuples from tables according to specified conditions.
  • Cartesian Product: Produces all combinations of tuples from two relations.

Important SQL Statements

Purpose Statement
Create databaseCREATE DATABASE
Select databaseUSE
View databasesSHOW DATABASES
Create tableCREATE TABLE
View table structureDESCRIBE / DESC
View tablesSHOW TABLES
Modify table structureALTER TABLE
Remove table/databaseDROP
Insert recordsINSERT INTO
Retrieve recordsSELECT
Modify recordsUPDATE
Remove recordsDELETE

Important Operators / Clauses

Item Purpose
WHEREApplies conditions.
DISTINCTRemoves repetition.
BETWEENChecks an inclusive range.
INChecks membership in a list.
NOT INExcludes specified values.
IS NULLChecks NULL values.
IS NOT NULLChecks non-NULL values.
LIKEPattern matching.
ORDER BYOrders query output.
GROUP BYGroups rows.
HAVINGApplies conditions with grouped rows.

LIKE Wildcards

SymbolMeaning
%Zero, one or multiple characters.
_Exactly one character.

Important Functions

Category Functions
MathPOWER(), POW(), ROUND(), MOD()
StringUCASE(), UPPER(), LOWER(), LCASE(), MID(), SUBSTRING(), SUBSTR(), LENGTH(), LEFT(), RIGHT(), INSTR(), LTRIM(), RTRIM(), TRIM()
Date and TimeNOW(), DATE(), MONTH(), MONTHNAME(), YEAR(), DAY(), DAYNAME()
AggregateMAX(), MIN(), AVG(), SUM(), COUNT(), COUNT(*)

Important Differences

Single Row Function Multiple Row Function
Works on a single row.Works on a group of rows.
One result per row.One result for a group.
Examples: Math, String and Date functions.Examples: MAX, MIN, AVG, SUM, COUNT.

Important Relational Operations

Operation Meaning
UNIONCombines rows from two relations and removes duplicate rows.
INTERSECTReturns common tuples.
MINUSReturns tuples in the first relation but not the second.
Cartesian ProductProduces all combinations of tuples.

Important JOIN Points

  • JOIN combines related rows from tables.
  • JOIN uses specified conditions.
  • NATURAL JOIN removes the redundant common column.
  • N-1 joins are needed to combine N tables on equality conditions.

Important Syntax to Revise

CREATE DATABASE databasename;
CREATE TABLE tablename(
attributename1 datatype constraint,
attributename2 datatype constraint,
:
attributenameN datatype constraint);
DESCRIBE tablename;
ALTER TABLE table_name
ADD FOREIGN KEY(attribute name)
REFERENCES referenced_table_name(attribute name);
ALTER TABLE table_name
MODIFY attribute DATATYPE;
ALTER TABLE table_name
DROP attribute;
DROP TABLE table_name;
INSERT INTO tablename
VALUES(value 1, value 2,....);
SELECT attribute1, attribute2, ...
FROM table_name
WHERE condition;
UPDATE table_name
SET attribute1 = value1, attribute2 = value2, ...
WHERE condition;
DELETE FROM table_name
WHERE condition;
SELECT * FROM EMPLOYEE
ORDER BY Salary DESC;
SELECT * FROM EMPLOYEE
WHERE DeptId IN ('D01', 'D02', 'D04');
SELECT * FROM EMPLOYEE
WHERE Bonus IS NULL;
SELECT * FROM EMPLOYEE
WHERE Ename LIKE 'K%';
SELECT CustID, COUNT(*)
FROM SALE
GROUP BY CustID;
SELECT * FROM UNIFORM U JOIN COST C
ON U.Ucode=C.Ucode;
SELECT * FROM UNIFORM NATURAL JOIN COST;

Important Programs / SQL Practice Areas

  • Create StudentAttendance database.
  • Create STUDENT table.
  • Describe STUDENT.
  • Add primary and foreign keys using ALTER TABLE.
  • Insert records into GUARDIAN and STUDENT.
  • Retrieve selected columns using SELECT.
  • Use aliases with AS.
  • Use DISTINCT and WHERE.
  • Use BETWEEN and IN.
  • Use ORDER BY.
  • Handle NULL values.
  • Use LIKE pattern matching.
  • Update and delete records.
  • Use Math, String and Date functions.
  • Use Aggregate functions.
  • Use GROUP BY and HAVING.
  • Perform UNION, INTERSECT, MINUS and Cartesian Product operations.
  • Use Cartesian Product and JOIN with two tables.
  • Use NATURAL JOIN.

Important Diagrams / Structures to Revise

  • MySQL Shell prompt shown in Figure 9.1.
  • CARSHOWROOM database schema shown in Figure 9.2.
  • Single Row Function categories shown in Figure 9.3.
  • UNION diagram shown in Figure 9.4.
  • INTERSECT diagram shown in Figure 9.5.
  • MINUS / Difference diagram shown in Figure 9.6.
  • Relationships and JOIN structure involving the tables used in the chapter.
Final Revision Tip: Before the examination, revise SQL syntax carefully, especially CREATE, ALTER, INSERT, SELECT, UPDATE, DELETE, WHERE, DISTINCT, BETWEEN, IN, LIKE, ORDER BY, GROUP BY, HAVING, aggregate functions, Cartesian Product and JOIN.
verakworld.com

Textbook Exercise — Chapter 9

Exercise 1

  1. Define RDBMS. Name any two RDBMS software.
  2. State the purpose of ORDER BY and GROUP BY.
  3. Give two differences between Single Row Functions and Aggregate Functions.
  4. Explain Cartesian Product.
  5. Differentiate ALTER and UPDATE; DELETE and DROP.
  6. Name functions used for displaying day name, extracting characters from a string, displaying month name and displaying a name in capital letters.

Exercise 2 — Output Based

SELECT POW(2,3);

SELECT ROUND(342.9234,-1);

SELECT LENGTH("Informatics Practices");

SELECT YEAR("1979/11/26"),
MONTH("1979/11/26"),
DAY("1979/11/26"),
MONTHNAME("1979/11/26");

SELECT LEFT("INDIA",3),
RIGHT("Computer Science",4),
MID("Informatics",3,4),
SUBSTR("Practices",3);

Exercise 3 — MOVIE Table

MovieID MovieName Category ReleaseDate ProductionCost BusinessCost
001Hindi_MovieMusical2018-04-23124500130000
002Tamil_MovieAction2016-05-17112000118000
003English_MovieHorror2017-08-06245000360000
004Bengali_MovieAdventure2017-01-0472000100000
005Telugu_MovieAction100000
006Punjabi_MovieComedy30500

Write SQL queries to:

  1. Display all information from Movie.
  2. Display MovieID, MovieName and Total_Earning, where Total_Earning is ProductionCost + BusinessCost.
  3. List different movie categories.
  4. Find NetProfit as BusinessCost − ProductionCost.
  5. List movies with ProductionCost greater than 10,000 and less than 1,00,000.
  6. List movies in Comedy or Action categories.
  7. List movies that have not been released.

Exercise 4 — SPORTS Database

The textbook asks students to create a database named Sports and a TEAM table with TeamID and TeamName, make TeamID the primary key, display the table structure, insert four teams and create MATCH_DETAILS.

MatchID MatchDate FirstTeamID SecondTeamID FirstTeamScore SecondTeamScore
M12018-07-17129086
M22018-07-18344548
M32018-07-19137856
M42018-07-19245667
M52018-07-18143287
M62018-07-17236751

The textbook asks for queries to:

  • Display MatchID where both teams scored more than 70.
  • Display MatchID where FirstTeam scored less than 70 and SecondTeam scored more than 70.
  • Display MatchID and date of matches played by Team 1 and won by it.
  • Display MatchID of matches played by Team 2 and not won by it.
  • Rename TEAM to T_DATA and TeamID and TeamName to T_ID and T_NAME.

Exercise 5 — Two Relations

The textbook asks students to use TEAM and MATCH_DETAILS relations and write queries based on team scores, matches and table/attribute renaming.

Exercise 6 — SCHOOLUNIFORM Database

The exercise deals with UNIFORM and COST relations and asks students to write SQL queries to handle insertion, foreign-key provisions, appropriate constraints and a condition ensuring that price is greater than zero.

Exercise 7 — Product Table

PCode PName UPrice Manufacturer
P01Washing Powder120Surf
P02Toothpaste54Colgate
P03Soap25Lux
P04Toothpaste65Pepsodent
P05Soap38Dove
P06Shampoo245Dove

The textbook asks students to:

  1. Create Product with suitable data types and constraints.
  2. Identify the primary key.
  3. Display Product Code, Product name and price in descending order of product name and, for equal names, ascending order of price.
  4. Add Discount.
  5. Calculate 10% discount when UPrice is more than 100; otherwise discount is 0.
  6. Increase price by 12% for products manufactured by Dove.
  7. Display total products manufactured by each manufacturer.
  8. Find output of AVG(UPrice) grouped by PName.
  9. Find distinct manufacturers.
  10. Find COUNT(DISTINCT PName).
  11. Find MAX and MIN UPrice grouped by PName.

Exercise 8 — CARSHOWROOM

The textbook asks students to:

  • Add a Discount column to INVENTORY.
  • Set no discount for LXI.
  • Set 10% discount for VXI.
  • Set 12% discount for models other than LXI and VXI.
  • Display the costliest Petrol car.
  • Calculate average and total discount for Baleno cars.
  • Find the total number of cars having no discount.
verakworld.com

Final Revision

Chapter 9 — Structured Query Language (SQL)

Revise SQL syntax, data types, constraints, DDL, DML, SELECT queries, conditions, pattern matching, functions, GROUP BY, relational operations and JOIN operations.

verakworld.com

Leave a Comment