Q1. SQL stands for:
SQL is the standard language used to define, manipulate and retrieve data in relational databases.
Complete curriculum textbook chapter document for reading and offline study.
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Complete study notes based on the uploaded 32-page NCERT chapter, with clear concepts, MySQL syntax, worked examples, tables and revision material.
A Relational Database Management System (RDBMS) allows us to create databases consisting of relations (tables), connect related tables, and store, retrieve and manipulate data. Examples include MySQL, Microsoft SQL Server, PostgreSQL and Oracle.
This chapter uses MySQL to create and work with a school database named StudentAttendance. The example database has three related tables:
| Table | Information stored | Important attributes |
|---|---|---|
| STUDENT | Student information | RollNumber, SName, SDateofBirth, GUID |
| GUARDIAN | Guardian information | GUID, GName, GPhone, GAddress |
| ATTENDANCE | Daily attendance | AttendanceDate, RollNumber, AttendanceStatus |
STUDENT.GUID refers to GUARDIAN.GUID. ATTENDANCE.RollNumber refers to STUDENT.RollNumber.
SQL stands for Structured Query Language. It is the standard language used to communicate with relational database systems. SQL is used to define database structures, declare constraints, insert/update/delete records and retrieve information.
;).MySQL is open-source RDBMS software. The textbook gives the official download site as https://dev.mysql.com/downloads. After installation, start the MySQL service and open the MySQL shell/client. The mysql> prompt indicates readiness to accept SQL statements. For a multi-line statement, MySQL may show -> as the continuation prompt; enter the semicolon after the final line.
mysql> SHOW DATABASES;
mysql> USE StudentAttendance;
mysql> SHOW TABLES;
A data type specifies what kind of value an attribute (column) can store. It determines the valid values and the operations meaningful for that attribute.
| Type | Description | Example / use |
|---|---|---|
CHAR(n) | Fixed-length character string. The chapter describes n from 0 to 255. Shorter values are padded with spaces. | CHAR(10) for a fixed-length code. |
VARCHAR(n) | Variable-length character string, up to the declared maximum. Actual storage depends on the entered string length. Maximum depends on MySQL limits. | VARCHAR(30) for names. |
INT | Integer. Textbook: 4 bytes; −2147483648 to 2147483647. | Roll number, count. |
BIGINT | Larger integer type. Textbook: 8 bytes. | Very large integer values. |
FLOAT | Number that can contain a decimal point. Textbook: 4 bytes. | Decimal measurements. |
DATE | Date in YYYY-MM-DD format. Textbook range: 1000-01-01 to 9999-12-31. | '2003-05-15' |
CHAR(10) reserves a fixed 10-character field. A value such as CITY is padded to the defined length.
VARCHAR(30) allows up to 30 characters, but stores according to the actual string length.
RollNumber INT – numeric roll number.SName VARCHAR(20) – names have varying lengths.SDateofBirth DATE – date value.GUID CHAR(12) – fixed-length 12-character identifier.A constraint is a restriction on the values that an attribute can contain. Constraints help maintain accuracy and reliability. Not every column must have a constraint.
| Constraint | Purpose | Example |
|---|---|---|
NOT NULL | Column cannot contain NULL. | SName VARCHAR(20) NOT NULL |
UNIQUE | Prevents duplicate values in a column. | GPhone CHAR(10) UNIQUE |
DEFAULT | Supplies a value when one is not provided. | Status CHAR(1) DEFAULT 'P' |
PRIMARY KEY | Uniquely identifies each row; cannot be NULL. | PRIMARY KEY (RollNumber) |
FOREIGN KEY | Refers to a key in another table to establish a relationship. | FOREIGN KEY (GUID) REFERENCES GUARDIAN(GUID) |
A primary key has the essential properties of uniqueness and non-NULL values. The combination of UNIQUE and NOT NULL enforces those properties, while PRIMARY KEY explicitly declares the table's identifier. A foreign-key value must match an existing referenced key unless it is NULL and NULL is permitted.
Data Definition Language (DDL) contains commands for defining database and table structures (schemas), data types and constraints.
CREATE DATABASE – creates a database.CREATE TABLE – creates a table.DESCRIBE / DESC – displays table structure.ALTER TABLE – changes table structure.DROP TABLE / DROP DATABASE – permanently removes objects.CREATE DATABASE database_name;Example:
CREATE DATABASE StudentAttendance;
Select the database before creating tables or querying it:
USE StudentAttendance;
SHOW DATABASES;
USE StudentAttendance;
SHOW TABLES;SHOW DATABASES; lists databases on the server. SHOW TABLES; lists tables in the currently selected database. A newly created database initially has no tables.
CREATE TABLE defines a relation by specifying its column names, data types and optional constraints. The number of columns is the degree of the relation.
CREATE TABLE table_name (
attribute1 datatype constraint,
attribute2 datatype constraint,
attribute3 datatype constraint
);
CREATE TABLE STUDENT (
RollNumber INT,
SName VARCHAR(20),
SDateofBirth DATE,
GUID CHAR(12),
PRIMARY KEY (RollNumber)
);
RollNumber uniquely identifies a student. SName stores a variable-length name; SDateofBirth stores a date; GUID stores a 12-character guardian identifier.
| Table | Attribute | Type | Constraint / role |
|---|---|---|---|
| STUDENT | RollNumber | INT | PRIMARY KEY |
| STUDENT | SName | VARCHAR(20) | NOT NULL |
| STUDENT | SDateofBirth | DATE | NOT NULL |
| STUDENT | GUID | CHAR(12) | FOREIGN KEY |
| GUARDIAN | GUID | CHAR(12) | PRIMARY KEY |
| GUARDIAN | GName | VARCHAR(20) | NOT NULL |
| GUARDIAN | GPhone | CHAR(10) | UNIQUE; may be NULL |
| GUARDIAN | GAddress | VARCHAR(30) | NOT NULL |
| ATTENDANCE | AttendanceDate | DATE | Part of composite primary key |
| ATTENDANCE | RollNumber | INT | Part of composite primary key; FOREIGN KEY |
| ATTENDANCE | AttendanceStatus | CHAR(1) | NOT NULL (P/A) |
Complete example with constraints declared during table creation:
CREATE TABLE GUARDIAN (
GUID CHAR(12) PRIMARY KEY,
GName VARCHAR(20) NOT NULL,
GPhone CHAR(10) UNIQUE,
GAddress VARCHAR(30) NOT NULL
);
CREATE TABLE ATTENDANCE (
AttendanceDate DATE,
RollNumber INT,
AttendanceStatus CHAR(1) NOT NULL,
PRIMARY KEY (AttendanceDate, RollNumber)
);
The ATTENDANCE primary key is composite because the same student has many attendance dates and each date has many students. The pair (AttendanceDate, RollNumber) identifies one attendance entry.
Use DESCRIBE to see the structure of a table. MySQL also supports the short form DESC.
DESCRIBE STUDENT;
-- Short form:
DESC STUDENT;The output includes Field (column name), Type (data type), Null (whether NULL is allowed), Key, Default and Extra. DESC is for viewing structure; it does not display table records.
SELECT * FROM STUDENT;DESC STUDENT; describes the table. SELECT * FROM STUDENT; displays its records.ALTER TABLE changes the structure of an existing table: add or remove a column, modify a data type, or add/remove constraints.
ALTER TABLE GUARDIAN
ADD PRIMARY KEY (GUID);
ALTER TABLE ATTENDANCE
ADD PRIMARY KEY (AttendanceDate, RollNumber);
ALTER TABLE table_name
ADD FOREIGN KEY (column_name)
REFERENCES referenced_table (referenced_column);Example – STUDENT.GUID refers to GUARDIAN.GUID:
ALTER TABLE STUDENT
ADD FOREIGN KEY (GUID)
REFERENCES GUARDIAN (GUID);
Before adding a foreign key, the referenced table must exist; the referenced column must be an eligible key; and the referencing and referenced columns should have matching data types and sizes.
ALTER TABLE GUARDIAN
ADD UNIQUE (GPhone);
ALTER TABLE GUARDIAN
ADD income INT;
ALTER TABLE GUARDIAN
MODIFY GAddress VARCHAR(40);
ALTER TABLE STUDENT
MODIFY SName VARCHAR(20) NOT NULL;When using MODIFY, specify the data type along with the constraint.
ALTER TABLE STUDENT
MODIFY SDateofBirth DATE DEFAULT '2000-05-15';
ALTER TABLE GUARDIAN
DROP income;
ALTER TABLE GUARDIAN
DROP PRIMARY KEY;
DROP permanently removes a database object. It cannot be treated like deleting one row.
DROP TABLE table_name;
DROP TABLE ATTENDANCE;DROP DATABASE database_name;
DROP DATABASE StudentAttendance;INSERT INTO adds new rows to a table.
INSERT INTO table_name
VALUES (value1, value2, ...);INSERT INTO GUARDIAN
VALUES ('444444444444', 'Amit Ahuja',
'5711492685', 'G-35, Ashok Vihar, Delhi');
When column names are omitted, provide one value for every column in the correct order.
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);INSERT INTO GUARDIAN (GUID, GName, GAddress)
VALUES ('333333333333', 'Danny Dsouza',
'S-13, Ashok Village, Daman');
GPhone is omitted, so it receives NULL or its permitted default value.
INSERT INTO STUDENT
VALUES (1, 'Atharv Ahuja', '2003-05-15',
'444444444444');
-- Equivalent form with column names
INSERT INTO STUDENT
(RollNumber, SName, SDateofBirth, GUID)
VALUES (1, 'Atharv Ahuja', '2003-05-15',
'444444444444');
INSERT INTO STUDENT
VALUES (3, 'Taleem Shah', '2002-02-28', NULL);
-- Or omit the GUID column
INSERT INTO STUDENT (RollNumber, SName, SDateofBirth)
VALUES (3, 'Taleem Shah', '2002-02-28');
SELECT retrieves information from tables. Its output is displayed in tabular form.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
SELECT specifies the columns, FROM identifies the source table, and optional WHERE filters rows.
SELECT * FROM STUDENT;The asterisk (*) represents all columns.
SELECT SName, SDateofBirth
FROM STUDENT;
SELECT SName, SDateofBirth
FROM STUDENT
WHERE RollNumber = 1;The textbook's OFFICE database contains an EMPLOYEE table and related tables such as DEPARTMENT. DeptId in EMPLOYEE identifies the department and acts as a foreign key.
| 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 |
Use these sample records to understand the SELECT examples that follow.
AS assigns a temporary alias to a column in the query result. It does not rename the actual database column.
SELECT Ename AS Name
FROM EMPLOYEE;
SQL can calculate expressions in a query. For annual salary, multiply monthly Salary by 12:
SELECT Ename AS Name, Salary * 12
FROM EMPLOYEE;
SELECT Ename AS Name,
Salary * 12 AS 'Annual Salary'
FROM EMPLOYEE;If an alias contains a space, enclose it in quotes. The calculated Annual Salary is only in the output; it is not stored as a new column.
By default, repeated values may appear in query results. DISTINCT returns only distinct values.
SELECT DISTINCT DeptId
FROM EMPLOYEE;To find distinct salaries in department D01:
SELECT DISTINCT Salary
FROM EMPLOYEE
WHERE DeptId = 'D01';WHERE retrieves only those rows that satisfy a condition.
| Operator | Meaning | Example |
|---|---|---|
= | Equal to | DeptId = 'D01' |
< | Less than | Salary < 30000 |
<= | Less than or equal | Salary <= 30000 |
> | Greater than | Salary > 50000 |
>= | Greater than or equal | Salary >= 50000 |
!= | Not equal to | DeptId != 'D01' |
Every condition connected by AND must be true.
SELECT *
FROM EMPLOYEE
WHERE Salary > 5000 AND DeptId = 'D04';
At least one condition connected by OR must be true.
SELECT *
FROM EMPLOYEE
WHERE DeptId = 'D01' OR DeptId = 'D02';
NOT reverses a condition.
SELECT *
FROM EMPLOYEE
WHERE NOT Ename = 'Aaliya';
To find employees with salaries between 20,000 and 50,000 inclusive using comparison operators:
SELECT Ename, DeptId
FROM EMPLOYEE
WHERE Salary >= 20000 AND Salary <= 50000;
BETWEEN checks whether a value lies within a range. The lower and upper boundary values are included.
SELECT Ename, DeptId
FROM EMPLOYEE
WHERE Salary BETWEEN 20000 AND 50000;Equivalent condition:
WHERE Salary >= 20000 AND Salary <= 50000
IN compares a value with a list and returns rows where the value matches any item in the list.
SELECT *
FROM EMPLOYEE
WHERE DeptId IN ('D01', 'D02', 'D04');This is shorter than joining the same comparisons with OR.
NOT IN excludes the values in the list.
SELECT *
FROM EMPLOYEE
WHERE DeptId NOT IN ('D01', 'D02');
| Operator | Use |
|---|---|
| BETWEEN A AND B | Range including A and B. |
| IN (A, B, C) | Match any listed value. |
| NOT IN (A, B) | Exclude listed values. |
ORDER BY arranges query output according to one or more columns. Ascending order is the default.
SELECT *
FROM EMPLOYEE
ORDER BY Salary;
-- Explicit ascending order
SELECT *
FROM EMPLOYEE
ORDER BY Salary ASC;
SELECT *
FROM EMPLOYEE
ORDER BY Salary DESC;
DESC means descending. Multiple sort columns may be supplied; the later column is used when earlier sort values tie.
SELECT *
FROM EMPLOYEE
ORDER BY Salary ASC, Bonus DESC;NULL represents missing, unknown or not-applicable information. It is not the same as zero or an empty string. Arithmetic involving NULL generally produces NULL because the result is unknown.
SELECT *
FROM EMPLOYEE
WHERE Bonus IS NULL;This finds employees who have not been assigned a bonus.
SELECT Ename
FROM EMPLOYEE
WHERE Bonus IS NOT NULL;Bonus = NULL. Use Bonus IS NULL or Bonus IS NOT NULL.LIKE is used with WHERE when an exact match is not required and we want to search for a character pattern or substring.
| Wildcard | Meaning |
|---|---|
% | Zero, one or multiple characters. |
_ | Exactly one character. |
SELECT *
FROM EMPLOYEE
WHERE Ename LIKE 'K%';
SELECT *
FROM EMPLOYEE
WHERE Ename LIKE '%a';
SELECT *
FROM EMPLOYEE
WHERE Ename LIKE '_ANYA';_ matches one first character; ANYA matches the remaining four.
SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE '%se%';
SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE '_a%';
| Pattern | Meaning |
|---|---|
'A%' | Starts with A |
'%A' | Ends with A |
'%A%' | Contains A anywhere |
'_A%' | Second character is A |
'A_' | Exactly two characters, first is A |
'__A%' | Third character is A |
UPDATE modifies existing values in one or more columns of selected records.
UPDATE table_name
SET column1 = value1,
column2 = value2
WHERE condition;
Set GUID for student RollNumber 3:
UPDATE STUDENT
SET GUID = '101010101010'
WHERE RollNumber = 3;
UPDATE GUARDIAN
SET GAddress = 'WZ-68, Azad Avenue, Bijnour, MP',
GPhone = '4817362092'
WHERE GUID = '466444444666';
SELECT * FROM GUARDIAN;
DELETE removes one or more records from a table. It does not remove the table structure.
DELETE FROM table_name
WHERE condition;
Example: Delete the student whose RollNumber is 2:
DELETE FROM STUDENT
WHERE RollNumber = 2;
Verify the remaining records:
SELECT * FROM STUDENT;
| Command / clause | Purpose | Syntax reminder |
|---|---|---|
| CREATE DATABASE | Create a database | CREATE DATABASE db; |
| USE | Select a database | USE db; |
| SHOW TABLES | List tables in active database | SHOW TABLES; |
| CREATE TABLE | Create table structure | CREATE TABLE t (...); |
| DESC | Show table structure | DESC t; |
| ALTER TABLE | Change table structure | ALTER TABLE t ADD ...; |
| DROP | Remove table/database | DROP TABLE t; |
| INSERT | Add records | INSERT INTO t VALUES (...); |
| SELECT | Retrieve data | SELECT * FROM t; |
| DISTINCT | Remove repeated result values | SELECT DISTINCT c FROM t; |
| WHERE | Filter records | SELECT * FROM t WHERE ...; |
| BETWEEN | Inclusive range test | c BETWEEN x AND y |
| IN | Match a list | c IN (x,y) |
| ORDER BY | Sort result | ORDER BY c DESC |
| IS NULL | Find missing values | WHERE c IS NULL |
| LIKE | Pattern matching | WHERE c LIKE 'A%' |
| UPDATE | Modify records | UPDATE t SET c=v WHERE ...; |
| DELETE | Delete records | DELETE FROM t WHERE ...; |
| Pair | Difference |
|---|---|
| CHAR / VARCHAR | CHAR is fixed-length; VARCHAR is variable-length. |
| PRIMARY KEY / FOREIGN KEY | Primary key identifies a row in its own table; foreign key refers to a key in another table. |
| DESC / ORDER BY ... DESC | DESC table describes table structure; DESC after ORDER BY sorts descending. |
| ALTER / UPDATE | ALTER changes table structure; UPDATE changes stored values. |
| DELETE / DROP | DELETE removes rows; DROP removes a table or database object. |
| AND / OR | AND requires all conditions true; OR requires at least one condition true. |
| BETWEEN / IN | BETWEEN checks a range; IN checks membership in a list. |
| % / _ | % matches zero or more characters; _ matches exactly one character. |
= NULL instead of IS NULL.The uploaded chapter ends with exercises covering the following skills. Use these as a checklist while practising:
Step-by-step solved textbook exercises, derivations, and solutions.
Class XI – Informatics Practices (065)
| SQL clause / command | Correct function |
|---|---|
| ALTER | Change the structure of a table or a column |
| UPDATE | Update existing information in a table |
| DELETE | Delete an existing row from a table |
| INSERT INTO | Insert the values in a table |
| CONSTRAINTS | Restrictions on columns |
| DESC | Display the structure of a table |
| CREATE | Create a database or table |
Explanation: ALTER modifies table structure; UPDATE changes existing record values; DELETE removes records; INSERT INTO adds records; constraints restrict column values; DESC displays table structure; CREATE creates database objects.
CREATE TABLE student (
name CHAR(30),
student_id INT,
gender CHAR(1),
PRIMARY KEY (student_id)
);
Options: (i) 30 (ii) 1 (iii) 3 (iv) 4
Options: (i) A table (ii) A row (iii) A column (iv) A database
SelecT * fROM student;
Options: (i) Displays contents of table student; (ii) Displays column names and contents; (iii) Error due to improper case; (iv) Displays only column names.
INSERT INTO student
VALUES ("Suhana",109,'F'),
("Rivaan",102,'M'),
("Atharv",103,'M'),
("Rishika",105,'F'),
("Garvit",104,'M'),
("Shaurya",109,'M');
Options: (i) Error (ii) No Error (iii) Depends on compiler (iv) Successful completion
Correct multi-row syntax (still fails because 109 is duplicated):
INSERT INTO student
VALUES
('Suhana', 109, 'F'),
('Rivaan', 102, 'M'),
('Atharv', 103, 'M'),
('Rishika', 105, 'F'),
('Garvit', 104, 'M'),
('Shaurya', 109, 'M');
DELETE student WHERE student_id = 109;
Options: (i) 1 row; (ii) All rows where student_id is 109; (iii) No row; (iv) 2 rows.
DELETE FROM student WHERE student_id = 109;
Options: (i) Primary Key (ii) Foreign Key (iii) Composite Key (iv) Secondary Key
Options: (i) All data from the table (ii) Data of primary key only (iii) NULL data (iv) None of the mentioned
SELECT * FROM student;
This query retrieves all columns from the specified 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 | NULL | 100000 | NULL |
| 006 | Punjabi_Movie | Comedy | NULL | 30500 | NULL |
SELECT * FROM MOVIE;
SELECT * retrieves all columns and all records from MOVIE.
SELECT MovieID, MovieName, BusinessCost FROM MOVIE;
SELECT DISTINCT Category FROM MOVIE;
Expected output:
| Category |
|---|
| Musical |
| Action |
| Horror |
| Adventure |
| Comedy |
DISTINCT eliminates duplicate values from the result.
Hint: Net Profit = BusinessCost − ProductionCost.
SELECT
MovieID,
MovieName,
BusinessCost - ProductionCost AS NetProfit
FROM MOVIE;
Expected output:
| MovieID | MovieName | NetProfit |
|---|---|---|
| 001 | Hindi_Movie | 5500 |
| 002 | Tamil_Movie | 6000 |
| 003 | English_Movie | 115000 |
| 004 | Bengali_Movie | 28000 |
| 005 | Telugu_Movie | NULL |
| 006 | Punjabi_Movie | NULL |
Is NetProfit a part of the MOVIE relation? No. It is a calculated/derived column created in the query output, not a permanent attribute of MOVIE.
What happens for a movie which has not yet released? The result is NULL, not zero, because BusinessCost is NULL and arithmetic involving NULL produces NULL.
SELECT MovieID, MovieName, ProductionCost FROM MOVIE WHERE ProductionCost > 80000 AND ProductionCost < 125000;
Expected output:
| MovieID | MovieName | ProductionCost |
|---|---|---|
| 001 | Hindi_Movie | 124500 |
| 002 | Tamil_Movie | 112000 |
| 005 | Telugu_Movie | 100000 |
AND requires both conditions to be true.
SELECT * FROM MOVIE WHERE Category = 'Comedy' OR Category = 'Action';
Alternative using IN:
SELECT *
FROM MOVIE
WHERE Category IN ('Comedy', 'Action');
Matching movies: Tamil_Movie, Telugu_Movie and Punjabi_Movie.
SELECT * FROM MOVIE WHERE ReleaseDate IS NULL;
IS NULL checks missing or unknown values. Do not use = NULL.
The school wants to conduct cricket matches between Class XI and Class XII. Four teams are Team Titan, Team Rockers, Team Magnet and Team Hurricane.
CREATE DATABASE Sports; USE Sports;
TeamID stores integer values from 1 to 9 and uniquely identifies a team. TeamName is a string of at least 10 characters.
CREATE TABLE TEAM
(
TeamID INT,
TeamName VARCHAR(30),
CHECK (TeamID BETWEEN 1 AND 9),
CHECK (CHAR_LENGTH(TeamName) >= 10)
);
ALTER TABLE TEAM ADD PRIMARY KEY (TeamID);
Alternatively, define PRIMARY KEY (TeamID) inside CREATE TABLE.
DESC TEAM;
Alternative: DESCRIBE TEAM;
INSERT INTO TEAM VALUES (1, 'Team Titan'), (2, 'Team Rockers'), (3, 'Team Magnet'), (4, 'Team Hurricane');
SELECT * FROM TEAM;
Expected output:
| TeamID | TeamName |
|---|---|
| 1 | Team Titan |
| 2 | Team Rockers |
| 3 | Team Magnet |
| 4 | Team Hurricane |
| 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-20 | 1 | 4 | 32 | 87 |
| M6 | 2018-07-21 | 2 | 3 | 67 | 51 |
CREATE TABLE MATCH_DETAILS
(
MatchID CHAR(2),
MatchDate DATE,
FirstTeamID INT,
SecondTeamID INT,
FirstTeamScore INT,
SecondTeamScore INT,
PRIMARY KEY (MatchID)
);
INSERT INTO MATCH_DETAILS
VALUES
('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-20', 1, 4, 32, 87),
('M6', '2018-07-21', 2, 3, 67, 51);
ALTER TABLE MATCH_DETAILS ADD FOREIGN KEY (FirstTeamID) REFERENCES TEAM(TeamID); ALTER TABLE MATCH_DETAILS ADD FOREIGN KEY (SecondTeamID) REFERENCES TEAM(TeamID);
Both team ID columns refer to TEAM.TeamID. These constraints prevent references to team IDs that do not exist in TEAM.
Relations: TEAM(TeamID, TeamName) and MATCH_DETAILS(MatchID, MatchDate, FirstTeamID, SecondTeamID, FirstTeamScore, SecondTeamScore).
Relational Algebra:
\(\pi_{MatchID}(\sigma_{FirstTeamScore>70 \land SecondTeamScore>70}(MATCH\_DETAILS))\)
SQL:
SELECT MatchID FROM MATCH_DETAILS WHERE FirstTeamScore > 70 AND SecondTeamScore > 70;
Expected output: M1
Relational Algebra:
\(\pi_{MatchID}(\sigma_{FirstTeamScore<70 \land SecondTeamScore>70}(MATCH\_DETAILS))\)
SQL:
SELECT MatchID FROM MATCH_DETAILS WHERE FirstTeamScore < 70 AND SecondTeamScore > 70;
Expected output: M4, M5
Relational Algebra:
\(\pi_{MatchID,MatchDate}(\sigma_{FirstTeamID=1 \land FirstTeamScore>SecondTeamScore}(MATCH\_DETAILS))\)
SQL:
SELECT MatchID, MatchDate FROM MATCH_DETAILS WHERE FirstTeamID = 1 AND FirstTeamScore > SecondTeamScore;
Expected output:
| MatchID | MatchDate |
|---|---|
| M1 | 2018-07-17 |
| M3 | 2018-07-19 |
SELECT MatchID
FROM MATCH_DETAILS
WHERE
(
FirstTeamID = 2
AND FirstTeamScore <= SecondTeamScore
)
OR
(
SecondTeamID = 2
AND SecondTeamScore <= FirstTeamScore
);
Correct expected output: M4
In M4, Team 2 scored 56 while Team 4 scored 67, so Team 2 did not win. In M6, Team 2 scored 67 while Team 3 scored 51, so Team 2 won and M6 must not be included.
RENAME TABLE TEAM TO T_DATA; ALTER TABLE T_DATA RENAME COLUMN TeamID TO T_ID; ALTER TABLE T_DATA RENAME COLUMN TeamName TO T_NAME;
RENAME TABLE changes the table name. ALTER TABLE ... RENAME COLUMN changes column names.
| ALTER | UPDATE |
|---|---|
| ALTER is a DDL command. | UPDATE is a DML command. |
| It changes the structure of a table. | It changes existing records in a table. |
| It can add, remove or modify columns. | It modifies values stored in columns. |
| It does not directly update record values. | It does not change the table structure. |
ALTER example:
ALTER TABLE STUDENT ADD Email VARCHAR(50);
This adds a new column named Email.
UPDATE example:
UPDATE STUDENT SET Email = 'student@gmail.com' WHERE RollNo = 101;
This updates the Email value for the student whose RollNo is 101.
| DELETE | DROP |
|---|---|
| DELETE is a DML command. | DROP is a DDL command. |
| It removes records from a table. | It removes an entire database object, such as a table or database. |
| It can delete selected records using WHERE. | It removes the complete specified table or database. |
| Table structure remains after deletion. | The dropped table structure is also removed. |
DELETE example:
DELETE FROM STUDENT WHERE RollNo = 101;
DROP example:
DROP TABLE STUDENT;
DELETE removes matching records; DROP removes the table structure and its records.
STUDENT: RollNo, Name, Stream, Section, RegistrationID
Stream values: Science, Commerce or Humanities. Section values: I or II.
PROJECT_ASSIGNED: RegistrationID, ProjectID, AssignDate
PROJECT: ProjectID, ProjectName, SubmissionDate, TeamSize, GuideTeacher
CREATE DATABASE STUDENT_PROJECT; USE STUDENT_PROJECT;
CREATE TABLE STUDENT
(
RollNo INT,
Name VARCHAR(40) NOT NULL,
Stream VARCHAR(15),
Section CHAR(1),
RegistrationID INT,
PRIMARY KEY (RegistrationID),
UNIQUE (RollNo),
CHECK (Stream IN ('Science', 'Commerce', 'Humanities')),
CHECK (Section IN ('I', 'II'))
);
CREATE TABLE PROJECT
(
ProjectID INT,
ProjectName VARCHAR(50) NOT NULL,
SubmissionDate DATE,
TeamSize INT,
GuideTeacher VARCHAR(40),
PRIMARY KEY (ProjectID),
CHECK (TeamSize > 0)
);
CREATE TABLE PROJECT_ASSIGNED
(
RegistrationID INT,
ProjectID INT,
AssignDate DATE,
PRIMARY KEY (RegistrationID, ProjectID),
FOREIGN KEY (RegistrationID)
REFERENCES STUDENT(RegistrationID),
FOREIGN KEY (ProjectID)
REFERENCES PROJECT(ProjectID)
);
Insert into STUDENT:
INSERT INTO STUDENT VALUES (1, 'Aarav', 'Science', 'I', 1001), (2, 'Diya', 'Commerce', 'II', 1002), (3, 'Rohan', 'Humanities', 'I', 1003), (4, 'Meera', 'Commerce', 'I', 1004), (5, 'Kabir', 'Science', 'II', 1005);
Insert into PROJECT:
INSERT INTO PROJECT VALUES (101, 'Library Management', '2026-12-10', 3, 'Mr Sharma'), (102, 'Sales Analysis', '2026-12-15', 4, 'Ms Patel'), (103, 'Website Development', '2026-12-20', 3, 'Mr Sharma');
Insert into PROJECT_ASSIGNED:
INSERT INTO PROJECT_ASSIGNED VALUES (1001, 101, '2026-11-01'), (1002, 102, '2026-11-02'), (1003, 103, '2026-11-03'), (1004, 102, '2026-11-04'), (1005, 101, '2026-11-05');
The remaining sub-questions are answered below.
SELECT Name FROM STUDENT WHERE Stream = 'Science';
Expected output: Aarav, Kabir.
| Table | Primary key |
|---|---|
| STUDENT | RegistrationID |
| PROJECT_ASSIGNED | RegistrationID, ProjectID (composite primary key) |
| PROJECT | ProjectID |
| Table | Foreign key | References |
|---|---|---|
| STUDENT | None | — |
| PROJECT | None | — |
| PROJECT_ASSIGNED | RegistrationID | STUDENT(RegistrationID) |
| PROJECT_ASSIGNED | ProjectID | PROJECT(ProjectID) |
SELECT DISTINCT S.Name, P.GuideTeacher
FROM STUDENT S
JOIN PROJECT_ASSIGNED PA
ON S.RegistrationID = PA.RegistrationID
JOIN PROJECT P
ON PA.ProjectID = P.ProjectID
WHERE S.Stream = 'Commerce';
Expected output for the sample records:
| Name | GuideTeacher |
|---|---|
| Diya | Ms Patel |
| Meera | Ms Patel |
Join STUDENT with PROJECT_ASSIGNED using RegistrationID, then join PROJECT using ProjectID. Filter Commerce students and display their names and guide teachers.
EMPLOYEE: EMPLOYEE(AadhaarNo, Name, Address, Department, EmpID)
DEPENDENT: DEPENDENT(EmpID, DependentName, Relationship)
Assumption: EmpID uniquely identifies an employee and is the primary key in EMPLOYEE. It is a foreign key in DEPENDENT.
CREATE DATABASE EMP_DEPENDENT; USE EMP_DEPENDENT;
CREATE TABLE EMPLOYEE
(
AadhaarNo CHAR(12),
Name VARCHAR(40),
Address VARCHAR(100),
Department VARCHAR(30),
EmpID INT,
PRIMARY KEY (EmpID)
);
CREATE TABLE DEPENDENT
(
EmpID INT,
DependentName VARCHAR(40),
Relationship VARCHAR(20),
FOREIGN KEY (EmpID)
REFERENCES EMPLOYEE(EmpID)
);
SELECT E.Name, D.DependentName
FROM EMPLOYEE E
INNER JOIN DEPENDENT D
ON E.EmpID = D.EmpID;
INNER JOIN returns employees who have matching records in DEPENDENT.
SELECT * FROM EMPLOYEE WHERE Department = 'PRODUCTION';
SELECT E.Name
FROM EMPLOYEE E
LEFT JOIN DEPENDENT D
ON E.EmpID = D.EmpID
WHERE D.EmpID IS NULL;
LEFT JOIN keeps all employees. Where no dependent matches, dependent-side columns are NULL. IS NULL identifies those employees.
SELECT E.Name
FROM EMPLOYEE E
INNER JOIN DEPENDENT D
ON E.EmpID = D.EmpID
WHERE E.Department = 'SALES'
GROUP BY E.EmpID, E.Name
HAVING COUNT(D.DependentName) = 2;
WHERE filters SALES employees, GROUP BY groups their dependent records, COUNT counts dependents and HAVING selects employees with exactly two.
| UCode | UName | UColor |
|---|---|---|
| 1 | Shirt | White |
| 2 | Pant | Grey |
| 3 | Skirt | Grey |
| 4 | Tie | Blue |
| 5 | Socks | Blue |
| 6 | Belt | Blue |
| UCode | Size | Price |
|---|---|---|
| 1 | M | 500 |
| 1 | L | 580 |
| 1 | XL | 620 |
| 2 | M | 810 |
| 2 | L | 890 |
| 2 | XL | 940 |
| 3 | M | 770 |
| 3 | L | 830 |
| 3 | XL | 910 |
| 4 | S | 150 |
| 4 | L | 170 |
| 5 | S | 180 |
| 5 | L | 210 |
| 6 | M | 110 |
| 6 | L | 140 |
| 6 | XL | 160 |
RENAME TABLE PRICE TO COST;
Assume the new item is assigned UCode 7.
INSERT INTO COST VALUES (7, 'M', 100);
ALTER TABLE COST ADD CONSTRAINT FK_COST_UNIFORM FOREIGN KEY (UCode) REFERENCES UNIFORM(UCode);
Insert the handkerchief's details in UNIFORM first, then its price in COST:
INSERT INTO UNIFORM VALUES (7, 'Handkerchief', 'Red'); INSERT INTO COST VALUES (7, 'M', 100);
The foreign key ensures that COST.UCode must refer to an existing UNIFORM.UCode.
ALTER TABLE UNIFORM MODIFY UName VARCHAR(30) NOT NULL;
NOT NULL prevents a uniform record from being inserted without a name.
ALTER TABLE COST ADD CONSTRAINT CHECK_PRICE CHECK (Price > 0);
CHECK (Price > 0) ensures that the price must be greater than zero.
| Command | Purpose | Example |
|---|---|---|
| CREATE DATABASE | Create a database | CREATE DATABASE School; |
| USE | Select a database | USE School; |
| CREATE TABLE | Create a table | CREATE TABLE Student (...); |
| DESC | Display table structure | DESC Student; |
| INSERT INTO | Insert records | INSERT INTO Student VALUES (...); |
| SELECT | Retrieve records | SELECT * FROM Student; |
| DISTINCT | Remove duplicate values | SELECT DISTINCT City FROM Student; |
| WHERE | Apply conditions | WHERE Marks > 80; |
| UPDATE | Modify existing records | UPDATE Student SET Marks=90 WHERE RollNo=1; |
| DELETE | Delete records | DELETE FROM Student WHERE RollNo=1; |
| ALTER TABLE | Modify table structure | ALTER TABLE Student ADD Email VARCHAR(50); |
| RENAME TABLE | Rename a table | RENAME TABLE PRICE TO COST; |
| DROP TABLE | Remove a table | DROP TABLE Student; |
High-yield board questions, previous year questions (PYQs), and model answer keys.
50 Multiple-Choice Questions with answers and explanations
Select one option for each question. Click Check Answers to view your score and explanations. You can also reveal or hide all solutions.
SQL is the standard language used to define, manipulate and retrieve data in relational databases.
The MySQL shell displays the mysql> prompt when ready.
A semicolon marks the end of a complete SQL statement.
The chapter explains that SQL keywords are not case-sensitive.
CHAR(n) reserves a fixed character length.
VARCHAR(n) stores variable-length strings up to the declared maximum.
The chapter uses DATE for calendar dates in YYYY-MM-DD format.
The textbook specifies INT as a 4-byte integer.
NOT NULL requires a value for that column.
A primary key uniquely identifies each record and cannot be NULL.
A foreign key creates a relationship by referencing a key in another table.
A primary key combines uniqueness and non-null requirements.
CREATE DATABASE database_name; creates a database.
USE database_name; selects the database for subsequent operations.
CREATE TABLE defines the table structure and columns.
Degree is the number of attributes (columns) in a relation.
DESC is the short form of DESCRIBE.
ALTER TABLE can add, drop or modify columns and constraints.
DROP TABLE removes the table definition and its data.
INSERT INTO adds records to a table.
Without a column list, provide a value for every column in the table's defined order.
NULL represents missing, unknown or not-applicable data.
SELECT is the SQL query statement.
The asterisk requests all attributes/columns from the selected table.
FROM names the table from which data is retrieved.
WHERE restricts the result to rows satisfying the condition.
DISTINCT displays non-repeated result values.
BETWEEN includes both its lower and upper boundary values.
IN returns true when the tested value matches any value in the list.
ORDER BY arranges rows by one or more specified columns.
Ascending order is the default unless DESC is specified.
NULL must be tested with IS NULL, not the equality operator.
IS NOT NULL selects rows with a non-NULL value.
% can represent zero, one or multiple characters.
Underscore represents a single character.
K followed by % means K at the beginning and any number of characters after it.
The percent wildcard before a allows any preceding characters; a is the final character.
AND combines conditions that must all be satisfied.
OR is true when one or more conditions are true.
UPDATE changes values in existing rows.
WHERE identifies the record(s) to update. Without it, all rows are affected.
DELETE removes rows while retaining the table.
Without WHERE, DELETE applies to every row in the table.
Without WHERE, every row is subject to the SET operation.
ALTER TABLE ... ADD adds an attribute to an existing table.
The referenced table and its primary key must already exist and data types/sizes must match.
A table-level PRIMARY KEY can list multiple columns inside parentheses.
ALTER is a DDL operation; UPDATE is a DML operation.
DELETE removes records; DROP removes the database object itself.
The referenced record must exist before inserting a child row that references it.