Skip to content
Skip to page content
soylai.com

Structured Query Language (SQL) — Notes

6 sections 6 min readBeta

1. SQL, DDL and DML; data types and constraints

SQL is the standard, declarative language of relational databases such as MySQL.

  • DDL (structure): CREATE, ALTER, DROP.
  • DML (rows): INSERT, UPDATE, DELETE, SELECT.

Data types: CHAR(n) fixed length (padded), VARCHAR(n) variable length, INT, FLOAT, DATE ('YYYY-MM-DD').

Constraints: NOT NULL (value required), UNIQUE (no repeats; several NULLs allowed), PRIMARY KEY (unique and not null; one per table).

Table comparing DDL, which works on structure with CREATE, ALTER and DROP, and DML, which works on rows with INSERT, UPDATE, DELETE and SELECT
CategoryWorks onCommands
DDL (Data Definition Language)Structure of databases and tablesCREATE, ALTER, DROP
DML (Data Manipulation Language)Rows of data in tablesINSERT, UPDATE, DELETE, SELECT
Table of MySQL data types: CHAR fixed-length text, VARCHAR variable-length text, INT whole numbers, FLOAT decimal numbers and DATE in year-month-day form, each with an example column
Data typeStoresExample
CHAR(n)Fixed-length text of n characters (padded)Class CHAR(3) → 12A
VARCHAR(n)Variable-length text, up to n charactersName VARCHAR(20) → Aarav
INTWhole numbersMarks INT → 88
FLOATNumbers with a decimal partRating FLOAT → 4.5
DATEA date written YYYY-MM-DDStartDate DATE → 2026-11-14
Table of constraints: NOT NULL requires a value, UNIQUE forbids repeated values, and PRIMARY KEY is unique and not null and identifies each row
ConstraintRule it enforcesTypical column
NOT NULLA value must be enteredName
UNIQUENo two rows may have the same value (several NULLs allowed)Email
PRIMARY KEYUnique and not null; identifies each row; one per tableRollNo

Key terms

DDL

Commands that define or change the structure of databases and tables: CREATE, ALTER, DROP.

DML

Commands that insert, change, delete or retrieve rows: INSERT, UPDATE, DELETE, SELECT.

Constraint

A rule on a column that the database enforces, such as NOT NULL, UNIQUE or PRIMARY KEY.

2. Database and table commands

CREATE DATABASE vidyalaya;
SHOW DATABASES;
USE vidyalaya;
SHOW TABLES;
DESCRIBE STUDENT;
ALTER TABLE STUDENT ADD Phone CHAR(10);
ALTER TABLE STUDENT DROP Phone;
ALTER TABLE ROOM ADD PRIMARY KEY (RoomNo);
ALTER TABLE ROOM DROP PRIMARY KEY;
DROP TABLE ROOM;
DROP DATABASE hostel;

INSERT: INSERT INTO CLUB VALUES (5, 'Art', 'Ms Das', 250); or with a column list: INSERT INTO CLUB (ClubID, ClubName) VALUES (6, 'Yoga'); (unlisted columns become NULL).

Table of ALTER and DROP commands: add or remove a column, add or remove a primary key, drop a table and drop a database
TaskCommand
Add a columnALTER TABLE STUDENT ADD Phone CHAR(10);
Remove a columnALTER TABLE STUDENT DROP Phone;
Add a primary keyALTER TABLE ROOM ADD PRIMARY KEY (RoomNo);
Remove the primary keyALTER TABLE ROOM DROP PRIMARY KEY;
Delete a tableDROP TABLE ROOM;
Delete a databaseDROP DATABASE hostel;
A first session in MySQL
Design of STUDENT (the structure DESCRIBE STUDENT would report)
ColumnTypeConstraint
RollNoINTPRIMARY KEY
NameVARCHAR(20)NOT NULL
ClassCHAR(3)
StreamVARCHAR(12)
MarksINT
CityVARCHAR(15)
ClubIDINT

Key terms

DESCRIBE

Shows the columns, data types and keys of a table.

ALTER TABLE

Changes the structure of a table: adds or removes columns or keys.

3. SELECT with WHERE, IN, BETWEEN and LIKE

General form: SELECT columns FROM table WHERE condition ORDER BY column;

  • * selects all columns; DISTINCT removes repeated rows; AS gives an alias; arithmetic (Price * Stock) is allowed.
  • Relational: =, <>, >, <, >=, <=; logical: AND, OR, NOT.
  • IN ('Pune', 'Nashik') matches any value in the list; BETWEEN 70 AND 90 includes both ends.
  • LIKE: % any run of characters, _ exactly one character.
SELECT Name, Marks FROM STUDENT WHERE Marks BETWEEN 70 AND 90 AND City IN ('Pune', 'Nagpur') ORDER BY Name;
Name    Marks
Aarav   88
Bhavna  74
Farah   79
Hina    83
SELECT Name, Stream, Marks FROM STUDENT WHERE Marks >= 80 AND Stream <> 'Science' ORDER BY Marks DESC;
NameStreamMarks
DiyaHumanities91
HinaCommerce83
SELECT PName FROM PRODUCT WHERE PName LIKE '%Box' ORDER BY PName;
PName
Geometry Box
Lunch Box
SELECT Name, Marks + 5 AS Revised FROM STUDENT WHERE City = 'Nashik' ORDER BY Name;
NameRevised
Diya96
Gaurav100

Key terms

Alias

A temporary name for a column or table in a query, given with AS.

Wildcard

A LIKE symbol: % for any number of characters, _ for exactly one.

4. NULL and ORDER BY

NULL means missing or unknown. Any comparison with NULL using = or <> is never true, so test with IS NULL or IS NOT NULL.

ORDER BY sorts ascending by default; DESC sorts descending. With two columns, the second sorts within ties of the first. In ascending order MySQL puts NULL first.

SELECT PName, Stock FROM PRODUCT ORDER BY Stock DESC;
PName            Stock
Gel Pen          300
Notebook         120
Sketch Pens      80
Water Bottle     45
Lunch Box        30
Extension Board  20
Desk Lamp        12
Geometry Box     NULL

In descending order the NULL stock comes last.

SELECT Name, Stream FROM STUDENT WHERE ClubID IS NULL ORDER BY Name;
NameStream
ChiragScience
FarahHumanities
SELECT Name, Class, Marks FROM STUDENT ORDER BY Class, Marks DESC;
NameClassMarks
Gaurav12A95
Aarav12A88
Chirag12A65
Hina12B83
Bhavna12B74
Eshan12B58
Diya12C91
Farah12C79

Key terms

NULL

A missing or unknown value; not zero and not an empty string.

5. Aggregate functions, GROUP BY and HAVING

COUNT, SUM, AVG, MIN, MAX give one value from many rows and skip NULL (only COUNT(*) counts every row). MySQL shows averages with decimal places (for example 85.0000).

GROUP BY col gives one result row per group; HAVING filters groups and may use aggregates; WHERE filters rows before grouping and may not.

Written order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.

SELECT City, COUNT(*), MAX(Marks) FROM STUDENT WHERE Stream <> 'Commerce' GROUP BY City HAVING COUNT(*) >= 2 ORDER BY City;
City    COUNT(*)  MAX(Marks)
Nashik  2         95
Pune    2         88
SELECT Stream, COUNT(*), AVG(Marks) FROM STUDENT GROUP BY Stream ORDER BY Stream;
StreamCOUNT(*)AVG(Marks)
Commerce371.6667
Humanities285
Science382.6667
SELECT COUNT(*), MIN(Marks), MAX(Marks), SUM(Marks), AVG(Marks) FROM STUDENT; (MySQL shows the average as 79.1250)
COUNT(*)MIN(Marks)MAX(Marks)SUM(Marks)AVG(Marks)
8589563379.125
SELECT COUNT(*), COUNT(ClubID), COUNT(DISTINCT ClubID) FROM STUDENT;
COUNT(*)COUNT(ClubID)COUNT(DISTINCT ClubID)
863
Table comparing WHERE and HAVING: WHERE works on rows before grouping and cannot use aggregates; HAVING works on groups after grouping and can
WHEREHAVING
Works onSingle rowsGroups
WhenBefore GROUP BYAfter GROUP BY
Aggregate functions allowed?NoYes
ExampleWHERE Marks > 60HAVING COUNT(*) >= 2

Key terms

Aggregate function

A function that returns one value from a set of rows: COUNT, SUM, AVG, MIN, MAX.

HAVING

The clause that keeps only the groups satisfying a condition, written after GROUP BY.

6. Joins, UPDATE and DELETE

Cartesian product: SELECT * FROM A, B; pairs every row of A with every row of B. Degree = degree(A) + degree(B); cardinality = cardinality(A) × cardinality(B).

Equi-join: WHERE A.col = B.col; the common column appears twice with SELECT *.

Natural join: A NATURAL JOIN B matches the column with the same name and shows it once.

SELECT S.Name, C.ClubName, C.Fee FROM STUDENT S, CLUB C WHERE S.ClubID = C.ClubID AND S.Marks > 80 ORDER BY C.Fee DESC, S.Name;
Name    ClubName  Fee
Gaurav  Robotics  500
Aarav   Music     300
Diya    Debate    200
Hina    Debate    200

UPDATE table SET col = value WHERE …; changes rows; DELETE FROM table WHERE …; removes rows (all rows without WHERE; the table remains).

Equi-join pairs rows with equal ClubID values
Rows multiply, columns add
STUDENTCLUBCartesian product
8 rows × 7 columns4 rows × 4 columns32 rows × 11 columns
SELECT PName, SupName, City FROM PRODUCT NATURAL JOIN SUPPLIER WHERE Price < 100 ORDER BY PName;
PNameSupNameCity
Gel PenSwastik SuppliesIndore
Geometry BoxKaveri TradersChennai
NotebookKaveri TradersChennai
UPDATE CLUB SET Fee = Fee + 100 WHERE Fee >= 300;
ClubNameFee beforeFee after
Robotics500600
Music300400
Debate200200
Chess150150
Table comparing DELETE with a condition, DELETE without a condition and DROP TABLE: what each removes, whether the table remains, and whether it is DML or DDL
CommandRemovesTable remains?Category
DELETE FROM T WHERE …;Matching rowsYesDML
DELETE FROM T;All rowsYes (empty)DML
DROP TABLE T;Table, structure and dataNoDDL

Key terms

Equi-join

A join that keeps pairs of rows with equal values in the joining columns.

Natural join

A join on the column with the same name in both tables, which appears once in the result.

Cardinality

The number of rows of a table or result; degree is the number of columns.

Exam tips

Common mistakes

  • = NULL instead of IS NULL.
  • An aggregate in WHERE instead of HAVING.
  • Forgetting the join condition (giving a Cartesian product), or not prefixing a column both tables share.
  • Treating BETWEEN as excluding its ends.
  • Mixing up DELETE (rows, DML) and DROP (table, DDL).

How marks are usually awarded

  • 1 mark: the correct option or keyword.
  • 2–3 marks: one mark per correct query (or per query with its output).
  • 5 marks: five correct queries or statements, each with the right clauses; outputs in the right order with column headings.

About the data here: all tables are imagined. Results were produced by running each query; MySQL may show averages with trailing zeros (85.0000).