Aimify IP Material
Class 11 · Chapter 8

Introduction to Structured Query Language (SQL)

In CBSE syllabusUnit 3: Database concepts and the Structured Query Language (30 marks)~30 periods
25 MCQs42 written Qs10 practicals

Overview

This chapter teaches students to create and use a relational database in MySQL with SQL. They learn the three command groups (DDL, DML, DQL), choose data types and constraints, build and alter tables, add, change and remove rows, and write SELECT queries that filter, match patterns, handle NULLs and sort results. Every example uses one STUDENT table whose outputs were produced by actually running the queries.

The whole chapter is in the CBSE 2025-26 syllabus: advantages of SQL, DDL/DQL/DML, introduction to MySQL, data types, CREATE DATABASE, CREATE TABLE, ALTER, DROP, INSERT, UPDATE, DELETE and SELECT with WHERE, relational and logical operators, BETWEEN, IS NULL and IS NOT NULL. IN, LIKE, DISTINCT, aliases and ORDER BY are covered by NCERT and regularly asked. Together with Chapter 7, this unit carries 30 marks in theory, and SQL queries are also tested in the practical exam (7 marks) and practical file (14 SQL queries).

Learning outcomes

  • Students will be able to state the advantages of SQL and classify commands as DDL, DML or DQL.
  • Students will be able to choose suitable data types (CHAR, VARCHAR, INT, FLOAT, DECIMAL, DATE) and explain the difference between CHAR and VARCHAR.
  • Students will be able to apply NOT NULL, UNIQUE, DEFAULT, PRIMARY KEY and FOREIGN KEY constraints while creating tables.
  • Students will be able to create, open, describe, alter and drop databases and tables in MySQL.
  • Students will be able to insert rows with all columns, selected columns and NULL values.
  • Students will be able to write SELECT queries using aliases, expressions, DISTINCT, WHERE, relational and logical operators, BETWEEN, IN, LIKE, IS NULL and ORDER BY.
  • Students will be able to modify and remove data using UPDATE and DELETE, and distinguish DELETE from DROP.
  • Students will be able to predict the output of a given query on a given table.

Lesson plan

Periods 1-2
Why SQL; command categories

Ask: "How would you find all students with more than 80 marks in a 2,000-row register?" Contrast a manual search with one SQL line. List the advantages of SQL. Students sort a jumbled list of commands into DDL, DML and DQL columns on the board.

Periods 3-4
MySQL client and data types

Lab: open the MySQL Command Line Client, show the mysql> and -> prompts and the semicolon rule. In class, students pick data types for a school admission form (name, PIN, mobile, fee, date of birth) and justify CHAR versus VARCHAR with the 'Ravi' example.

Periods 5-6
Constraints and keys

Recap candidate, primary and alternate keys. Pairs design STUDENT and FEE on paper, marking NOT NULL, UNIQUE, DEFAULT, PRIMARY KEY and FOREIGN KEY, and explain why a fee receipt must point to a real student.

Periods 7-8
CREATE DATABASE, USE, CREATE TABLE, DESC

Lab practicals 1 and 2: each student creates SCHOOL and STUDENT, then runs DESC and records it in the practical file. Discuss why Null = NO appears for the primary key.

Periods 9-10
ALTER TABLE and DROP

Lab: add, modify and drop a Phone column; create a table without a key and add the primary key later; create and drop a scratch table. Students track degree and cardinality after each statement.

Periods 11-12
INSERT and constraint errors

Lab practical 3: insert 10 rows, including NULLs and selected-column inserts. Deliberately insert a duplicate RollNo and a NULL Name, read the error messages aloud, and link each to its constraint.

Periods 13-14
SELECT, aliases, expressions, DISTINCT

Project the sample table. Students predict results on mini whiteboards before each query is run: chosen columns, Marks + 5 AS "After Grace", DISTINCT Section, DISTINCT Class, Gender.

Periods 15-17
WHERE, relational and logical operators

Practicals 4 and 5. Card game: each card holds a condition; students hold up the roll numbers that satisfy it. Run the bracketed and unbracketed AND/OR queries to show precedence.

Periods 18-19
BETWEEN, IN, LIKE

Practicals 6 to 8. Students write five LIKE patterns for their own classmates' names and swap with a partner to predict matches.

Periods 20-21
NULL handling and ORDER BY

Run = NULL and IS NULL side by side and discuss why the first silently returns nothing. Sort by marks ascending and descending and locate the NULL row each time.

Periods 22-23
UPDATE, DELETE, DELETE vs DROP

Practical 9. Show SELECT-first, then UPDATE/DELETE. Demonstrate DELETE FROM followed by SELECT (empty set) and DROP TABLE followed by SELECT (error) on a copy of the table.

Periods 24-27
Practical file and lab test

Practical 10 and the remaining practical-file queries (minimum 14 SQL queries). Timed lab test: create a table from a description, insert rows, and answer five queries.

Periods 28-30
Board-style practice

Solve the "write queries (i)-(v)" and output-prediction long questions, the case studies and the assertion-reason set. Peer-mark using the answer key.

Notes

What SQL is and why we use it

In a file-based system, a programmer has to write a separate program for every new question asked of the data. An RDBMS such as MySQL, Oracle, PostgreSQL or Microsoft SQL Server instead understands a common query language called SQL (Structured Query Language), usually read as "sequel" or "S-Q-L".

SQL is declarative (non-procedural): we say what data we want, not how to find it. For example, SELECT Name FROM STUDENT WHERE Marks > 80; simply states the need; the RDBMS decides how to search the table.

Advantages of using SQL

  • Easy to learn: statements use plain English words like SELECT, INSERT, UPDATE and DELETE.
  • Non-procedural: no loops or step-by-step logic are needed to fetch data.
  • Standard and portable: SQL is an ANSI/ISO standard, so the same basic statements work in MySQL, Oracle, SQL Server and others.
  • Does everything in one language: create tables, add and change data, apply rules (constraints) and query data.
  • Fast retrieval of large data: a single short query can search thousands of rows in a fraction of a second.
  • Multiple views of the same data: different users can see different columns and rows of the same table.
  • Supports many users at once and works in client-server and web applications.
Teacher tip

Board exams often ask for "any two/four advantages of SQL". Train students to write one line per point with a keyword in bold: easy, non-procedural, portable, fast, one language for all tasks.

Categories of SQL commands: DDL, DML and DQL

SQL statements are grouped by the job they do. The CBSE syllabus names three groups.

  • DDL (Data Definition Language) defines or changes the structure (schema) of the database: databases, tables, columns and constraints.
  • DML (Data Manipulation Language) changes the data stored in tables: adding, changing and removing rows.
  • DQL (Data Query Language) reads data without changing it. Its only statement is SELECT.

A simple test: if the statement changes what the table looks like, it is DDL; if it changes what is inside the table, it is DML; if it only shows data, it is DQL.

CategoryWorks onCommands in syllabusExample
DDLStructure (schema)CREATE DATABASE, CREATE TABLE, ALTER TABLE, DROPALTER TABLE STUDENT ADD Phone CHAR(10);
DMLRows of dataINSERT, UPDATE, DELETEUPDATE STUDENT SET Marks = 80 WHERE RollNo = 3;
DQLReading dataSELECTSELECT * FROM STUDENT;
Teacher tip

Many textbooks place SELECT under DML. For CBSE 2025-26, follow the syllabus wording and classify SELECT as DQL. Other groups such as DCL (GRANT, REVOKE) and TCL (COMMIT, ROLLBACK) exist but are not in the Class 11 syllabus.

Introduction to MySQL and rules for writing statements

MySQL is a free, open-source RDBMS that uses SQL. It is widely used in schools and in web applications. After installing MySQL Server (from dev.mysql.com), students open the MySQL Command Line Client, type the root password, and see the mysql> prompt. Every statement is typed at this prompt.

Rules to follow

  1. End every statement with a semicolon ;. Pressing Enter without it only moves to a continuation prompt ->.
  2. SQL keywords are not case-sensitive: select, SELECT and SeLeCt all work. Write keywords in capitals for readability.
  3. A statement may run over several lines; MySQL waits for the ;.
  4. Text (CHAR/VARCHAR) and date values go inside single quotes: 'Diya Menon', '2008-07-22'. Numbers do not need quotes.
  5. Dates are written in the format 'YYYY-MM-DD'.
  6. Table and database names may be case-sensitive on Linux servers, so always use the same spelling you used while creating them.
  7. A line starting with -- (two hyphens and a space) is a comment.
Text
mysql> SELECT Name, Marks
    -> FROM STUDENT
    -> WHERE Marks > 80;
Teacher tip

If a student sees -> and nothing happens, the semicolon is missing. Type ; and press Enter. If a quote is left open the prompt changes to '>; close the quote, then type ;.

Data types in MySQL

Every column must be given a data type. It decides which values the column can hold, how much space each value takes and which operations are allowed (we can add two INT values, but not two DATE values in the same way). Choosing the right type also catches wrong data early: MySQL rejects 'abc' in an INT column in strict mode.

The types needed for Class 11 are below.

Data typeStoresExample column and value
CHAR(n)Fixed-length text of exactly n characters (n from 0 to 255). Shorter values are padded with spaces.Gender CHAR(1) → 'F'; PinCode CHAR(6) → '110001'
VARCHAR(n)Variable-length text up to n characters (n up to 65,535). Only the actual characters are stored.Name VARCHAR(30) → 'Meera Nair'
INT / INTEGERWhole numbers, 4 bytes, from -2,147,483,648 to 2,147,483,647.Marks INT → 78
FLOATApproximate numbers with a decimal point, 4 bytes.Height FLOAT → 1.62
DECIMAL(p,s)Exact decimal numbers: p total digits, s digits after the point.Amount DECIMAL(8,2) → 4500.00 (max 999999.99)
DATEA date in 'YYYY-MM-DD' format, from '1000-01-01' to '9999-12-31'.DOB DATE → '2008-07-22'
Teacher tip

Phone numbers, PIN codes and Aadhaar numbers are stored as CHAR, not INT: they are never added or multiplied, they can start with 0, and a 10-digit mobile number is larger than the INT limit. Use DECIMAL, not FLOAT, for money because FLOAT can store 0.1 slightly inaccurately.

CHAR versus VARCHAR

Both store text, but they use space differently. Suppose a column is declared with size 10 and we store the word 'Ravi' (4 characters):

  • CHAR(10) reserves all 10 characters; the remaining 6 are filled with spaces (removed again when the value is displayed).
  • VARCHAR(10) stores only the 4 characters plus a small length prefix (1 byte here).

So CHAR suits values that always have the same length; VARCHAR suits values whose length changes from row to row.

PointCHAR(n)VARCHAR(n)
LengthFixedVariable
Space used for 'Ravi' in size 1010 characters4 characters + 1 length byte
Maximum n25565,535 (shared with the whole row)
SpeedSlightly faster (fixed positions)Slightly slower
Best forGender, Section, PIN code, mobile number, ICodeNames, addresses, e-mail IDs, city names
Teacher tip

A favourite 2-mark question: "Differentiate between CHAR and VARCHAR with an example." The 'Ravi' in size 10 example fetches full marks when the space used in each case is stated.

Constraints: rules on columns

A constraint is a rule attached to a column (or table) that the RDBMS checks on every INSERT and UPDATE. Rows that break the rule are rejected, which keeps the data correct and consistent. Constraints are optional, but good tables always have at least a primary key.

Recall from the previous chapter: a candidate key is any column (or set of columns) that can uniquely identify a row; the one we choose is the primary key and the others become alternate keys. In STUDENT, both RollNo and an AdmissionNo could be candidate keys.

ConstraintMeaningExample
NOT NULLThe column must always have a value; NULL is not accepted.Name VARCHAR(30) NOT NULL
UNIQUENo two rows may have the same value in this column. NULL is still allowed (and may appear more than once).Email VARCHAR(40) UNIQUE
DEFAULTValue used automatically when INSERT does not give one.Section CHAR(1) DEFAULT 'A'
PRIMARY KEYIdentifies each row uniquely. Works as UNIQUE + NOT NULL. Only one primary key per table (it may span several columns).RollNo INT PRIMARY KEY
FOREIGN KEYColumn whose values must match the primary key of another (parent) table, or be NULL. Links two tables.FOREIGN KEY (RollNo) REFERENCES STUDENT(RollNo)
Teacher tip

Ask students: "Can a table have two UNIQUE columns?" (Yes.) "Two primary keys?" (No, only one; but one primary key can be made of two columns, called a composite key.)

Creating and opening a database

A database is a container that holds related tables. MySQL already has some system databases (mysql, information_schema and others); we create our own for the school.

  • CREATE DATABASE name; creates an empty database.
  • SHOW DATABASES; lists all databases on the server.
  • USE name; makes it the current database, so later statements work inside it. MySQL replies Database changed.
  • SHOW TABLES; lists tables in the current database. A new database has none, so MySQL says Empty set.

Creating a database that already exists gives an error; CREATE DATABASE IF NOT EXISTS SCHOOL; avoids it.

MySQL
CREATE DATABASE SCHOOL;
SHOW DATABASES LIKE 'SCHOOL';
USE SCHOOL;
SHOW TABLES;
Output
Query OK, 1 row affected (0.00 sec)

+-------------------+
| Database (SCHOOL) |
+-------------------+
| SCHOOL            |
+-------------------+
1 row in set (0.00 sec)

Empty set (0.00 sec)
Teacher tip

After every new login, students must type USE SCHOOL; again. The error "No database selected" (ERROR 1046) means they forgot this step.

CREATE TABLE: defining the STUDENT table

CREATE TABLE gives the table a name and lists each column with its data type and optional constraints.

Syntax

CREATE TABLE table_name (column1 datatype [constraint], column2 datatype [constraint], ..., [table-level constraints]);

The STUDENT table below is used for every example in this chapter. RollNo is the primary key, Name may not be left empty, and Section is 'A' unless we say otherwise. Columns without NOT NULL accept NULL.

MySQL
CREATE TABLE STUDENT (
    RollNo  INT PRIMARY KEY,
    Name    VARCHAR(30) NOT NULL,
    Class   INT,
    Section CHAR(1) DEFAULT 'A',
    Gender  CHAR(1),
    DOB     DATE,
    Marks   INT
);
Output
Query OK, 0 rows affected (0.00 sec)
Teacher tip

Constraints can also be written at the end as table-level constraints, e.g. ..., Marks INT, PRIMARY KEY (RollNo));. A composite key can only be written this way: PRIMARY KEY (Class, Section, RollNo).

FOREIGN KEY: linking two tables

A school keeps fee receipts in a separate table FEE. Each receipt belongs to one student, so FEE has a RollNo column that must refer to a real RollNo in STUDENT. STUDENT is the parent (referenced) table; FEE is the child (referencing) table.

The parent table must be created first. MySQL then refuses any FEE row whose RollNo does not exist in STUDENT, and also refuses to delete a student who still has fee receipts. This protection is called referential integrity. DECIMAL(8,2) is used for Amount because money must be exact.

MySQL
CREATE TABLE FEE (
    ReceiptNo INT PRIMARY KEY,
    RollNo    INT NOT NULL,
    Amount    DECIMAL(8,2),
    PayDate   DATE,
    FOREIGN KEY (RollNo) REFERENCES STUDENT(RollNo)
);
INSERT INTO FEE VALUES (5001, 2, 4500.00, '2025-04-05');
INSERT INTO FEE VALUES (5002, 15, 4500.00, '2025-04-09');
Output
Query OK, 0 rows affected (0.00 sec)

Query OK, 1 row affected (0.00 sec)

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`school`.`fee`, CONSTRAINT `fee_ibfk_1` FOREIGN KEY (`RollNo`) REFERENCES `student` (`RollNo`))
Teacher tip

Roll number 2 exists in STUDENT, so the first receipt is accepted. Roll number 15 does not, so the second is rejected with error 1452. Use this to explain why a foreign key is useful: no fee receipt can belong to a student who is not on the rolls.

DESCRIBE: viewing the structure of a table

DESCRIBE table_name; or its short form DESC table_name; shows the schema of a table: each column (Field), its data type, whether it accepts NULL, any key (PRI for primary key, UNI for unique, MUL for a foreign-key or indexed column) and its default value. It does not show the rows.

MySQL
DESC STUDENT;
Output
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| RollNo  | int         | NO   | PRI | NULL    |       |
| Name    | varchar(30) | NO   |     | NULL    |       |
| Class   | int         | YES  |     | NULL    |       |
| Section | char(1)     | YES  |     | A       |       |
| Gender  | char(1)     | YES  |     | NULL    |       |
| DOB     | date        | YES  |     | NULL    |       |
| Marks   | int         | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
Teacher tip

MySQL 8 shows int; older MySQL 5.x shows int(11). Both are correct. The Null column says NO for RollNo even though we did not write NOT NULL, because a primary key is automatically NOT NULL.

ALTER TABLE: adding, removing and changing columns

ALTER TABLE changes the structure of an existing table without losing its data. It is a DDL command.

  • Add a column: ALTER TABLE STUDENT ADD Phone CHAR(10); New column appears at the end, with NULL in every existing row (or its DEFAULT value, if one is given).
  • Change data type or size: ALTER TABLE STUDENT MODIFY Name VARCHAR(40) NOT NULL; Repeat any constraint you want to keep, because MODIFY replaces the whole definition.
  • Set a default value: ALTER TABLE STUDENT MODIFY Class INT DEFAULT 11;
  • Remove a column: ALTER TABLE STUDENT DROP Phone; (DROP COLUMN Phone also works). Its data is lost.

Adding a column increases the degree (number of columns) by one; dropping a column reduces it. The cardinality (number of rows) is not changed.

MySQL
ALTER TABLE STUDENT ADD Phone CHAR(10);
ALTER TABLE STUDENT MODIFY Name VARCHAR(40) NOT NULL;
ALTER TABLE STUDENT DROP Phone;
Output
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0
Teacher tip

The NCERT exercise mentions changing a column's name. It is done with ALTER TABLE STUDENT CHANGE Marks Score INT; (old name, new name, type). Mention it, but drill ADD, MODIFY and DROP, which are the most frequently tested.

ALTER TABLE: adding keys and constraints later

Sometimes a table is created without keys. ALTER TABLE can add them afterwards, provided the existing data already obeys the rule (no duplicate or NULL values for a primary key).

  • ALTER TABLE STUDENT ADD PRIMARY KEY (RollNo);
  • ALTER TABLE STUDENT DROP PRIMARY KEY;
  • ALTER TABLE STUDENT ADD UNIQUE (Phone);
  • ALTER TABLE FEE ADD FOREIGN KEY (RollNo) REFERENCES STUDENT(RollNo);
  • ALTER TABLE STUDENT MODIFY Gender CHAR(1) NOT NULL; (adds NOT NULL)

In the example a table SPORTS was created with no primary key. The key is added afterwards, and DESC confirms it.

MySQL
CREATE TABLE SPORTS (
    RollNo INT,
    Game   VARCHAR(20)
);
ALTER TABLE SPORTS ADD PRIMARY KEY (RollNo);
DESC SPORTS;
Output
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| RollNo | int         | NO   | PRI | NULL    |       |
| Game   | varchar(20) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Teacher tip

If two rows already share the same RollNo, ADD PRIMARY KEY fails with a duplicate-entry error. Students must clean the data first, which is a good lesson in why keys are planned at design time.

DROP: removing a table or database

DROP permanently deletes a database object, structure and data together. There is no undo, so it must be used with great care.

  • DROP TABLE SPORTS; removes the table SPORTS.
  • DROP DATABASE SCHOOL; removes the database and every table inside it.
  • DROP TABLE IF EXISTS SPORTS; avoids an error if the table is not there.

A parent table cannot be dropped while a child table still refers to it through a foreign key; drop the child table first.

MySQL
DROP TABLE SPORTS;
SHOW TABLES;
Output
Query OK, 0 rows affected (0.00 sec)

+------------------+
| Tables_in_school |
+------------------+
| STUDENT          |
+------------------+
1 row in set (0.00 sec)

INSERT: adding rows

INSERT INTO adds new rows (records) to a table. It is a DML command.

  1. Values for all columns, in the same order as the table structure: INSERT INTO STUDENT VALUES (1, 'Aarav Sharma', 11, 'A', 'M', '2009-03-14', 78);
  2. Values for selected columns: name the columns first. Columns left out get their DEFAULT value, or NULL if they have no default.
  3. Several rows at once: separate the row lists with commas after a single VALUES keyword.
  4. Missing value: write the keyword NULL (without quotes) in its place.

In the example, roll 9 is added with every column; roll 10 gives only four columns, so Section gets its default 'A' and Gender and DOB become NULL.

MySQL
INSERT INTO STUDENT VALUES (9, 'Ishaan Verma', 12, 'C', 'M', '2008-02-14', 55);
INSERT INTO STUDENT (RollNo, Name, Class, Marks) VALUES (10, 'Pooja Reddy', 11, 49);
SELECT * FROM STUDENT WHERE RollNo >= 9;
Output
Query OK, 1 row affected (0.00 sec)

Query OK, 1 row affected (0.00 sec)

+--------+--------------+-------+---------+--------+------------+-------+
| RollNo | Name         | Class | Section | Gender | DOB        | Marks |
+--------+--------------+-------+---------+--------+------------+-------+
|      9 | Ishaan Verma |    12 | C       | M      | 2008-02-14 |    55 |
|     10 | Pooja Reddy  |    11 | A       | NULL   | NULL       |    49 |
+--------+--------------+-------+---------+--------+------------+-------+
2 rows in set (0.00 sec)
Teacher tip

'NULL' in quotes is the four-letter text NULL, not a missing value. Also, the number of values must match the number of columns, otherwise MySQL gives "Column count doesn't match value count".

Constraints in action: rejected INSERTs

When an INSERT breaks a constraint, MySQL rejects the whole row and shows an error. Running these in the lab makes constraints concrete.

  • RollNo 3 already exists, so a second row with RollNo 3 breaks the PRIMARY KEY (duplicate entry).
  • Name is NOT NULL, so a NULL name is refused.

The table still has its original 8 rows after both errors.

MySQL
INSERT INTO STUDENT VALUES (3, 'Tara Joshi', 11, 'B', 'F', '2009-02-11', 66);
INSERT INTO STUDENT VALUES (11, NULL, 11, 'B', 'M', '2009-08-19', 59);
SELECT COUNT(*) FROM STUDENT;
Output
ERROR 1062 (23000): Duplicate entry '3' for key 'student.PRIMARY'

ERROR 1048 (23000): Column 'Name' cannot be null

+----------+
| COUNT(*) |
+----------+
|        8 |
+----------+
1 row in set (0.00 sec)
Teacher tip

COUNT(*) is used here only to show the row count; aggregate functions are taught in Class 12.

The sample STUDENT table

All query examples from here on use the 8 rows below. Note the two NULLs: Ananya (RollNo 4) has no marks entered yet and Vihaan (RollNo 7) has no DOB recorded. SELECT * FROM STUDENT; displays every column (* means all columns) of every row.

MySQL
SELECT * FROM STUDENT;
Output
+--------+--------------+-------+---------+--------+------------+-------+
| RollNo | Name         | Class | Section | Gender | DOB        | Marks |
+--------+--------------+-------+---------+--------+------------+-------+
|      1 | Aarav Sharma |    11 | A       | M      | 2009-03-14 |    78 |
|      2 | Diya Menon   |    12 | B       | F      | 2008-07-22 |    91 |
|      3 | Kabir Singh  |    11 | A       | M      | 2008-11-05 |    45 |
|      4 | Ananya Iyer  |    12 | C       | F      | 2008-01-30 |  NULL |
|      5 | Rohan Das    |    12 | B       | M      | 2009-09-18 |    62 |
|      6 | Sneha Patil  |    12 | A       | F      | 2007-12-25 |    84 |
|      7 | Vihaan Gupta |    11 | C       | M      | NULL       |    38 |
|      8 | Meera Nair   |    11 | B       | F      | 2008-05-10 |    70 |
+--------+--------------+-------+---------+--------+------------+-------+
8 rows in set (0.00 sec)
Teacher tip

Project this table and keep it visible throughout the SELECT lessons. Ask students to predict each result on paper before running the query.

SELECT: chosen columns, expressions and column aliases

Syntax: SELECT column_list FROM table_name;

  • List the columns you want, separated by commas, in the order you want them shown.
  • A column can be used in an arithmetic expression (+ - * /). The result is calculated for display only; the table is not changed.
  • Any arithmetic with NULL gives NULL (see Ananya below).
  • A column alias gives a heading to a column or expression: expression AS alias. The word AS is optional. Put the alias in quotes if it contains a space.
MySQL
SELECT Name, Marks, Marks + 5 AS "After Grace"
FROM STUDENT
WHERE Class = 12;
Output
+-------------+-------+-------------+
| Name        | Marks | After Grace |
+-------------+-------+-------------+
| Diya Menon  |    91 |          96 |
| Ananya Iyer |  NULL |        NULL |
| Rohan Das   |    62 |          67 |
| Sneha Patil |    84 |          89 |
+-------------+-------+-------------+
4 rows in set (0.00 sec)
Teacher tip

An alias cannot be used in the WHERE clause of the same query in MySQL (WHERE "After Grace" > 80 fails); repeat the expression instead. Aliases can be used in ORDER BY.

DISTINCT: removing repeated values

SELECT DISTINCT column FROM table; shows each different value only once. It is useful to answer questions like "Which sections exist?" When DISTINCT is used with more than one column, the combination must be unique.

Without DISTINCT, SELECT Section FROM STUDENT; would return 8 rows with repeats.

MySQL
SELECT DISTINCT Section FROM STUDENT;
SELECT DISTINCT Class, Gender FROM STUDENT;
Output
+---------+
| Section |
+---------+
| A       |
| B       |
| C       |
+---------+
3 rows in set (0.00 sec)

+-------+--------+
| Class | Gender |
+-------+--------+
|    11 | M      |
|    12 | F      |
|    12 | M      |
|    11 | F      |
+-------+--------+
4 rows in set (0.00 sec)
Teacher tip

DISTINCT treats all NULLs as one value. DISTINCT applies to the whole row of selected columns, not just the first column, so SELECT DISTINCT Class, Gender gives the 4 different class-gender combinations here, not 2 values.

WHERE with relational operators

The WHERE clause filters rows: only rows for which the condition is true are shown.

Syntax: SELECT column_list FROM table_name WHERE condition;

Relational (comparison) operators: = equal, <> or != not equal, >, <, >=, <=. They work on numbers, text (alphabetical order) and dates (earlier date is smaller).

MySQL
SELECT RollNo, Name, Marks FROM STUDENT WHERE Marks >= 70;
SELECT Name, DOB FROM STUDENT WHERE DOB < '2008-06-01';
SELECT Name, Section FROM STUDENT WHERE Section <> 'B';
Output
+--------+--------------+-------+
| RollNo | Name         | Marks |
+--------+--------------+-------+
|      1 | Aarav Sharma |    78 |
|      2 | Diya Menon   |    91 |
|      6 | Sneha Patil  |    84 |
|      8 | Meera Nair   |    70 |
+--------+--------------+-------+
4 rows in set (0.00 sec)

+-------------+------------+
| Name        | DOB        |
+-------------+------------+
| Ananya Iyer | 2008-01-30 |
| Sneha Patil | 2007-12-25 |
| Meera Nair  | 2008-05-10 |
+-------------+------------+
3 rows in set (0.00 sec)

+--------------+---------+
| Name         | Section |
+--------------+---------+
| Aarav Sharma | A       |
| Kabir Singh  | A       |
| Ananya Iyer  | C       |
| Sneha Patil  | A       |
| Vihaan Gupta | C       |
+--------------+---------+
5 rows in set (0.00 sec)
Teacher tip

Rows with NULL never satisfy a comparison. Ananya (Marks NULL) is missing from the first result, and Vihaan (DOB NULL) from the second, even though their values are "unknown" rather than wrong.

Logical operators: AND, OR, NOT

Conditions can be combined:

  • AND: row is selected only if both conditions are true.
  • OR: row is selected if at least one condition is true.
  • NOT: reverses a condition.

Order of evaluation is NOT, then AND, then OR. Use brackets to make the meaning clear. In the last query below, brackets make sure the class check applies to both sections.

MySQL
SELECT Name, Class, Gender FROM STUDENT WHERE Class = 11 AND Gender = 'M';
SELECT Name, Marks FROM STUDENT WHERE Marks > 85 OR Marks < 40;
SELECT Name, Class, Section FROM STUDENT WHERE Class = 12 AND (Section = 'A' OR Section = 'C');
Output
+--------------+-------+--------+
| Name         | Class | Gender |
+--------------+-------+--------+
| Aarav Sharma |    11 | M      |
| Kabir Singh  |    11 | M      |
| Vihaan Gupta |    11 | M      |
+--------------+-------+--------+
3 rows in set (0.00 sec)

+--------------+-------+
| Name         | Marks |
+--------------+-------+
| Diya Menon   |    91 |
| Vihaan Gupta |    38 |
+--------------+-------+
2 rows in set (0.00 sec)

+-------------+-------+---------+
| Name        | Class | Section |
+-------------+-------+---------+
| Ananya Iyer |    12 | C       |
| Sneha Patil |    12 | A       |
+-------------+-------+---------+
2 rows in set (0.00 sec)
Teacher tip

Without the brackets, Class = 12 AND Section = 'A' OR Section = 'C' would also pick Vihaan (Class 11, Section C), because AND is done first. Ask students to run both versions and compare.

BETWEEN and IN

  • BETWEEN low AND high selects values in a range, including both end values. Marks BETWEEN 45 AND 70 means Marks >= 45 AND Marks <= 70. It works for numbers, dates and text.
  • IN (list) selects values that match any value in the list. Section IN ('A', 'C') means Section = 'A' OR Section = 'C'.
  • NOT BETWEEN and NOT IN give the opposite.
MySQL
SELECT Name, Marks FROM STUDENT WHERE Marks BETWEEN 45 AND 70;
SELECT Name, DOB FROM STUDENT WHERE DOB BETWEEN '2008-01-01' AND '2008-12-31';
SELECT RollNo, Name, Section FROM STUDENT WHERE Section IN ('A', 'C');
Output
+-------------+-------+
| Name        | Marks |
+-------------+-------+
| Kabir Singh |    45 |
| Rohan Das   |    62 |
| Meera Nair  |    70 |
+-------------+-------+
3 rows in set (0.00 sec)

+-------------+------------+
| Name        | DOB        |
+-------------+------------+
| Diya Menon  | 2008-07-22 |
| Kabir Singh | 2008-11-05 |
| Ananya Iyer | 2008-01-30 |
| Meera Nair  | 2008-05-10 |
+-------------+------------+
4 rows in set (0.00 sec)

+--------+--------------+---------+
| RollNo | Name         | Section |
+--------+--------------+---------+
|      1 | Aarav Sharma | A       |
|      3 | Kabir Singh  | A       |
|      4 | Ananya Iyer  | C       |
|      6 | Sneha Patil  | A       |
|      7 | Vihaan Gupta | C       |
+--------+--------------+---------+
5 rows in set (0.00 sec)
Teacher tip

Write the smaller value first. BETWEEN 70 AND 45 returns an empty set, a common trap in output questions.

LIKE: pattern matching with % and _

LIKE compares text with a pattern that uses two wildcard characters:

  • % (percent) stands for zero or more characters.
  • _ (underscore) stands for exactly one character.

In MySQL, LIKE is not case-sensitive for normal text columns, so 'a%' also matches 'Aarav'.

PatternMatchesFrom STUDENT
'A%'starts with AAarav Sharma, Ananya Iyer
'%a'ends with aAarav Sharma, Vihaan Gupta
'%an%'contains 'an' anywhereAnanya Iyer, Rohan Das, Vihaan Gupta
'_i%'i is the second letterDiya Menon, Vihaan Gupta
'_____ %'first word has exactly 5 lettersAarav Sharma, Kabir Singh, Rohan Das, Sneha Patil, Meera Nair
MySQL
SELECT Name FROM STUDENT WHERE Name LIKE '%an%';
SELECT Name FROM STUDENT WHERE Name LIKE '_i%';
SELECT Name FROM STUDENT WHERE Name NOT LIKE '%e%';
Output
+--------------+
| Name         |
+--------------+
| Ananya Iyer  |
| Rohan Das    |
| Vihaan Gupta |
+--------------+
3 rows in set (0.00 sec)

+--------------+
| Name         |
+--------------+
| Diya Menon   |
| Vihaan Gupta |
+--------------+
2 rows in set (0.00 sec)

+--------------+
| Name         |
+--------------+
| Aarav Sharma |
| Kabir Singh  |
| Rohan Das    |
| Vihaan Gupta |
+--------------+
4 rows in set (0.00 sec)
Teacher tip

Use LIKE only with wildcards. Name = 'A%' searches for the actual text A% and finds nothing.

Handling NULL: IS NULL and IS NOT NULL

NULL means a value is missing or unknown. It is not zero and not a blank space. Because the value is unknown, Marks = NULL is never true, not even for a NULL. MySQL gives special operators:

  • column IS NULL finds rows where the value is missing.
  • column IS NOT NULL finds rows where a value is present.

The query with = NULL below runs without an error but returns an empty set, which is why the mistake is easy to miss.

MySQL
SELECT RollNo, Name FROM STUDENT WHERE Marks = NULL;
SELECT RollNo, Name FROM STUDENT WHERE Marks IS NULL;
SELECT Name, DOB FROM STUDENT WHERE DOB IS NOT NULL AND Gender = 'M';
Output
Empty set (0.00 sec)

+--------+-------------+
| RollNo | Name        |
+--------+-------------+
|      4 | Ananya Iyer |
+--------+-------------+
1 row in set (0.00 sec)

+--------------+------------+
| Name         | DOB        |
+--------------+------------+
| Aarav Sharma | 2009-03-14 |
| Kabir Singh  | 2008-11-05 |
| Rohan Das    | 2009-09-18 |
+--------------+------------+
3 rows in set (0.00 sec)
Teacher tip

Remember the three NULL rules: (1) test with IS NULL, never = NULL; (2) arithmetic with NULL gives NULL; (3) a NULL row fails every comparison, including <>.

ORDER BY: sorting the result

ORDER BY sorts the rows of the result. ASC (ascending) is the default; DESC gives descending order. You can sort on several columns: rows are sorted by the first column, and ties are broken by the second.

ORDER BY is always the last clause: SELECT ... FROM ... WHERE ... ORDER BY ...;. It only changes the display; the table itself is not rearranged.

In MySQL, NULL values come first in ascending order and last in descending order.

MySQL
SELECT Name, Marks FROM STUDENT ORDER BY Marks DESC;
SELECT Class, Section, Name FROM STUDENT WHERE Gender = 'F' ORDER BY Class, Name;
Output
+--------------+-------+
| Name         | Marks |
+--------------+-------+
| Diya Menon   |    91 |
| Sneha Patil  |    84 |
| Aarav Sharma |    78 |
| Meera Nair   |    70 |
| Rohan Das    |    62 |
| Kabir Singh  |    45 |
| Vihaan Gupta |    38 |
| Ananya Iyer  |  NULL |
+--------------+-------+
8 rows in set (0.00 sec)

+-------+---------+-------------+
| Class | Section | Name        |
+-------+---------+-------------+
|    11 | B       | Meera Nair  |
|    12 | C       | Ananya Iyer |
|    12 | B       | Diya Menon  |
|    12 | A       | Sneha Patil |
+-------+---------+-------------+
4 rows in set (0.00 sec)
Teacher tip

Point out where Ananya's NULL appears (last in DESC). Asking "Where would she appear with ORDER BY Marks?" (first) is a good oral check.

UPDATE: changing existing data

UPDATE changes values in rows that already exist. It is a DML command.

Syntax: UPDATE table_name SET column1 = value1 [, column2 = value2] WHERE condition;

  • The WHERE clause decides which rows change. Without WHERE, every row is updated.
  • The new value can be an expression using the old value, e.g. Marks = Marks + 5.
  • A NULL can be filled in, or a value can be set to NULL with SET column = NULL.

Below, Ananya's marks are entered, and then 5 grace marks are given to Class 11 students who scored below 50.

MySQL
UPDATE STUDENT SET Marks = 88 WHERE RollNo = 4;
UPDATE STUDENT SET Marks = Marks + 5 WHERE Class = 11 AND Marks < 50;
SELECT RollNo, Name, Marks FROM STUDENT WHERE RollNo IN (3, 4, 7);
Output
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

+--------+--------------+-------+
| RollNo | Name         | Marks |
+--------+--------------+-------+
|      3 | Kabir Singh  |    50 |
|      4 | Ananya Iyer  |    88 |
|      7 | Vihaan Gupta |    43 |
+--------+--------------+-------+
3 rows in set (0.00 sec)
Teacher tip

Good lab habit: run a SELECT with the same WHERE clause first, check the rows, then change SELECT to UPDATE. "Rows matched" in MySQL's reply tells how many rows were affected.

DELETE: removing rows

DELETE removes rows from a table. It is a DML command.

Syntax: DELETE FROM table_name WHERE condition;

  • Only rows matching the condition are removed; the structure stays.
  • Without WHERE, all rows are deleted and the table becomes empty (but still exists).
  • A parent row cannot be deleted while a child table refers to it through a foreign key.

Below, the student who left the school (RollNo 7) is removed.

MySQL
DELETE FROM STUDENT WHERE RollNo = 7;
SELECT RollNo, Name FROM STUDENT WHERE Class = 11;
Output
Query OK, 1 row affected (0.00 sec)

+--------+--------------+
| RollNo | Name         |
+--------+--------------+
|      1 | Aarav Sharma |
|      3 | Kabir Singh  |
|      8 | Meera Nair   |
+--------+--------------+
3 rows in set (0.00 sec)

DELETE versus DROP (and ALTER ... DROP)

These three are often confused in exams. The difference is in what disappears.

PointDELETE FROM STUDENT;DROP TABLE STUDENT;ALTER TABLE STUDENT DROP Marks;
CategoryDMLDDLDDL
RemovesRows (all, or those matching WHERE)The whole table: structure and all dataOne column and its data
Table still exists?Yes (empty if no WHERE)NoYes
WHERE allowed?YesNoNo
EffectCardinality fallsTable is goneDegree falls by 1
MySQL
DELETE FROM STUDENT;
SELECT * FROM STUDENT;
DROP TABLE STUDENT;
SELECT * FROM STUDENT;
Output
Query OK, 8 rows affected (0.00 sec)

Empty set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

ERROR 1146 (42S02): Table 'school.student' doesn't exist
Teacher tip

After DELETE, SELECT gives "Empty set" (the table exists but has no rows). After DROP, SELECT gives an error because the table no longer exists. This contrast makes the difference memorable.

Writing a complete query: clause order

A SELECT statement for Class 11 has this fixed order. Only SELECT and FROM are compulsory.

SELECT [DISTINCT] columns / expressions [AS alias]
FROM table
WHERE condition
ORDER BY column [ASC | DESC];

Exam method for "Write SQL queries" questions: (1) underline the columns asked to display; (2) circle the condition words (more than, between, starting with, not entered); (3) look for words like "in descending order"; (4) write the query in the order above and end with a semicolon.

MySQL
SELECT RollNo, Name, Marks
FROM STUDENT
WHERE Gender = 'F' AND Marks IS NOT NULL
ORDER BY Marks DESC;
Output
+--------+-------------+-------+
| RollNo | Name        | Marks |
+--------+-------------+-------+
|      2 | Diya Menon  |    91 |
|      6 | Sneha Patil |    84 |
|      8 | Meera Nair  |    70 |
+--------+-------------+-------+
3 rows in set (0.00 sec)

Key terms

SQL
Structured Query Language; the standard language used to create, change and query relational databases.
MySQL
A free, open-source relational database management system that uses SQL.
DDL
Data Definition Language; commands that define or change structure, e.g. CREATE, ALTER, DROP.
DML
Data Manipulation Language; commands that change the data in tables: INSERT, UPDATE, DELETE.
DQL
Data Query Language; the SELECT command, used to read data without changing it.
Data type
Property of a column that decides the kind of values it can store, e.g. INT, VARCHAR, DATE.
CHAR(n)
Fixed-length text type; always uses n characters of space.
VARCHAR(n)
Variable-length text type; stores only the characters actually entered, up to n.
DECIMAL(p,s)
Exact number type with p total digits and s digits after the decimal point.
Constraint
A rule on a column or table that the RDBMS checks before accepting data.
Primary key
Column(s) that uniquely identify each row; cannot be NULL or repeated.
Foreign key
Column in a child table whose values must match the primary key of a parent table (or be NULL).
Referential integrity
The guarantee, enforced by foreign keys, that every reference points to a row that really exists.
NULL
A marker for a missing or unknown value; different from 0 or an empty string.
Schema
The structure of a table or database: its columns, data types and constraints.
Degree
Number of columns (attributes) in a table.
Cardinality
Number of rows (tuples) in a table.
Column alias
A temporary heading given to a column or expression in a query result using AS.
Wildcard
A special character used with LIKE: % for any number of characters, _ for exactly one.
Clause
A part of an SQL statement that starts with a keyword, such as WHERE or ORDER BY.

MCQs

Tap an option to check it, or use Show answers above to reveal them all.

  1. SQL is called a non-procedural language because:

    Answer

    (b) the user states what data is needed, not the steps to get it

    In SQL we describe the required result; the RDBMS decides how to fetch it.

  2. Which of the following is a DDL command?

    Answer

    (c) ALTER

    ALTER changes the structure of a table, so it is DDL. INSERT and UPDATE are DML; SELECT is DQL.

  3. According to the CBSE syllabus, the SELECT command belongs to:

    Answer

    (a) DQL

    SELECT only reads data, so it is classified as Data Query Language.

  4. Which data type is most suitable for storing a 6-digit PIN code such as 110001?

    Answer

    (d) CHAR(6)

    A PIN code always has 6 characters and is never used in arithmetic, so fixed-length CHAR(6) fits best.

  5. A column is declared as VARCHAR(20). How many characters of space are used to store the value 'Ravi'?

    Answer

    (b) 4 (plus a small length prefix)

    VARCHAR is variable length, so only the 4 characters entered are stored, along with a length byte.

  6. In MySQL, a DATE value is written in the format:

    Answer

    (c) 'YYYY-MM-DD'

    MySQL stores and accepts dates as 'YYYY-MM-DD', for example '2008-07-22'.

  7. Which constraint ensures that no two rows have the same value in a column but still allows NULL?

    Answer

    (d) UNIQUE

    UNIQUE stops duplicates but accepts NULL. PRIMARY KEY stops both duplicates and NULL.

  8. Which statement about a PRIMARY KEY is correct?

    Answer

    (a) Its values must be unique and cannot be NULL

    A primary key behaves like UNIQUE + NOT NULL, and a table has only one primary key.

  9. In table FEE, RollNo is a foreign key referring to STUDENT(RollNo). Which RollNo can be inserted in FEE?

    Answer

    (b) Only a RollNo that exists in STUDENT (or NULL, if the column allows it)

    A foreign key value must match an existing primary key value in the parent table, or be NULL.

  10. Which command shows the column names, data types and keys of the table STUDENT?

    Answer

    (c) DESCRIBE STUDENT;

    DESCRIBE (or DESC) displays the structure of a table.

  11. Which command makes SCHOOL the current database?

    Answer

    (b) USE SCHOOL;

    USE database_name; selects the database for later statements.

  12. Which statement adds a column Phone to the table STUDENT?

    Answer

    (d) ALTER TABLE STUDENT ADD Phone CHAR(10);

    A structure change needs ALTER TABLE, followed by ADD, the column name and its data type.

  13. Which command removes both the structure and the data of a table permanently?

    Answer

    (a) DROP TABLE

    DROP TABLE removes the whole table. DELETE removes rows only; ALTER ... DROP removes one column.

  14. Using the sample STUDENT table, how many rows does SELECT DISTINCT Section FROM STUDENT; return?

    Answer

    (c) 3

    The sections present are A, B and C; DISTINCT shows each once.

  15. Using the sample STUDENT table, how many rows are returned by SELECT Name FROM STUDENT WHERE Marks BETWEEN 45 AND 70;?

    Answer

    (b) 3

    Kabir (45), Rohan (62) and Meera (70). BETWEEN includes both end values.

  16. Which names from the sample table match Name LIKE '_i%'?

    Answer

    (a) Diya Menon and Vihaan Gupta

    The pattern needs 'i' as the second character: D-i-ya and V-i-haan.

  17. Which condition correctly finds students whose marks have not been entered?

    Answer

    (d) WHERE Marks IS NULL

    NULL can only be tested with IS NULL or IS NOT NULL.

  18. If no ASC or DESC is written after ORDER BY, the rows are sorted in:

    Answer

    (b) ascending order

    ASC is the default sort order.

  19. Which condition is equivalent to Section = 'A' OR Section = 'C'?

    Answer

    (c) Section IN ('A', 'C')

    IN matches any value in the list. BETWEEN 'A' AND 'C' would also include 'B'.

  20. What is displayed for Ananya by SELECT Marks + 10 FROM STUDENT WHERE RollNo = 4; (her Marks is NULL)?

    Answer

    (a) NULL

    Any arithmetic with NULL gives NULL.

  21. What happens when UPDATE STUDENT SET Marks = 50; is executed?

    Answer

    (c) Marks of every row becomes 50

    Without a WHERE clause, UPDATE changes all rows.

  22. After DELETE FROM STUDENT;, which statement is true?

    Answer

    (d) The table exists but has no rows

    DELETE without WHERE removes all rows but keeps the structure.

  23. In WHERE Class = 12 AND Section = 'A' OR Section = 'C', which operator is evaluated first?

    Answer

    (b) AND

    The precedence is NOT, then AND, then OR. Use brackets to change it.

  24. Which keyword is used to give a temporary heading to a column in the output?

    Answer

    (a) AS

    Example: SELECT Marks + 5 AS NewMarks FROM STUDENT;

  25. A table has degree 7 and cardinality 8. After ALTER TABLE STUDENT ADD Phone CHAR(10); and one INSERT, the degree and cardinality are:

    Answer

    (c) 8 and 9

    ADD increases the number of columns to 8; one INSERT increases the number of rows to 9.

Assertion–Reason

Choose: (A) Both A and R are true and R is the correct explanation of A. (B) Both A and R are true but R is not the correct explanation of A. (C) A is true but R is false. (D) A is false but R is true.
  1. Assertion (A): CHAR is a better choice than VARCHAR for a Gender column that stores 'M' or 'F'.

    Reason (R): CHAR is a fixed-length type, which suits values that always have the same length.

    Answer

    (A)

    Every gender value has length 1, so fixed-length CHAR(1) wastes no space and R correctly explains A.

  2. Assertion (A): The query SELECT * FROM STUDENT WHERE Marks = NULL; returns no rows even though some marks are NULL.

    Reason (R): NULL represents an unknown value, so a comparison with = is never true; IS NULL must be used.

    Answer

    (A)

    Both are true, and R explains why the = comparison fails.

  3. Assertion (A): A table can have two primary keys.

    Reason (R): A primary key may consist of more than one column.

    Answer

    (D)

    A table has only one primary key, so A is false. R is true: a composite primary key has several columns.

  4. Assertion (A): DELETE FROM STUDENT; removes the table STUDENT from the database.

    Reason (R): DELETE is a DML command that removes rows from a table.

    Answer

    (D)

    DELETE keeps the table structure, so A is false. R is a correct statement.

  5. Assertion (A): SQL is a non-procedural language.

    Reason (R): SQL keywords are not case-sensitive.

    Answer

    (B)

    Both statements are true, but case-insensitivity has nothing to do with being non-procedural.

  6. Assertion (A): The condition Marks BETWEEN 50 AND 60 selects a student who scored exactly 60.

    Reason (R): BETWEEN includes both the lower and the upper boundary values.

    Answer

    (A)

    Because both ends are included, 60 is selected; R explains A.

  7. Assertion (A): A column with the UNIQUE constraint can contain NULL in more than one row in MySQL.

    Reason (R): A PRIMARY KEY column can contain NULL values.

    Answer

    (C)

    UNIQUE allows multiple NULLs in MySQL, so A is true. A primary key never allows NULL, so R is false.

Short answer

  1. 2 marks

    Write any four advantages of using SQL.

    Answer
    1. Easy to learn: uses simple English keywords.
    2. Non-procedural: we state what is needed, not how to get it.
    3. Portable/standard: the same statements work in most RDBMS such as MySQL and Oracle.
    4. One language for all tasks: defining tables, changing data and querying are all done in SQL; large data is retrieved quickly.
  2. 2 marks

    Differentiate between DDL and DML. Give two commands of each.

    Answer

    DDL (Data Definition Language) defines or changes the structure of database objects, e.g. CREATE TABLE, ALTER TABLE, DROP.

    DML (Data Manipulation Language) works on the data stored in tables, e.g. INSERT, UPDATE, DELETE.

  3. 2 marks

    Differentiate between CHAR and VARCHAR data types with an example.

    Answer

    CHAR(n) is fixed length: it always uses n characters, padding with spaces. VARCHAR(n) is variable length: it uses only as many characters as entered (plus a length byte).

    Example: storing 'Ravi' in CHAR(10) uses 10 characters; in VARCHAR(10) it uses 4. CHAR suits fixed-size data like Gender CHAR(1); VARCHAR suits names.

  4. 2 marks

    Differentiate between a primary key and a foreign key with an example.

    Answer

    A primary key uniquely identifies each row of its own table; it cannot be NULL or repeated, e.g. RollNo in STUDENT.

    A foreign key is a column in another table that refers to that primary key, linking the two tables; it may repeat, e.g. RollNo in FEE refers to STUDENT(RollNo), so one student can have many fee receipts.

  5. 2 marks

    How is the UNIQUE constraint different from the PRIMARY KEY constraint?

    Answer
    • UNIQUE allows NULL values; PRIMARY KEY does not.
    • A table can have many UNIQUE columns but only one PRIMARY KEY.

    Both prevent duplicate values. Example: Email UNIQUE, RollNo PRIMARY KEY.

  6. 2 marks

    Differentiate between DELETE and DROP commands.

    Answer
    • DELETE is DML; DROP is DDL.
    • DELETE removes rows (all, or those matching a WHERE condition) and keeps the table structure; DROP removes the entire table (structure and data).

    Example: DELETE FROM STUDENT WHERE RollNo = 7; versus DROP TABLE STUDENT;

  7. 2 marks

    Differentiate between ALTER and UPDATE commands with one example each.

    Answer

    ALTER (DDL) changes the structure of a table, e.g. ALTER TABLE STUDENT ADD Phone CHAR(10);

    UPDATE (DML) changes values in existing rows, e.g. UPDATE STUDENT SET Marks = 80 WHERE RollNo = 3;

  8. 2 marks

    What is NULL? Why can we not use = to search for NULL values?

    Answer

    NULL means a value is missing or unknown; it is not 0 or a blank. Since the value is unknown, comparing it with anything using = (even with NULL) is never true, so no rows are returned. We must use IS NULL or IS NOT NULL, e.g. SELECT * FROM STUDENT WHERE Marks IS NULL;

  9. 2 marks

    Explain the wildcard characters used with LIKE, with one example each.

    Answer
    • % matches zero or more characters: Name LIKE 'S%' finds names starting with S.
    • _ matches exactly one character: Name LIKE '____' finds names of exactly 4 characters; Name LIKE '_e%' finds names whose second letter is e.
  10. 2 marks

    Write SQL statements to (i) create a database LIBRARY, (ii) open it, and (iii) list the tables in it.

    Answer
    MySQL
    CREATE DATABASE LIBRARY;
    USE LIBRARY;
    SHOW TABLES;
  11. 2 marks

    Rewrite the following query after removing all errors. Underline each correction.

    SELECT Name Marks FROM STUDENT WHERE Marks = NULL ORDER Name DESC

    Answer

    Corrections: comma between Name and Marks; IS NULL instead of = NULL; ORDER BY instead of ORDER; semicolon at the end.

    MySQL
    SELECT Name, Marks FROM STUDENT WHERE Marks IS NULL ORDER BY Name DESC;
  12. 2 marks

    The table STUDENT has 7 columns and 8 rows. What will be its degree and cardinality after: (a) ALTER TABLE STUDENT ADD Phone CHAR(10); (b) two new rows are inserted (c) DELETE FROM STUDENT WHERE RollNo = 7;

    Answer

    Degree = 7 + 1 = 8 (only ALTER changes columns).

    Cardinality = 8 + 2 − 1 = 9 (INSERT and DELETE change rows).

  13. 2 marks

    Rewrite the following conditions using IN and BETWEEN respectively:

    (i) Section = 'A' OR Section = 'B'
    (ii) Marks >= 40 AND Marks <= 60

    Answer

    (i) Section IN ('A', 'B')

    (ii) Marks BETWEEN 40 AND 60

  14. 2 marks

    What is the use of the DISTINCT keyword? Write a query to display the different classes in STUDENT.

    Answer

    DISTINCT removes duplicate values from the result so each value is shown only once.

    MySQL
    SELECT DISTINCT Class FROM STUDENT;
    Output
    +-------+
    | Class |
    +-------+
    |    11 |
    |    12 |
    +-------+
    2 rows in set (0.00 sec)
  15. 2 marks

    What is the DEFAULT constraint? Write a column definition so that City gets 'Jaipur' when no value is given.

    Answer

    DEFAULT supplies a value automatically for a column when an INSERT does not give one.

    City VARCHAR(20) DEFAULT 'Jaipur'

Long answer

  1. 5 marks

    Consider the table STUDENT given in the notes (RollNo, Name, Class, Section, Gender, DOB, Marks). Write SQL queries for the following:

    (i) Display the names and marks of all girls, highest marks first.
    (ii) Display the details of students of Class 11 whose marks are between 40 and 80.
    (iii) Display the roll number and name of students whose name ends with 'r' or whose section is 'C'.
    (iv) Display the names of students whose date of birth has not been recorded.
    (v) Display the name and marks of each student along with marks increased by 10%, using the heading "Revised", for students who have marks.

    Answer

    Queries with results on the sample data:

    MySQL
    -- (i)
    SELECT Name, Marks FROM STUDENT WHERE Gender = 'F' ORDER BY Marks DESC;
    -- (ii)
    SELECT * FROM STUDENT WHERE Class = 11 AND Marks BETWEEN 40 AND 80;
    -- (iii)
    SELECT RollNo, Name FROM STUDENT WHERE Name LIKE '%r' OR Section = 'C';
    -- (iv)
    SELECT Name FROM STUDENT WHERE DOB IS NULL;
    -- (v)
    SELECT Name, Marks, Marks * 1.1 AS Revised FROM STUDENT WHERE Marks IS NOT NULL;
    Output
    +-------------+-------+
    | Name        | Marks |
    +-------------+-------+
    | Diya Menon  |    91 |
    | Sneha Patil |    84 |
    | Meera Nair  |    70 |
    | Ananya Iyer |  NULL |
    +-------------+-------+
    4 rows in set (0.00 sec)
    
    +--------+--------------+-------+---------+--------+------------+-------+
    | RollNo | Name         | Class | Section | Gender | DOB        | Marks |
    +--------+--------------+-------+---------+--------+------------+-------+
    |      1 | Aarav Sharma |    11 | A       | M      | 2009-03-14 |    78 |
    |      3 | Kabir Singh  |    11 | A       | M      | 2008-11-05 |    45 |
    |      8 | Meera Nair   |    11 | B       | F      | 2008-05-10 |    70 |
    +--------+--------------+-------+---------+--------+------------+-------+
    3 rows in set (0.00 sec)
    
    +--------+--------------+
    | RollNo | Name         |
    +--------+--------------+
    |      4 | Ananya Iyer  |
    |      7 | Vihaan Gupta |
    |      8 | Meera Nair   |
    +--------+--------------+
    3 rows in set (0.00 sec)
    
    +--------------+
    | Name         |
    +--------------+
    | Vihaan Gupta |
    +--------------+
    1 row in set (0.00 sec)
    
    +--------------+-------+---------+
    | Name         | Marks | Revised |
    +--------------+-------+---------+
    | Aarav Sharma |    78 |    85.8 |
    | Diya Menon   |    91 |   100.1 |
    | Kabir Singh  |    45 |    49.5 |
    | Rohan Das    |    62 |    68.2 |
    | Sneha Patil  |    84 |    92.4 |
    | Vihaan Gupta |    38 |    41.8 |
    | Meera Nair   |    70 |    77.0 |
    +--------------+-------+---------+
    7 rows in set (0.00 sec)
  2. 5 marks

    A stationery shop stores its stock in the table ITEM:

    Columns: ICode, IName, Category, Price, Qty, LastSold

    • I101 | Gel Pen | Pen | 15.00 | 120 | 2025-07-12
    • I102 | Fountain Pen | Pen | 180.00 | 25 | 2025-06-30
    • I103 | Notebook A4 | Paper | 60.00 | 200 | 2025-07-15
    • I104 | Geometry Box | Kit | 245.50 | 18 | NULL
    • I105 | Drawing Sheet | Paper | 8.00 | 500 | 2025-07-10
    • I106 | Pencil Box | Kit | 99.00 | NULL | 2025-05-21
    • I107 | Marker Pen | Pen | 35.00 | 60 | 2025-07-01

    Write SQL queries to:

    (i) Display the name and price of items in the categories 'Pen' and 'Kit'.
    (ii) Display the name and stock value (Price × Qty) of each item with the heading StockValue.
    (iii) Display the details of items sold between 1 July 2025 and 12 July 2025.
    (iv) Display the names of items whose name contains the word 'Pen', in alphabetical order.
    (v) Increase the price of all 'Paper' items by 2.

    Answer

    Note two traps in the results: Pencil Box shows NULL in (ii) because its Qty is NULL, and Pencil Box also appears in (iv) because 'Pen' occurs inside 'Pencil'.

    MySQL
    -- (i)
    SELECT IName, Price FROM ITEM WHERE Category IN ('Pen', 'Kit');
    -- (ii)
    SELECT IName, Price * Qty AS StockValue FROM ITEM;
    -- (iii)
    SELECT * FROM ITEM WHERE LastSold BETWEEN '2025-07-01' AND '2025-07-12';
    -- (iv)
    SELECT IName FROM ITEM WHERE IName LIKE '%Pen%' ORDER BY IName;
    -- (v)
    UPDATE ITEM SET Price = Price + 2 WHERE Category = 'Paper';
    Output
    +--------------+--------+
    | IName        | Price  |
    +--------------+--------+
    | Gel Pen      |  15.00 |
    | Fountain Pen | 180.00 |
    | Geometry Box | 245.50 |
    | Pencil Box   |  99.00 |
    | Marker Pen   |  35.00 |
    +--------------+--------+
    5 rows in set (0.00 sec)
    
    +---------------+------------+
    | IName         | StockValue |
    +---------------+------------+
    | Gel Pen       |    1800.00 |
    | Fountain Pen  |    4500.00 |
    | Notebook A4   |   12000.00 |
    | Geometry Box  |    4419.00 |
    | Drawing Sheet |    4000.00 |
    | Pencil Box    |       NULL |
    | Marker Pen    |    2100.00 |
    +---------------+------------+
    7 rows in set (0.00 sec)
    
    +-------+---------------+----------+-------+-----+------------+
    | ICode | IName         | Category | Price | Qty | LastSold   |
    +-------+---------------+----------+-------+-----+------------+
    | I101  | Gel Pen       | Pen      | 15.00 | 120 | 2025-07-12 |
    | I105  | Drawing Sheet | Paper    |  8.00 | 500 | 2025-07-10 |
    | I107  | Marker Pen    | Pen      | 35.00 |  60 | 2025-07-01 |
    +-------+---------------+----------+-------+-----+------------+
    3 rows in set (0.00 sec)
    
    +--------------+
    | IName        |
    +--------------+
    | Fountain Pen |
    | Gel Pen      |
    | Marker Pen   |
    | Pencil Box   |
    +--------------+
    4 rows in set (0.00 sec)
    
    Query OK, 2 rows affected (0.00 sec)
    Rows matched: 2  Changed: 2  Warnings: 0
  3. 3 marks

    Write the output of the following queries based on the sample STUDENT table:

    (i) SELECT Name, Marks FROM STUDENT WHERE Section = 'A' AND Marks > 50;
    (ii) SELECT DISTINCT Gender FROM STUDENT WHERE Class = 11;
    (iii) SELECT Name, DOB FROM STUDENT WHERE Name LIKE '%a' OR DOB < '2008-01-01';

    Answer
    MySQL
    SELECT Name, Marks FROM STUDENT WHERE Section = 'A' AND Marks > 50;
    SELECT DISTINCT Gender FROM STUDENT WHERE Class = 11;
    SELECT Name, DOB FROM STUDENT WHERE Name LIKE '%a' OR DOB < '2008-01-01';
    Output
    +--------------+-------+
    | Name         | Marks |
    +--------------+-------+
    | Aarav Sharma |    78 |
    | Sneha Patil  |    84 |
    +--------------+-------+
    2 rows in set (0.00 sec)
    
    +--------+
    | Gender |
    +--------+
    | M      |
    | F      |
    +--------+
    2 rows in set (0.00 sec)
    
    +--------------+------------+
    | Name         | DOB        |
    +--------------+------------+
    | Aarav Sharma | 2009-03-14 |
    | Sneha Patil  | 2007-12-25 |
    | Vihaan Gupta | NULL       |
    +--------------+------------+
    3 rows in set (0.00 sec)
  4. 3 marks

    Consider the table PLAYER of a cricket league:

    Columns: PID, PName, Team, Role, Runs, Wickets, Debut

    • 1 | Rahul Yadav | Mumbai Stars | Batter | 1450 | 2 | 2019-04-10
    • 2 | Arjun Mehta | Delhi Kings | Bowler | 210 | 58 | 2020-03-22
    • 3 | Farhan Ali | Mumbai Stars | All-rounder | 890 | 31 | 2018-11-02
    • 4 | Karan Bhatia | Chennai Lions | Batter | 1720 | NULL | 2017-09-15
    • 5 | Nikhil Rao | Delhi Kings | Wicketkeeper | 640 | NULL | 2021-01-08
    • 6 | Sameer Khan | Chennai Lions | Bowler | 95 | 72 | 2019-12-01

    Write the output of:

    (i) SELECT PName, Runs FROM PLAYER WHERE Team = 'Delhi Kings' OR Runs > 1500;
    (ii) SELECT PName, Wickets FROM PLAYER WHERE Wickets IS NULL;
    (iii) SELECT PName, Role FROM PLAYER WHERE Debut BETWEEN '2019-01-01' AND '2020-12-31' ORDER BY PName DESC;

    Answer
    MySQL
    SELECT PName, Runs FROM PLAYER WHERE Team = 'Delhi Kings' OR Runs > 1500;
    SELECT PName, Wickets FROM PLAYER WHERE Wickets IS NULL;
    SELECT PName, Role FROM PLAYER WHERE Debut BETWEEN '2019-01-01' AND '2020-12-31' ORDER BY PName DESC;
    Output
    +--------------+------+
    | PName        | Runs |
    +--------------+------+
    | Arjun Mehta  |  210 |
    | Karan Bhatia | 1720 |
    | Nikhil Rao   |  640 |
    +--------------+------+
    3 rows in set (0.00 sec)
    
    +--------------+---------+
    | PName        | Wickets |
    +--------------+---------+
    | Karan Bhatia |    NULL |
    | Nikhil Rao   |    NULL |
    +--------------+---------+
    2 rows in set (0.00 sec)
    
    +-------------+--------+
    | PName       | Role   |
    +-------------+--------+
    | Sameer Khan | Bowler |
    | Rahul Yadav | Batter |
    | Arjun Mehta | Bowler |
    +-------------+--------+
    3 rows in set (0.00 sec)
  5. 5 marks

    Based on the table PLAYER given in the previous question, write SQL statements to:

    (i) Display the name, team and runs of all batters, in descending order of runs.
    (ii) Display the names of players whose name starts with 'S' or 'K'.
    (iii) Set the wickets of all players whose wickets are not recorded to 0.
    (iv) Add a column Fees of type DECIMAL(10,2) to the table.
    (v) Remove the record of the player with PID 6.

    Answer
    MySQL
    -- (i)
    SELECT PName, Team, Runs FROM PLAYER WHERE Role = 'Batter' ORDER BY Runs DESC;
    -- (ii)
    SELECT PName FROM PLAYER WHERE PName LIKE 'S%' OR PName LIKE 'K%';
    -- (iii)
    UPDATE PLAYER SET Wickets = 0 WHERE Wickets IS NULL;
    -- (iv)
    ALTER TABLE PLAYER ADD Fees DECIMAL(10,2);
    -- (v)
    DELETE FROM PLAYER WHERE PID = 6;
    Output
    +--------------+---------------+------+
    | PName        | Team          | Runs |
    +--------------+---------------+------+
    | Karan Bhatia | Chennai Lions | 1720 |
    | Rahul Yadav  | Mumbai Stars  | 1450 |
    +--------------+---------------+------+
    2 rows in set (0.00 sec)
    
    +--------------+
    | PName        |
    +--------------+
    | Karan Bhatia |
    | Sameer Khan  |
    +--------------+
    2 rows in set (0.00 sec)
    
    Query OK, 2 rows affected (0.00 sec)
    Rows matched: 2  Changed: 2  Warnings: 0
    
    Query OK, 0 rows affected (0.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    Query OK, 1 row affected (0.00 sec)
  6. 3 marks

    Write an SQL statement to create a table BOOK with the following structure, then insert one record into it.

    • BookID: integer, primary key
    • Title: variable-length text up to 40 characters, must not be empty
    • Author: variable-length text up to 30 characters
    • Price: exact number with 2 decimal places, up to 9999.99
    • Language: 10 characters, default 'English'
    • PubDate: date of publication
    Answer

    Price uses DECIMAL(6,2) (6 digits in all, 2 after the point). Language is not listed in the INSERT, so it takes its default value.

    MySQL
    CREATE TABLE BOOK (
        BookID   INT PRIMARY KEY,
        Title    VARCHAR(40) NOT NULL,
        Author   VARCHAR(30),
        Price    DECIMAL(6,2),
        Language CHAR(10) DEFAULT 'English',
        PubDate  DATE
    );
    INSERT INTO BOOK (BookID, Title, Author, Price, PubDate)
    VALUES (101, 'Wings of Fire', 'A. P. J. Abdul Kalam', 299.00, '1999-01-01');
    SELECT * FROM BOOK;
    Output
    Query OK, 0 rows affected (0.00 sec)
    
    Query OK, 1 row affected (0.00 sec)
    
    +--------+---------------+----------------------+--------+----------+------------+
    | BookID | Title         | Author               | Price  | Language | PubDate    |
    +--------+---------------+----------------------+--------+----------+------------+
    |    101 | Wings of Fire | A. P. J. Abdul Kalam | 299.00 | English  | 1999-01-01 |
    +--------+---------------+----------------------+--------+----------+------------+
    1 row in set (0.00 sec)
  7. 5 marks

    What are constraints? Explain NOT NULL, UNIQUE, DEFAULT, PRIMARY KEY and FOREIGN KEY with the help of a CREATE TABLE statement for two related tables CLASSTEACHER and STUDENT.

    Answer

    A constraint is a rule applied to a column or table that the RDBMS checks whenever data is inserted or changed; rows that break the rule are rejected, keeping the data valid.

    • NOT NULL: a value must be given (TName).
    • UNIQUE: no two rows may repeat the value, though NULL is allowed (Phone).
    • DEFAULT: value used when none is given (Section defaults to 'A').
    • PRIMARY KEY: unique, non-NULL identifier; one per table (TID, RollNo).
    • FOREIGN KEY: value must exist in the referenced primary key; links STUDENT to CLASSTEACHER (TID). The parent table CLASSTEACHER is created first.
    MySQL
    CREATE TABLE CLASSTEACHER (
        TID    INT PRIMARY KEY,
        TName  VARCHAR(30) NOT NULL,
        Phone  CHAR(10) UNIQUE
    );
    
    CREATE TABLE STUDENT (
        RollNo  INT PRIMARY KEY,
        Name    VARCHAR(30) NOT NULL,
        Section CHAR(1) DEFAULT 'A',
        TID     INT,
        FOREIGN KEY (TID) REFERENCES CLASSTEACHER(TID)
    );
  8. 3 marks

    A table MEMBER was created without a primary key: CREATE TABLE MEMBER (MID INT, MName VARCHAR(20), City VARCHAR(15)); Write SQL statements to:

    (i) make MID the primary key,
    (ii) change the size of MName to 30 characters and make it compulsory,
    (iii) remove the column City.

    Answer
    MySQL
    ALTER TABLE MEMBER ADD PRIMARY KEY (MID);
    ALTER TABLE MEMBER MODIFY MName VARCHAR(30) NOT NULL;
    ALTER TABLE MEMBER DROP City;
    Output
    Query OK, 0 rows affected (0.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    Query OK, 0 rows affected (0.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    Query OK, 0 rows affected (0.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0

Case-based

Case study 1

The librarian of Kendriya Vidyalaya, Jammu wants to computerise the school library in MySQL. Each book has a book number, title, author, subject and price. Each issue of a book to a student is recorded in a second table ISSUE with an issue number, the book number, the student's admission number, the issue date and the return date. The return date is left empty until the book comes back.

  1. 1 mark

    Suggest suitable data types for BookNo, Title, Price and IssueDate.

    Answer

    BookNo INT, Title VARCHAR(50), Price DECIMAL(7,2), IssueDate DATE.

  2. 1 mark

    Which column of ISSUE should be a foreign key, and which table and column will it refer to? Why is it needed?

    Answer

    ISSUE.BookNo should refer to BOOK(BookNo). It ensures a book that does not exist in the library can never be issued (referential integrity).

  3. 2 marks

    Write the CREATE TABLE statement for ISSUE with suitable constraints.

    Answer

    BOOK must be created before ISSUE. ReturnDate has no NOT NULL because it stays empty until the book is returned.

    MySQL
    CREATE TABLE ISSUE (
        IssueNo    INT PRIMARY KEY,
        BookNo     INT NOT NULL,
        AdmNo      INT NOT NULL,
        IssueDate  DATE NOT NULL,
        ReturnDate DATE,
        FOREIGN KEY (BookNo) REFERENCES BOOK(BookNo)
    );
  4. 1 mark

    Write a query to list the issue number and book number of all books that have not yet been returned.

    Answer

    SELECT IssueNo, BookNo FROM ISSUE WHERE ReturnDate IS NULL;

Case study 2

Refer to the ITEM table of the stationery shop given in the long-answer questions. The owner, Mr Bhatia, is learning SQL from his daughter, who is in Class 11. He has written some queries and wants to know what they will do.

  1. 1 mark

    Write the output of: SELECT IName, Qty FROM ITEM WHERE Qty < 50 OR Qty IS NULL;

    Answer
    MySQL
    SELECT IName, Qty FROM ITEM WHERE Qty < 50 OR Qty IS NULL;
    Output
    +--------------+------+
    | IName        | Qty  |
    +--------------+------+
    | Fountain Pen |   25 |
    | Geometry Box |   18 |
    | Pencil Box   | NULL |
    +--------------+------+
    3 rows in set (0.00 sec)
  2. 1 mark

    Write the output of: SELECT DISTINCT Category FROM ITEM WHERE Price > 50;

    Answer
    MySQL
    SELECT DISTINCT Category FROM ITEM WHERE Price > 50;
    Output
    +----------+
    | Category |
    +----------+
    | Pen      |
    | Paper    |
    | Kit      |
    +----------+
    3 rows in set (0.00 sec)
  3. 1 mark

    He wants to see items whose code ends in 5, 6 or 7. Write the query using LIKE or IN.

    Answer

    SELECT * FROM ITEM WHERE ICode IN ('I105', 'I106', 'I107'); or ... WHERE ICode LIKE '%5' OR ICode LIKE '%6' OR ICode LIKE '%7';

  4. 1 mark

    He typed DELETE FROM ITEM; by mistake instead of DROP TABLE ITEM;. What is the difference in the result?

    Answer

    DELETE FROM ITEM removed all rows but the empty table ITEM still exists; DROP TABLE would have removed the table itself along with its structure.

Case study 3

A railway enquiry project stores train data in the table TRAIN (TrainNo CHAR(5) primary key, TName, Source, Dest, Fare, Coaches). Sample rows:

  • 12951, Mumbai Rajdhani, Mumbai, New Delhi, 3150, 22
  • 12002, Bhopal Shatabdi, New Delhi, Bhopal, 1655, 18
  • 12627, Karnataka Express, Bengaluru, New Delhi, 2210, 24
  • 22436, Vande Bharat Express, New Delhi, Varanasi, 1805, 16
  • 12839, Howrah Mail, Howrah, Chennai, 1930, NULL
  • 12423, Dibrugarh Rajdhani, Dibrugarh, New Delhi, 4120, 20
  1. 1 mark

    Write a query to display the name and fare of trains going to New Delhi, cheapest first.

    Answer
    MySQL
    SELECT TName, Fare FROM TRAIN WHERE Dest = 'New Delhi' ORDER BY Fare;
    Output
    +--------------------+------+
    | TName              | Fare |
    +--------------------+------+
    | Karnataka Express  | 2210 |
    | Mumbai Rajdhani    | 3150 |
    | Dibrugarh Rajdhani | 4120 |
    +--------------------+------+
    3 rows in set (0.00 sec)
  2. 1 mark

    Write a query to display the names of trains whose name contains 'Rajdhani' or 'Express'.

    Answer
    MySQL
    SELECT TName FROM TRAIN WHERE TName LIKE '%Rajdhani%' OR TName LIKE '%Express%';
    Output
    +----------------------+
    | TName                |
    +----------------------+
    | Dibrugarh Rajdhani   |
    | Karnataka Express    |
    | Mumbai Rajdhani      |
    | Vande Bharat Express |
    +----------------------+
    4 rows in set (0.00 sec)
  3. 1 mark

    Why is TrainNo declared as CHAR(5) and not INT?

    Answer

    Train numbers are identifiers, never used for arithmetic, and are always exactly 5 characters, so fixed-length CHAR(5) is suitable (it also keeps any leading zero).

  4. 1 mark

    The number of coaches of Howrah Mail is found to be 21, and all fares are to be raised by 50. Write the two statements.

    Answer
    MySQL
    UPDATE TRAIN SET Coaches = 21 WHERE TrainNo = '12839';
    UPDATE TRAIN SET Fare = Fare + 50;
    Output
    Query OK, 1 row affected (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    
    Query OK, 6 rows affected (0.00 sec)
    Rows matched: 6  Changed: 6  Warnings: 0

Practicals

1Create and open a database

Create a database named SCHOOL, check that it has been created, open it, and confirm that it does not yet have any tables.

Solution
MySQL
CREATE DATABASE SCHOOL;
SHOW DATABASES LIKE 'SCHOOL';
USE SCHOOL;
SHOW TABLES;
Output
Query OK, 1 row affected (0.00 sec)

+-------------------+
| Database (SCHOOL) |
+-------------------+
| SCHOOL            |
+-------------------+
1 row in set (0.00 sec)

Empty set (0.00 sec)
Viva questions (3)
  • Which command lists all databases on the server? SHOW DATABASES;
  • What does the message "Database changed" mean? The USE command worked and SCHOOL is now the current database.
  • Which category does CREATE DATABASE belong to? DDL.

2Create the STUDENT table with a primary key

In the SCHOOL database, create a table STUDENT with the attributes RollNo (student id), Name, Class, Section, Gender, DOB and Marks, where RollNo is the primary key and Name cannot be left empty. Display its structure.

Solution
MySQL
CREATE TABLE STUDENT (
    RollNo  INT PRIMARY KEY,
    Name    VARCHAR(30) NOT NULL,
    Class   INT,
    Section CHAR(1) DEFAULT 'A',
    Gender  CHAR(1),
    DOB     DATE,
    Marks   INT
);
DESC STUDENT;
Output
Query OK, 0 rows affected (0.00 sec)

+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| RollNo  | int         | NO   | PRI | NULL    |       |
| Name    | varchar(30) | NO   |     | NULL    |       |
| Class   | int         | YES  |     | NULL    |       |
| Section | char(1)     | YES  |     | A       |       |
| Gender  | char(1)     | YES  |     | NULL    |       |
| DOB     | date        | YES  |     | NULL    |       |
| Marks   | int         | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
Viva questions (3)
  • Why is RollNo shown with Null = NO although NOT NULL was not written? A primary key is automatically NOT NULL.
  • Why is Gender CHAR(1) and not VARCHAR? Every value has exactly one character, so fixed length suits it.
  • What is the degree of this table? 7.

3Insert details of 10 students

Insert the details of 10 students into STUDENT. Leave the marks of RollNo 4 and the date of birth of RollNo 7 empty (NULL), since they are not yet available.

Solution
MySQL
INSERT INTO STUDENT VALUES
(1,  'Aarav Sharma', 11, 'A', 'M', '2009-03-14', 78),
(2,  'Diya Menon',   12, 'B', 'F', '2008-07-22', 91),
(3,  'Kabir Singh',  11, 'A', 'M', '2008-11-05', 45),
(4,  'Ananya Iyer',  12, 'C', 'F', '2008-01-30', NULL),
(5,  'Rohan Das',    12, 'B', 'M', '2009-09-18', 62),
(6,  'Sneha Patil',  12, 'A', 'F', '2007-12-25', 84),
(7,  'Vihaan Gupta', 11, 'C', 'M', NULL,         38),
(8,  'Meera Nair',   11, 'B', 'F', '2008-05-10', 70),
(9,  'Ishaan Verma', 12, 'C', 'M', '2008-02-14', 55),
(10, 'Pooja Reddy',  11, 'A', 'F', '2009-06-03', 49);
Output
Query OK, 10 rows affected (0.00 sec)
Records: 10  Duplicates: 0  Warnings: 0
Viva questions (3)
  • Why are dates written in quotes? Dates are treated like text literals in the 'YYYY-MM-DD' format.
  • How do you insert a missing value? Write NULL without quotes.
  • What would happen if RollNo 3 were inserted twice? ERROR 1062: duplicate entry for the primary key.

4Display the entire table

Display the entire content of the table STUDENT.

Solution
MySQL
SELECT * FROM STUDENT;
Output
+--------+--------------+-------+---------+--------+------------+-------+
| RollNo | Name         | Class | Section | Gender | DOB        | Marks |
+--------+--------------+-------+---------+--------+------------+-------+
|      1 | Aarav Sharma |    11 | A       | M      | 2009-03-14 |    78 |
|      2 | Diya Menon   |    12 | B       | F      | 2008-07-22 |    91 |
|      3 | Kabir Singh  |    11 | A       | M      | 2008-11-05 |    45 |
|      4 | Ananya Iyer  |    12 | C       | F      | 2008-01-30 |  NULL |
|      5 | Rohan Das    |    12 | B       | M      | 2009-09-18 |    62 |
|      6 | Sneha Patil  |    12 | A       | F      | 2007-12-25 |    84 |
|      7 | Vihaan Gupta |    11 | C       | M      | NULL       |    38 |
|      8 | Meera Nair   |    11 | B       | F      | 2008-05-10 |    70 |
|      9 | Ishaan Verma |    12 | C       | M      | 2008-02-14 |    55 |
|     10 | Pooja Reddy  |    11 | A       | F      | 2009-06-03 |    49 |
+--------+--------------+-------+---------+--------+------------+-------+
10 rows in set (0.00 sec)
Viva questions (3)
  • What does * mean in SELECT *? All columns of the table.
  • What is the cardinality of the table now? 10.
  • Is SELECT a DDL, DML or DQL command? DQL.

5Students scoring more than 50

Display RollNo, Name and Marks of those students who scored more than 50 marks.

Solution
MySQL
SELECT RollNo, Name, Marks FROM STUDENT WHERE Marks > 50;
Output
+--------+--------------+-------+
| RollNo | Name         | Marks |
+--------+--------------+-------+
|      1 | Aarav Sharma |    78 |
|      2 | Diya Menon   |    91 |
|      5 | Rohan Das    |    62 |
|      6 | Sneha Patil  |    84 |
|      8 | Meera Nair   |    70 |
|      9 | Ishaan Verma |    55 |
+--------+--------------+-------+
6 rows in set (0.00 sec)
Viva questions (3)
  • Why is Ananya (RollNo 4) not shown? Her Marks is NULL, and NULL fails every comparison.
  • How would you include students who scored exactly 50? Use Marks >= 50.
  • Name two other relational operators. <> (not equal) and <=.

6Students born in a given year

Display RollNo, Name and DOB of those students who were born between '2008-01-01' and '2008-12-31'. (The CBSE list uses the year 2005; use the year that fits your data.)

Solution
MySQL
SELECT RollNo, Name, DOB FROM STUDENT WHERE DOB BETWEEN '2008-01-01' AND '2008-12-31';
Output
+--------+--------------+------------+
| RollNo | Name         | DOB        |
+--------+--------------+------------+
|      2 | Diya Menon   | 2008-07-22 |
|      3 | Kabir Singh  | 2008-11-05 |
|      4 | Ananya Iyer  | 2008-01-30 |
|      8 | Meera Nair   | 2008-05-10 |
|      9 | Ishaan Verma | 2008-02-14 |
+--------+--------------+------------+
5 rows in set (0.00 sec)
Viva questions (3)
  • Are the end dates included by BETWEEN? Yes, both are included.
  • Write the same condition without BETWEEN. DOB >= '2008-01-01' AND DOB <= '2008-12-31'.
  • Why is Vihaan not listed? His DOB is NULL.

7Using IN, AND and ORDER BY

Display the name, class, section and marks of girls in sections A or C, and separately display all students of Class 12 in descending order of marks.

Solution
MySQL
SELECT Name, Class, Section, Marks FROM STUDENT
WHERE Gender = 'F' AND Section IN ('A', 'C');
SELECT RollNo, Name, Marks FROM STUDENT WHERE Class = 12 ORDER BY Marks DESC;
Output
+-------------+-------+---------+-------+
| Name        | Class | Section | Marks |
+-------------+-------+---------+-------+
| Ananya Iyer |    12 | C       |  NULL |
| Sneha Patil |    12 | A       |    84 |
| Pooja Reddy |    11 | A       |    49 |
+-------------+-------+---------+-------+
3 rows in set (0.00 sec)

+--------+--------------+-------+
| RollNo | Name         | Marks |
+--------+--------------+-------+
|      2 | Diya Menon   |    91 |
|      6 | Sneha Patil  |    84 |
|      5 | Rohan Das    |    62 |
|      9 | Ishaan Verma |    55 |
|      4 | Ananya Iyer  |  NULL |
+--------+--------------+-------+
5 rows in set (0.00 sec)
Viva questions (3)
  • What is the default order of ORDER BY? Ascending (ASC).
  • Where does a NULL appear in descending order in MySQL? At the end.
  • Rewrite Section IN ('A', 'C') using OR. Section = 'A' OR Section = 'C'.

8Pattern matching and NULL checks

(a) Display names of students whose name starts with 'A' or 'S'. (b) Display names of students whose name has 'a' as the second letter. (c) Display RollNo and Name of students whose marks or date of birth is missing.

Solution
MySQL
SELECT Name FROM STUDENT WHERE Name LIKE 'A%' OR Name LIKE 'S%';
SELECT Name FROM STUDENT WHERE Name LIKE '_a%';
SELECT RollNo, Name FROM STUDENT WHERE Marks IS NULL OR DOB IS NULL;
Output
+--------------+
| Name         |
+--------------+
| Aarav Sharma |
| Ananya Iyer  |
| Sneha Patil  |
+--------------+
3 rows in set (0.00 sec)

+--------------+
| Name         |
+--------------+
| Aarav Sharma |
| Kabir Singh  |
+--------------+
2 rows in set (0.00 sec)

+--------+--------------+
| RollNo | Name         |
+--------+--------------+
|      4 | Ananya Iyer  |
|      7 | Vihaan Gupta |
+--------+--------------+
2 rows in set (0.00 sec)
Viva questions (3)
  • What is the difference between % and _? % matches any number of characters, _ exactly one.
  • Is LIKE case-sensitive in MySQL? Not for normal text columns.
  • Why not write Marks = NULL? It is never true; use IS NULL.

9Updating and deleting records

(a) Ananya's marks have been declared as 88; update her record. (b) Give 5 grace marks to every student who scored below 50. (c) Vihaan (RollNo 7) has left the school; delete his record. Display RollNo, Name and Marks after the changes.

Solution
MySQL
UPDATE STUDENT SET Marks = 88 WHERE RollNo = 4;
UPDATE STUDENT SET Marks = Marks + 5 WHERE Marks < 50;
DELETE FROM STUDENT WHERE RollNo = 7;
SELECT RollNo, Name, Marks FROM STUDENT;
Output
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

Query OK, 1 row affected (0.00 sec)

+--------+--------------+-------+
| RollNo | Name         | Marks |
+--------+--------------+-------+
|      1 | Aarav Sharma |    78 |
|      2 | Diya Menon   |    91 |
|      3 | Kabir Singh  |    50 |
|      4 | Ananya Iyer  |    88 |
|      5 | Rohan Das    |    62 |
|      6 | Sneha Patil  |    84 |
|      8 | Meera Nair   |    70 |
|      9 | Ishaan Verma |    55 |
|     10 | Pooja Reddy  |    54 |
+--------+--------------+-------+
9 rows in set (0.00 sec)
Viva questions (3)
  • What happens if WHERE is left out of UPDATE? Every row is updated.
  • Is UPDATE DDL or DML? DML.
  • After the DELETE, what is the cardinality? 9.

10Changing structure with ALTER and DROP

(a) Add a column Phone CHAR(10) to STUDENT and fill it for RollNo 2. (b) Increase the size of Name to 40 characters, keeping it NOT NULL. (c) Remove the column Phone. (d) Create a table TEMP_LIST with one column, then drop it and show the tables left.

Solution
MySQL
ALTER TABLE STUDENT ADD Phone CHAR(10);
UPDATE STUDENT SET Phone = '9876543210' WHERE RollNo = 2;
SELECT RollNo, Name, Phone FROM STUDENT WHERE RollNo <= 3;
ALTER TABLE STUDENT MODIFY Name VARCHAR(40) NOT NULL;
ALTER TABLE STUDENT DROP Phone;
CREATE TABLE TEMP_LIST (Item VARCHAR(20));
DROP TABLE TEMP_LIST;
SHOW TABLES;
Output
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

+--------+--------------+------------+
| RollNo | Name         | Phone      |
+--------+--------------+------------+
|      1 | Aarav Sharma | NULL       |
|      2 | Diya Menon   | 9876543210 |
|      3 | Kabir Singh  | NULL       |
+--------+--------------+------------+
3 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+------------------+
| Tables_in_school |
+------------------+
| STUDENT          |
+------------------+
1 row in set (0.00 sec)
Viva questions (3)
  • What value do old rows get in a newly added column? NULL (or the DEFAULT, if one is set).
  • Why is NOT NULL repeated in MODIFY? MODIFY replaces the full column definition, so constraints not repeated are lost.
  • Difference between ALTER TABLE ... DROP and DROP TABLE? The first removes one column; the second removes the whole table.

Common mistakes

  • Writing WHERE Marks = NULL or WHERE Marks = 'NULL'. Both return no rows. The correct test is WHERE Marks IS NULL.

  • Forgetting quotes around text and dates (WHERE Name = Diya Menon, DOB > 2008-01-01). Text and dates must be in single quotes: 'Diya Menon', '2008-01-01'. Numbers need no quotes.

  • Writing dates as '22-07-2008' or '22/07/2008'. MySQL expects 'YYYY-MM-DD', i.e. '2008-07-22'.

  • Using = with wildcards (WHERE Name = 'A%'). Wildcards work only with LIKE: WHERE Name LIKE 'A%'.

  • Writing WHERE Section = 'A' OR 'C'. Each condition needs its own column: WHERE Section = 'A' OR Section = 'C', or better WHERE Section IN ('A', 'C').

  • Running UPDATE or DELETE without a WHERE clause and changing every row. Always check the rows with a SELECT using the same WHERE first.

  • Confusing DELETE with DROP. DELETE FROM STUDENT; empties the table but keeps it; DROP TABLE STUDENT; removes the table itself.

  • Confusing ALTER with UPDATE. ALTER changes the structure (columns); UPDATE changes values in rows.

  • Putting ORDER BY before WHERE, or writing ORDER Marks. The order is SELECT, FROM, WHERE, ORDER BY, and the keyword is two words: ORDER BY.

  • Missing the semicolon in the MySQL client and thinking the computer has hung at the -> prompt.