2nd PUC Computer Science Chapter 9 SQL Notes | Structured Query Language
Complete Short Notes & Exam Preparation Guide
Based on the NCERT textbook
Table of Contents
- 9.1 Introduction
- 9.2 Structured Query Language (SQL)
- 9.3 Data Types and Constraints in MySQL
- 9.4 SQL for Data Definition
- 9.5 SQL for Data Manipulation
- 9.6 SQL for Data Query
- 9.7 Data Updation and Deletion
- 9.8 Functions in SQL
- 9.9 GROUP BY Clause in SQL
- 9.10 Operations on Relations
- 9.11 Using Two Relations in a Query
- Chapter Summary
- Questions & Answers
- Important Questions
- Quick Revision
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.
9.2 Structured Query Language (SQL)
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 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.
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
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
| 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. |
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).
9.4.1 CREATE Database
The CREATE DATABASE statement is used to create a database.
CREATE DATABASE databasename;
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;
9.4.2 CREATE Table
After creating the database, relations are created by specifying attributes, data types and constraints.
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));
9.4.3 DESCRIBE Table
The structure of an already created table can be viewed using the DESCRIBE or DESC statement.
DESCRIBE tablename;
mysql> DESCRIBE STUDENT;
| Field | Type | Null | Key | Default | Extra |
|---|---|---|---|---|---|
| RollNumber | int | NO | PRI | NULL | |
| SName | varchar(20) | YES | NULL | ||
| SDateofBirth | date | YES | NULL | ||
| GUID | char(12) | YES | NULL |
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.
ALTER TABLE table_name ADD FOREIGN KEY(attribute name) REFERENCES referenced_table_name(attribute name);
ALTER TABLE STUDENT -> ADD FOREIGN KEY(GUID) REFERENCES -> GUARDIAN(GUID);
C. Add UNIQUE Constraint
ALTER TABLE table_name ADD UNIQUE (attribute name);
ALTER TABLE GUARDIAN -> ADD UNIQUE(GPhone);
D. Add an Attribute
ALTER TABLE table_name ADD attribute name DATATYPE;
ALTER TABLE GUARDIAN -> ADD income INT;
E. Modify Data Type
ALTER TABLE table_name MODIFY attribute DATATYPE;
ALTER TABLE GUARDIAN -> MODIFY GAddress VARCHAR(40);
F. Modify Constraint
ALTER TABLE table_name MODIFY attribute DATATYPE NOT NULL;
ALTER TABLE STUDENT -> MODIFY SName VARCHAR(20) NOT NULL;
G. Add Default Value
ALTER TABLE table_name MODIFY attribute DATATYPE DEFAULT default_value;
ALTER TABLE STUDENT -> MODIFY SDateofBirth DATE DEFAULT '2000-05-15';
H. Remove an Attribute
ALTER TABLE table_name DROP attribute;
ALTER TABLE GUARDIAN DROP income;
I. Remove Primary Key
ALTER TABLE table_name DROP PRIMARY KEY;
ALTER TABLE GUARDIAN DROP PRIMARY KEY;
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 TABLE table_name;
DROP DATABASE database_name;
Dropping a database ultimately removes all the tables within it.
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.
9.5.1 Insertion of Records
INSERT INTO is used to insert new records into a table.
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.
Insert Record into GUARDIAN
INSERT INTO GUARDIAN -> VALUES (444444444444, 'Amit Ahuja', 5711492685, 'G-35,Ashok vihar, Delhi' );
To insert values only into selected attributes:
INSERT INTO tablename (column1, column2, ...) VALUES (value1, value2, ...);
INSERT INTO GUARDIAN(GUID, GName, GAddress) -> VALUES (333333333333, 'Danny Dsouza', 'S -13, Ashok Village, Daman' );
STUDENT Table Example
| RollNumber | SName | SDateofBirth | GUID |
|---|---|---|---|
| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |
| 2 | Daizy Bhutia | 2002-02-28 | 111111111111 |
| 3 | Taleem Shah | 2002-02-28 | NULL |
| 4 | John Dsouza | 2003-08-18 | 333333333333 |
| 5 | Ali Shah | 2003-07-05 | 101010101010 |
| 6 | Manika P. | 2002-03-10 | 466444444666 |
INSERT INTO STUDENT -> VALUES(1,'Atharv Ahuja','2003-05-15', 444444444444);
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');
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
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 |
|---|---|---|---|---|
| 101 | Aaliya | 10000 | 234 | D02 |
| 102 | Kritika | 60000 | 123 | D01 |
| 103 | Shabbir | 45000 | 566 | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
| 105 | Joseph | 34000 | 875 | D03 |
| 106 | Sanya | 48000 | 695 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
| 108 | Nachaobi | 29000 | NULL | D05 |
| 109 | Daribha | 42000 | NULL | D04 |
| 110 | Tanya | 50000 | 467 | D05 |
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;
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;
Example 9.7 — OR
SELECT * FROM EMPLOYEE WHERE DeptId = 'D01' OR DeptId = 'D02' OR DeptId = 'D04';
E. Membership Operator IN
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
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%';
9.7 Data Updation and Deletion
Updation and deletion are also part of SQL Data Manipulation Language (DML).
9.7.1 Data Updation
UPDATE table_name SET attribute1 = value1, attribute2 = value2, ... WHERE condition;
Example
UPDATE STUDENT -> SET GUID = 101010101010 -> WHERE RollNumber = 3;
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 FROM table_name WHERE condition;
Example
DELETE FROM STUDENT WHERE RollNumber = 2;
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
9.8.1 Single Row Functions
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
| 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";
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.
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;
9.10 Operations on Relations
The textbook describes operations such as UNION, INTERSECT, MINUS and Cartesian Product.
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 |
|---|---|---|
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
| 1 | Mehak | 8A |
| 3 | Lavanya | 7A |
| 5 | Abhay | 8A |
9.10.2 INTERSECT (∩)
INTERSECT returns the common tuples from two tables.
| SNo | Name | Class |
|---|---|---|
| 2 | Mahira | 6A |
| 4 | Sanjay | 7A |
9.10.3 MINUS (-)
MINUS returns rows that are present in the first table but not in the second table.
| SNo | Name | Class |
|---|---|---|
| 1 | Mehak | 8A |
| 3 | Lavanya | 7A |
| 5 | Abhay | 8A |
9.10.4 Cartesian Product (X)
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
Degree = 3
Cardinality = 4
Degree = 3
Cardinality = 5
Degree = 6
Cardinality = 20
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;
9.11.2 JOIN on Two Tables
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 |
|---|---|---|
| 1 | Shirt | White |
| 2 | Pant | Grey |
| 3 | Tie | Blue |
| UCode | Size | Price |
|---|---|---|
| 1 | L | 580 |
| 1 | M | 500 |
| 2 | L | 890 |
| 2 | M | 810 |
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.
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.
Questions & Answers
1-Mark Questions
2-Mark Questions
3-Mark Questions
- 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.
4/5-Mark Questions
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.
⚡ 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 database | CREATE DATABASE |
| Select database | USE |
| View databases | SHOW DATABASES |
| Create table | CREATE TABLE |
| View table structure | DESCRIBE / DESC |
| View tables | SHOW TABLES |
| Modify table structure | ALTER TABLE |
| Remove table/database | DROP |
| Insert records | INSERT INTO |
| Retrieve records | SELECT |
| Modify records | UPDATE |
| Remove records | DELETE |
Important Operators / Clauses
| Item | Purpose |
|---|---|
| WHERE | Applies conditions. |
| DISTINCT | Removes repetition. |
| BETWEEN | Checks an inclusive range. |
| IN | Checks membership in a list. |
| NOT IN | Excludes specified values. |
| IS NULL | Checks NULL values. |
| IS NOT NULL | Checks non-NULL values. |
| LIKE | Pattern matching. |
| ORDER BY | Orders query output. |
| GROUP BY | Groups rows. |
| HAVING | Applies conditions with grouped rows. |
LIKE Wildcards
| Symbol | Meaning |
|---|---|
| % | Zero, one or multiple characters. |
| _ | Exactly one character. |
Important Functions
| Category | Functions |
|---|---|
| Math | POWER(), POW(), ROUND(), MOD() |
| String | UCASE(), UPPER(), LOWER(), LCASE(), MID(), SUBSTRING(), SUBSTR(), LENGTH(), LEFT(), RIGHT(), INSTR(), LTRIM(), RTRIM(), TRIM() |
| Date and Time | NOW(), DATE(), MONTH(), MONTHNAME(), YEAR(), DAY(), DAYNAME() |
| Aggregate | MAX(), 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 |
|---|---|
| UNION | Combines rows from two relations and removes duplicate rows. |
| INTERSECT | Returns common tuples. |
| MINUS | Returns tuples in the first relation but not the second. |
| Cartesian Product | Produces 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.
Textbook Exercise — Chapter 9
Exercise 1
- Define RDBMS. Name any two RDBMS software.
- State the purpose of ORDER BY and GROUP BY.
- Give two differences between Single Row Functions and Aggregate Functions.
- Explain Cartesian Product.
- Differentiate ALTER and UPDATE; DELETE and DROP.
- 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 |
|---|---|---|---|---|---|
| 001 | Hindi_Movie | Musical | 2018-04-23 | 124500 | 130000 |
| 002 | Tamil_Movie | Action | 2016-05-17 | 112000 | 118000 |
| 003 | English_Movie | Horror | 2017-08-06 | 245000 | 360000 |
| 004 | Bengali_Movie | Adventure | 2017-01-04 | 72000 | 100000 |
| 005 | Telugu_Movie | Action | – | 100000 | – |
| 006 | Punjabi_Movie | Comedy | – | 30500 | – |
Write SQL queries to:
- Display all information from Movie.
- Display MovieID, MovieName and Total_Earning, where Total_Earning is ProductionCost + BusinessCost.
- List different movie categories.
- Find NetProfit as BusinessCost − ProductionCost.
- List movies with ProductionCost greater than 10,000 and less than 1,00,000.
- List movies in Comedy or Action categories.
- 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 |
|---|---|---|---|---|---|
| M1 | 2018-07-17 | 1 | 2 | 90 | 86 |
| M2 | 2018-07-18 | 3 | 4 | 45 | 48 |
| M3 | 2018-07-19 | 1 | 3 | 78 | 56 |
| M4 | 2018-07-19 | 2 | 4 | 56 | 67 |
| M5 | 2018-07-18 | 1 | 4 | 32 | 87 |
| M6 | 2018-07-17 | 2 | 3 | 67 | 51 |
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 |
|---|---|---|---|
| P01 | Washing Powder | 120 | Surf |
| P02 | Toothpaste | 54 | Colgate |
| P03 | Soap | 25 | Lux |
| P04 | Toothpaste | 65 | Pepsodent |
| P05 | Soap | 38 | Dove |
| P06 | Shampoo | 245 | Dove |
The textbook asks students to:
- Create Product with suitable data types and constraints.
- Identify the primary key.
- Display Product Code, Product name and price in descending order of product name and, for equal names, ascending order of price.
- Add Discount.
- Calculate 10% discount when UPrice is more than 100; otherwise discount is 0.
- Increase price by 12% for products manufactured by Dove.
- Display total products manufactured by each manufacturer.
- Find output of AVG(UPrice) grouped by PName.
- Find distinct manufacturers.
- Find COUNT(DISTINCT PName).
- 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.