📌 Snapshot
- Learn MySQL basics: CREATE, ALTER, INSERT, SELECT, WHERE, LIKE, UPDATE and DELETE with worked queries.
- Data types, constraints and the full set of ALTER TABLE variations, explained with the school database.
- Every SELECT clause (alias, DISTINCT, BETWEEN, IN, ORDER BY, IS NULL, LIKE) run on one EMPLOYEE table.
- The traps NTA sets: CHAR versus VARCHAR, missing WHERE, NULL comparisons and wildcard patterns.
📖 Detailed Notes
Written and reviewed by Rohit Singh, Computer Science & Commerce faculty at UniDrill (MCA, Osmania University · 6 years teaching). Based on NCERT Informatics Practices Class XI, Chapter 8.
You say what you want, not how to get it
With a file you must write a program that loops, compares and prints. With a database you write one sentence: "give me the names of students born in 2003". SQL (Structured Query Language) is the language for that sentence. You describe what data you want, and the DBMS works out how to fetch it. SQL is the standard language of relational databases such as MySQL, Oracle and SQL Server, and although it is called a query language it can also define tables, change data and set constraints.
Four habits of SQL are tested directly:
| Rule | Detail |
|---|---|
| Keywords are case insensitive | select, SELECT and SeLeCt are the same |
| Every statement ends with a semicolon | A statement may run over several lines; MySQL shows -> until you type ; |
| Text and date values go in single quotes | 'Amit Ahuja', '2003-05-15'; numbers do not |
| Database and table names | Case sensitive on Linux, not on Windows, so always type them exactly as created |
The chapter works on the StudentAttendance database from Class XI Chapter 7, and then on an EMPLOYEE table for queries.
Data types and constraints
A data type decides what values a column can hold and what you can do with them. Arithmetic works on numbers, not on text.
| Data type | Meaning | Remember |
|---|---|---|
CHAR(n) |
Fixed length text, n up to 255 | CHAR(10) always reserves 10 characters; short values are padded with spaces on the right |
VARCHAR(n) |
Variable length text, n up to 65535 | VARCHAR(30) stores only as many characters as you enter, up to 30 |
INT |
Whole numbers, 4 bytes | Range about minus 2.1 billion to plus 2.1 billion; larger needs BIGINT (8 bytes) |
FLOAT |
Numbers with decimals, 4 bytes | |
DATE |
Date in 'YYYY-MM-DD' form |
Year first, then month, then day |
Why GUID is CHAR(12) and not INT. A guardian ID is a 12 digit code of fixed length, and you will never add or average it. Identifiers, phone numbers and similar codes are labels, not quantities, so a fixed length text type fits. Roll number, on the other hand, is a small whole number, so INT is right, and a name uses VARCHAR(20) because names vary in length.
Constraints are restrictions that keep data accurate and reliable. They are optional for each column.
| Constraint | What it enforces |
|---|---|
NOT NULL |
The column cannot hold NULL |
UNIQUE |
No two rows can share a value in this column |
DEFAULT |
A fixed value is used when none is supplied |
PRIMARY KEY |
Uniquely identifies each row; behaves as NOT NULL plus UNIQUE |
FOREIGN KEY |
The value must exist as a primary key value in another table |
By default every column can take NULL, except the primary key.
Data definition: building the structure
Commands that define or change the structure of a database form Data Definition Language (DDL).
| Code |
|---|
CREATE DATABASE StudentAttendance; |
USE StudentAttendance; |
SHOW TABLES; |
CREATE DATABASE makes the database, USE selects it as the active one, and SHOW TABLES lists its tables (empty at first). Tables come next.
| Code |
|---|
CREATE TABLE STUDENT( |
RollNumber INT, |
SName VARCHAR(20), |
SDateofBirth DATE, |
GUID CHAR(12), |
PRIMARY KEY (RollNumber) |
); |
Each column needs a name and a data type; constraints are optional. The number of columns is the degree of the table. DESC STUDENT; (short for DESCRIBE) then shows its structure:
| Field | Type | Null | Key | Default |
|---|---|---|---|---|
| RollNumber | int | NO | PRI | NULL |
| SName | varchar(20) | YES | NULL | |
| SDateofBirth | date | YES | NULL | |
| GUID | char(12) | YES | NULL |
Only the primary key column says NO for null, which confirms the default rule above.
ALTER TABLE changes the structure of an existing table. One command, many jobs:
| Task | Statement |
|---|---|
| Add a primary key | ALTER TABLE GUARDIAN ADD PRIMARY KEY (GUID); |
| Add a composite primary key | ALTER TABLE ATTENDANCE ADD PRIMARY KEY (AttendanceDate, RollNumber); |
| Add a foreign key | ALTER TABLE STUDENT ADD FOREIGN KEY (GUID) REFERENCES GUARDIAN(GUID); |
| Add UNIQUE | ALTER TABLE GUARDIAN ADD UNIQUE (GPhone); |
| Add a column | ALTER TABLE GUARDIAN ADD income INT; |
| Change a data type or size | ALTER TABLE GUARDIAN MODIFY GAddress VARCHAR(40); |
| Make a column NOT NULL | ALTER TABLE STUDENT MODIFY SName VARCHAR(20) NOT NULL; |
| Set a default | ALTER TABLE STUDENT MODIFY SDateofBirth DATE DEFAULT '2000-05-15'; |
| Remove a column | ALTER TABLE GUARDIAN DROP income; |
| Remove the primary key | ALTER TABLE GUARDIAN DROP PRIMARY KEY; |
Three rules for a foreign key: the referenced table must already exist, the referenced column must be part of that table's primary key, and the data type and size of both columns must match. That is why GUARDIAN is created before the STUDENT table can point at it. Note also that MODIFY always repeats the data type, even when you only want to add NOT NULL or DEFAULT.
DROP removes a table or a whole database permanently: DROP TABLE table_name; and DROP DATABASE database_name;. It cannot be undone, and dropping a database removes every table in it.
Beyond the textbook. For the exam: DROP removes the whole table, while DELETE removes some or all rows but keeps the table. In reality: the difference is also one of category. DDL commands (CREATE, ALTER, DROP) work on structure and generally cannot be rolled back, while data manipulation commands (INSERT, UPDATE, DELETE) work on rows. Why it matters: "Which command removes the table itself?" always has the answer DROP, never DELETE.
Data manipulation: INSERT, UPDATE, DELETE
A new table has structure but no rows. INSERT INTO adds a row. If you give a value for every column, in table order, you can skip the column list.
| Code |
|---|
INSERT INTO GUARDIAN |
VALUES ('444444444444', 'Amit Ahuja', '5711492685', 'G-35, Ashok Vihar, Delhi'); |
INSERT INTO GUARDIAN(GUID, GName, GAddress) |
VALUES ('333333333333', 'Danny Dsouza', 'S-13, Ashok Village, Daman'); |
The second form names the columns it fills; the others (here GPhone) get NULL or their default. The values must follow the order of the column list. When a row has a foreign key, the referenced table must already contain the matching row, so you fill GUARDIAN before STUDENT. If a row has no guardian yet, you can supply NULL for the foreign key.
UPDATE changes values in existing rows, and DELETE removes rows. Both need a WHERE condition to pick the rows.
| Code |
|---|
UPDATE STUDENT |
SET GUID = '101010101010' |
WHERE RollNumber = 3; |
DELETE FROM STUDENT |
WHERE RollNumber = 2; |
Pause and predict: what does UPDATE STUDENT SET GUID = '101010101010'; do if you forget the WHERE clause?
Check your answer: It changes the GUID of every row in the table to 101010101010. Without WHERE, UPDATE applies to all rows, and DELETE FROM STUDENT would empty the whole table. Always write the condition first and check which rows it selects.
The SELECT statement
SELECT retrieves data and always displays it as a table. The skeleton is:
| Code |
|---|
SELECT column1, column2 |
FROM table_name |
WHERE condition; |
FROM is always present. WHERE is optional and keeps only the rows that satisfy the condition. SELECT * means all columns. All the examples below use this EMPLOYEE table.
| 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 |
Worked example: alias and calculation. Show each employee's name as Name and annual salary as Annual Salary, for those earning 40000 or more, highest first.
| Code |
|---|
SELECT Ename AS Name, Salary*12 AS 'Annual Salary' |
FROM EMPLOYEE |
WHERE Salary >= 40000 |
ORDER BY Salary DESC; |
| Name | Annual Salary |
|---|---|
| Kritika | 720000 |
| Tanya | 600000 |
| Sanya | 576000 |
| Shabbir | 540000 |
| Daribha | 504000 |
| Step | Thinking |
|---|---|
| 1 | AS renames a column only in the output. A new column is not added to the table |
| 2 | An alias with a space needs quotes, 'Annual Salary' |
| 3 | WHERE filters rows first; ORDER BY sorts what is left; DESC makes the order descending (the default is ascending) |
DISTINCT removes repeated values. SELECT DISTINCT DeptId FROM EMPLOYEE; returns each department once: D02, D01, D04, D03, D05, five values instead of ten.
Conditions are built from relational operators (=, <, <=, >, >=, !=) and logical operators (AND, OR, NOT). Text values need quotes.
| Need | Condition | Rows returned |
|---|---|---|
| Both conditions true | WHERE Salary > 30000 AND NOT DeptId = 'D01' |
Joseph, Sanya, Daribha, Tanya |
| Either condition true | WHERE DeptId = 'D01' OR DeptId = 'D04' |
Kritika, Shabbir, Gurpreet, Vergese, Daribha |
| Inside a range, both ends included | WHERE Salary BETWEEN 20000 AND 45000 |
Shabbir, Joseph, Nachaobi, Daribha |
| Belongs to a list | WHERE DeptId IN ('D01', 'D02', 'D04') |
7 employees |
| Does not belong to a list | WHERE DeptId NOT IN ('D01', 'D02') |
Gurpreet, Joseph, Nachaobi, Daribha, Tanya |
BETWEEN 20000 AND 45000 is the same as Salary >= 20000 AND Salary <= 45000. The bounds are inclusive, which is why Shabbir with exactly 45000 appears. IN is a shorter way to write a chain of ORs.
Pause and predict: which employees does SELECT Ename FROM EMPLOYEE WHERE Salary BETWEEN 45000 AND 50000; return?
Check your answer: Shabbir (45000), Sanya (48000) and Tanya (50000). Both ends are included, so Shabbir and Tanya, who earn exactly the two boundary amounts, are part of the result.
Beyond the textbook. For the exam: AND needs both conditions true and OR needs either. In reality: when a WHERE clause mixes the two without brackets, AND is evaluated first. WHERE DeptId = 'D01' OR DeptId = 'D02' AND Salary > 40000 returns all D01 employees (Kritika, Shabbir, Vergese) plus only the D02 employee with a high salary (Sanya), which is probably not what you meant. Why it matters: use brackets to state your intention.
ORDER BY sorts the output. Ascending is the default, DESC reverses, and you can sort on a second column to break ties: ORDER BY DeptId, Salary DESC sorts by department and, inside each department, highest salary first.
NULL means unknown or not applicable. It is not zero, and any arithmetic with NULL gives NULL (5 + NULL is NULL). You cannot test for NULL with =; you use IS NULL and IS NOT NULL.
| Query | Result |
|---|---|
SELECT Ename FROM EMPLOYEE WHERE Bonus IS NULL; |
Vergese, Nachaobi, Daribha |
SELECT Ename FROM EMPLOYEE WHERE Bonus IS NOT NULL; |
The other 7 employees |
SELECT Ename FROM EMPLOYEE WHERE Bonus = NULL; |
No rows: nothing is ever equal to NULL |
SELECT Ename, Salary + Bonus FROM EMPLOYEE WHERE DeptId = 'D04'; |
Gurpreet 19565, Daribha NULL |
Pattern matching with LIKE. When you do not know the whole value, = is useless. LIKE uses two wildcards: percent (%) stands for any number of characters, including none, and underscore (_) stands for exactly one character.
| Pattern | Meaning | Matches in EMPLOYEE |
|---|---|---|
'K%' |
Starts with K | Kritika |
'%a' |
Ends with a | Aaliya, Kritika, Sanya, Daribha, Tanya |
'%se%' |
Contains se anywhere | Joseph, Vergese |
'_a%' |
Second letter is a | Aaliya, Sanya, Nachaobi, Daribha, Tanya |
'_anya' |
Exactly 5 letters, ending in anya | Sanya, Tanya |
'__a%' |
Third letter is a | Shabbir |
Worked example: write the query. List name and salary of employees whose name has exactly five letters and ends in "anya", in decreasing salary order.
| Step | Thinking | Written as |
|---|---|---|
| 1 | Output columns | SELECT Ename, Salary |
| 2 | Source table | FROM EMPLOYEE |
| 3 | One unknown letter, then fixed text, so use _ |
WHERE Ename LIKE '_anya' |
| 4 | Highest first | ORDER BY Salary DESC |
The result is Tanya 50000 and then Sanya 48000. The wrong step is LIKE 'anya', which matches only a name that is exactly "anya".
Beyond the textbook. For the exam: wildcards are % and _, and values are compared as typed. In reality: in MySQL's default setup comparisons on text are not case sensitive, so WHERE Ename = 'AALIYA' still returns Aaliya. Why it matters: a wrong case in a text value usually does not cause an error, but the data inside quotes must still match in spelling.
Command sheet
| Group | Commands | Purpose |
|---|---|---|
| Data definition | CREATE, ALTER, DROP, DESC, SHOW TABLES, USE |
Build and change the structure |
| Data manipulation | INSERT INTO, UPDATE, DELETE |
Add, change, remove rows |
| Query | SELECT ... FROM ... WHERE ... ORDER BY |
Read data without changing it |
| Filters | AND OR NOT, BETWEEN, IN, LIKE, IS NULL, DISTINCT, AS |
Shape the result |
Exam traps
| Trap | Why it is tempting | The truth |
|---|---|---|
"CHAR(10) and VARCHAR(10) use the same space for 'city'" |
Both hold 10 characters | CHAR reserves 10 (padded); VARCHAR uses only what is needed |
"Bonus = NULL finds missing bonuses" |
Equality works for numbers | Use IS NULL; = NULL returns nothing |
| "UPDATE or DELETE without WHERE affects one row" | You have one row in mind | It affects every row |
"BETWEEN 20 AND 40 leaves out 20 and 40" |
Between sounds like strictly inside | Both bounds are included |
"MODIFY needs only the new constraint" |
Only NOT NULL is changing | MODIFY must repeat the data type: MODIFY SName VARCHAR(20) NOT NULL |
| "DELETE removes a table" | Both remove things | DELETE removes rows; DROP removes the table |
"INSERT INTO t VALUES (...) can give fewer values" |
Short forms feel flexible | Without a column list you must supply a value for every column; otherwise name the columns |
"LIKE '_a%' means starts with a" |
The % looks like the main part | The underscore stands for one character, so the second letter is a |
60-second revision
| Topic | Remember |
|---|---|
| SQL | Describes what to fetch; case insensitive; ends with ; |
| Text and dates | Single quotes; date format YYYY-MM-DD |
| Types | CHAR fixed, VARCHAR variable, INT whole, FLOAT decimal, DATE |
| Constraints | NOT NULL, UNIQUE, DEFAULT, PRIMARY KEY, FOREIGN KEY |
| Structure | CREATE, ALTER (ADD, MODIFY, DROP), DESC, DROP |
| Rows | INSERT INTO, UPDATE, DELETE |
| Always | Add WHERE to UPDATE and DELETE |
| NULL | IS NULL, never = NULL; arithmetic with NULL is NULL |
| Order | Ascending by default; DESC to reverse |
| LIKE | % zero or more characters, _ exactly one |
Where this chapter connects
The tables and keys here are the ones designed in Database Concepts. Class XII extends the same SELECT statement with built in functions, GROUP BY and joins in Querying and SQL Functions, and the other Class XII SQL chapter is Structured Query Language (SQL).
🎯 Practice MCQs
First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed
Q1. Which of the following is a Data Definition Language command?
▸ Show answer & explanation
Answer: C
ALTER changes the structure of a table, so it belongs to data definition, like CREATE and DROP. INSERT and UPDATE manipulate rows, and SELECT retrieves data.
Q2. Which command displays the structure (columns, types and keys) of a table named STUDENT?
▸ Show answer & explanation
Answer: B
DESC, short for DESCRIBE, lists the fields with their types, null status and keys. SHOW with a table name is not valid for this, SELECT needs a column list and FROM, and USE selects a database, not a table.
Q3. A column holds a fixed length 12 digit guardian ID that is never used in calculations. The most suitable data type is
▸ Show answer & explanation
Answer: C
A fixed length code that is only a label suits CHAR(12). INT cannot hold 12 digits safely in 4 bytes and would imply arithmetic, FLOAT is for decimals, and VARCHAR(255) wastes the idea of a known fixed size.
🔒 12 more practice MCQs
Create a free account to unlock every MCQ in this chapter — answers and explanations included. No payment needed.
Already registered? Just log in and they'll all appear here.
Q4. The word city is stored in a CHAR(10) column and in a VARCHAR(10) column. Which statement is correct?
▸ Show answer & explanation
Answer: C
CHAR is fixed length, so MySQL pads the rest with spaces. VARCHAR is variable length, so it stores only what is entered, up to the maximum. Options A, B and D mix the two up.
Q5. The table STUDENT has 4 columns: RollNumber, SName, SDateofBirth and GUID. The statement INSERT INTO STUDENT VALUES (3, 'Taleem Shah', '2002-02-28'); is executed. What happens?
▸ Show answer & explanation
Answer: C
Without a column list, a value must be given for every column, so 3 values for 4 columns is an error. To leave GUID out, name the other three columns in the statement, or supply NULL as the fourth value.
Q6. What does UPDATE STUDENT SET GUID = '101010101010'; do when no WHERE clause is written?
▸ Show answer & explanation
Answer: C
Without a WHERE clause, UPDATE applies to all rows. It does not stop at one row (A), it is valid syntax (B), and it never removes a column (D), which is done with ALTER TABLE and DROP.
Q7. Which of these names are returned by the condition Ename LIKE '_a%' from the names Aaliya, Kritika, Sanya, Joseph and Tanya?
▸ Show answer & explanation
Answer: B
The underscore matches any one first character and the next character must be a, followed by anything. Aaliya, Sanya and Tanya have a as the second letter. Kritika has r and Joseph has o. Option D confuses the pattern with 'a%'.
Q8. The condition Salary BETWEEN 20000 AND 50000 is equivalent to
▸ Show answer & explanation
Answer: B
BETWEEN includes both end values. Option A excludes them, option C is true for every number, and option D matches only the two end values themselves.
Q9. Which query correctly lists the employees whose Bonus value is missing?
▸ Show answer & explanation
Answer: C
NULL must be tested with IS NULL. Comparing with = NULL never evaluates to true, so option A returns nothing. NULL is not the same as zero, so B is wrong, and LIKE is meant for text patterns.
Q10. Assertion (A): SELECT DISTINCT DeptId FROM EMPLOYEE; can return fewer rows than there are employees. Reason (R): DISTINCT removes repeated values from the output.
▸ Show answer & explanation
Answer: A
Several employees share a department, so repeated DeptId values are collapsed and fewer rows appear. That is exactly what DISTINCT does, so R explains A.
Q11. Which clause is used to display query results in descending order of a column?
▸ Show answer & explanation
Answer: B
ORDER BY with the keyword DESC gives descending order, and ascending is the default. GROUP BY is for grouping rows, and SORT and ORDER alone are not SQL clauses for this.
Q12. The ten employees of EMPLOYEE, in order of EmpNo 101 to 110, belong to departments D02, D01, D01, D04, D03, D02, D01, D05, D04 and D05. How many rows does WHERE DeptId NOT IN ('D01', 'D02') return?
▸ Show answer & explanation
Answer: B
Remove the employees in D01 (three) and D02 (two). The remaining five are in D04, D03, D05, D04 and D05. Option C is the count of employees in D01, D02 or D04, not the NOT IN result.
Q13. Which statement adds a new column income of type INT to the table GUARDIAN?
▸ Show answer & explanation
Answer: A
Changing the structure of an existing table is done with ALTER TABLE. UPDATE changes values in rows, INSERT adds rows, and CREATE builds new objects and cannot be followed by ADD in this way.
Q14. Match List I with List II. List I: (i) DELETE (ii) DROP (iii) ALTER (iv) UPDATE. List II: (p) changes the structure of a table (q) removes a table or database permanently (r) removes rows from a table (s) changes values in existing rows.
▸ Show answer & explanation
Answer: A
DELETE removes rows, DROP removes the whole table or database, ALTER changes the structure, and UPDATE modifies values. Option B swaps DELETE and DROP, and options C and D mix up ALTER and UPDATE.
Q15. Which statement correctly makes the existing column SName of type VARCHAR(20) in STUDENT a NOT NULL column?
▸ Show answer & explanation
Answer: B
MODIFY must repeat the data type along with the new constraint. Option A leaves the data type out. Option C tries to add a column that already exists, and UPDATE changes row values, not constraints.
📊 Previous-Year Questions
Practise with real CUET Computer Science previous-year papers — every question solved, with the correct answer and a step-by-step explanation.
View solved CUET PYQ papers →Ready to drill Computer Science?
Unlock all MCQs, chapter tests, mocks & PYQs for ₹199/year.
Get UniDrill Pro