ByteBoard Notes Cheat sheets Full notes

Databases and SQL, on two pages

Everything the board asks from this unit (20 marks in CS, 25 in IP), most important first. The boxes beside each heading rate how often board papers ask it, from one to five. Every output shown was run on MySQL 8.4.

Download PDF

Importance most asked often rarely

SELECT queries

Write the clauses in this order; leave out the ones you don't need:

SELECT DISTINCT col, expr AS alias
FROM table
WHERE condition
GROUP BY col
HAVING group_condition
ORDER BY col DESC;
In WHEREExample
CompareMarks >= 80 · Class <> '12A'
AND, OR, NOTClass='12A' AND Marks>80
BETWEENMarks BETWEEN 70 AND 90 (both ends included)
INCity IN ('Delhi','Pune')
LIKE% any number of characters, _ exactly one
NULLMarks IS NULL · IS NOT NULL
LIKE patternMatches
'A%'starts with A
'%a'ends with a
'%an%'has "an" anywhere
'_a%'a is the second letter
'____'exactly four characters

ORDER BY is ascending by default; DESC applies only to the column it follows. DISTINCT removes duplicate rows. An alias (AS) renames only the output heading.

Never = NULL: write IS NULL. A NULL row fails every comparison, so it is in neither Marks > 80 nor Marks <= 80. Text and dates need quotes; numbers don't.

Aggregates, GROUP BY, HAVING

Table S, used for every output below:

RollNameClassMarks
1Aman12A91
2Riya12B78
3Kabir12ANULL
4Sara12B85
5Dev12A62
FunctionResultWhy
COUNT(*)5counts rows, NULLs too
COUNT(Marks)4skips the NULL
SUM(Marks)316
AVG(Marks)79.0000316 ÷ 4, not ÷ 5
MAX · MIN91 · 62
COUNT(DISTINCT Class)212A, 12B
SELECT Class, COUNT(*), AVG(Marks)
FROM S GROUP BY Class;          -- 12A 3 76.5000
                                -- 12B 2 81.5000
SELECT Class, COUNT(*) FROM S
GROUP BY Class HAVING COUNT(*) > 2;   -- 12A 3

WHERE filters rows before grouping; HAVING filters groups after. "Class-wise", "gender-wise", "category-wise" → GROUP BY that column, and put it in SELECT too.

Aggregates can't go in WHERE: WHERE COUNT(*) > 5 must become HAVING COUNT(*) > 5, written after GROUP BY. All aggregates except COUNT(*) ignore NULLs.

Single-row functions

MathResult
POWER(2,3)8
ROUND(15.193,1) · ROUND(15.5)15.2 · 16
ROUND(1567.8,-2) · ROUND(1567.8,-1)1600 · 1570
MOD(29,6)5 (remainder)
TextResult
UCASE('sql') / UPPER · LCASE('MySQL') / LOWERSQL · mysql
MID('Informatics',3,4) = SUBSTRform
LENGTH('Hello World')11 (space counts)
LEFT('Database',4) · RIGHT('Database',4)Data · base
INSTR('Database','base') · INSTR('Database','z')5 · 0
LTRIM · RTRIM · TRIM(' Hi ')'Hi ' · ' Hi' · 'Hi'
Date, for '2026-03-14'Result
NOW()current date and time
DATE('2026-03-14 10:30:00')2026-03-14
MONTH · MONTHNAME3 · March
DAY · DAYNAME14 · Saturday
YEAR2026

Positions start at 1. INSTR gives 0 when not found. Nested calls work inside out: ROUND(MOD(29,6)*2.456,1) → 5 × 2.456 = 12.28 → 12.3.

Relational terms and keys

TermMeans
Relationa table
Tuplea row (record)
Attributea column (field)
Domainthe set of values a column may take
Degreenumber of columns
Cardinalitynumber of rows (cardinality counts records)
KeyMeans
Candidate keyany column that can identify each row uniquely
Primary keythe candidate key chosen; unique, never NULL, one per table
Alternate keycandidate keys not chosen as primary
Foreign keya column that refers to the primary key of another table; links tables

4 rows × 3 columns; add 2 rows, remove 1 column → degree 2, cardinality 6. "Keeps data integrity between tables" → foreign key.

DDL and DML commands

TypeCommandsChanges
DDL (definition)CREATE, ALTER, DROPthe structure
DML (manipulation)INSERT, UPDATE, DELETEthe data
DQL (query)SELECTnothing; only reads
CREATE DATABASE School;  USE School;
CREATE TABLE S (Roll INT PRIMARY KEY,
  Name VARCHAR(20), Class CHAR(3), Marks INT);
ALTER TABLE S ADD City VARCHAR(15);
ALTER TABLE S DROP City;
ALTER TABLE S DROP PRIMARY KEY;
ALTER TABLE S ADD PRIMARY KEY (Roll);
INSERT INTO S VALUES (6,'Neha','12B',88);
UPDATE S SET Marks = Marks + 5 WHERE Roll = 2;
DELETE FROM S WHERE Marks IS NULL;
DROP TABLE S;      -- removes the whole table

Also: SHOW DATABASES; SHOW TABLES; DESCRIBE S; (or DESC S;) shows the structure.

CHAR(n)VARCHAR(n)
Lengthfixed: always n charactersvariable: up to n
'Hi' in (10)uses 10, padded with spacesuses 2

ALTER changes the degree; INSERT and DELETE change the cardinality; UPDATE changes neither. Without WHERE, UPDATE and DELETE hit every row. DROP removes the table; DELETE only its rows.

Python and MySQL connectivity

Every program follows the same six steps. A full-marks answer shows all six.

StepCode
1 Import the connectorimport mysql.connector as m
2 Connect to a databasecon = m.connect(host=…, user=…, passwd=…, database=…)
3 Make a cursorcur = con.cursor()
4 Run the SQLcur.execute(q, values)
5 Read or savecur.fetchall() for SELECT · con.commit() for changes
6 Closecon.close()

Display records (SELECT)

import mysql.connector as m
con = m.connect(host='localhost', user='root',
                passwd='tiger', database='School')
cur = con.cursor()
q = "SELECT Name, Marks FROM S WHERE Marks > %s"
cur.execute(q, (80,))
for row in cur.fetchall():
    print(row)
print("Rows:", cur.rowcount)
con.close()
('Aman', 91)
('Sara', 85)
Rows: 2

Insert values typed by the user (%s)

# steps 1–3: import, connect, cursor as above
r = int(input("Roll: "))
n = input("Name: ")
c = input("Class: ")
mk = int(input("Marks: "))
q = "INSERT INTO S VALUES (%s, %s, %s, %s)"
cur.execute(q, (r, n, c, mk))
con.commit()
print(cur.rowcount, "record inserted")
con.close()
Roll: 6
Name: Neha
Class: 12B
Marks: 88
1 record inserted

Update or delete (format)

# steps 1–3: import, connect, cursor as above
q = "UPDATE S SET Marks = {} WHERE Name = '{}'"
cur.execute(q.format(80, 'Riya'))
con.commit()
print(cur.rowcount, "record updated")
cur.execute("DELETE FROM S WHERE Marks IS NULL")
con.commit()
print(cur.rowcount, "record deleted")
con.close()
1 record updated
1 record deleted
%s placeholderformat()
Values goin a tuple: execute(q, (80,))into the string: q.format(80)
Quotes for textthe connector adds themyou write them: '{}'
MethodGives
fetchone()next row as a tuple, or None
fetchall()all remaining rows, a list of tuples
fetchmany(n)next n rows
cur.rowcountrows fetched or changed

commit() is on the connection (con.commit()), not the cursor; without it INSERT, UPDATE and DELETE are lost. One %s value still needs a tuple: (80,). Don't put quotes around %s.

Joins

  • Cartesian product: SELECT * FROM A, B; pairs every row of A with every row of B. 3 rows × 2 rows = 6 rows; degree = columns of A + columns of B.
  • Equi-join: join on equal values of a common column; name the table for that column.
SELECT Name, GName FROM PLAYER, GAMES
WHERE PLAYER.GCode = GAMES.GCode;

Natural join: like an equi-join, but the common column appears only once: SELECT * FROM PLAYER NATURAL JOIN GAMES;

Constraints

ConstraintRule
NOT NULLvalue must be given
UNIQUEno duplicates; NULL allowed; many per table
PRIMARY KEYunique and not NULL; one per table

Database concepts

A database is organised data; a DBMS is the software that manages it. Over a file system it removes redundancy (the same data stored many times) and inconsistency (copies that disagree). MySQL is an open-source RDBMS; SQL is the language it understands, and it is not case-sensitive for keywords.

What's the output?

On table S above. Cover the right column and answer; every result was run on MySQL.

QueryOutput
SELECT Name FROM S WHERE Name LIKE '%a';Riya, Sara
SELECT Name FROM S WHERE Name LIKE '_a%';Kabir, Sara
SELECT COUNT(*) FROM S WHERE Marks > 80;2
SELECT MAX(Marks) - MIN(Marks) FROM S;29
SELECT Class, MAX(Marks) FROM S GROUP BY Class;12A 91 · 12B 85
SELECT Name FROM S WHERE Marks BETWEEN 78 AND 85 ORDER BY Marks DESC;Sara, Riya
SELECT COUNT(*) FROM S WHERE Marks = NULL;0
SELECT DISTINCT Class FROM S;12A, 12B
SELECT UCASE(LEFT(Name,3)) FROM S WHERE Roll = 4;SAR
SELECT LENGTH(Name), INSTR(Name,'a') FROM S WHERE Roll = 3;5 · 2
SELECT ROUND(AVG(Marks)) FROM S;79

Find the error

WrongRight
WHERE COUNT(*) > 2HAVING COUNT(*) > 2
WHERE Marks = NULLWHERE Marks IS NULL
DELETE * FROM S;DELETE FROM S;
WHERE Name = RiyaWHERE Name = 'Riya'
... ORDER BY Marks WHERE Class='12A'WHERE before ORDER BY
... HAVING ... GROUP BY ClassGROUP BY before HAVING
WHERE Marks BETWEEN 70, 90BETWEEN 70 AND 90
UPDATE S Marks = 90 ...UPDATE S SET Marks = 90 ...
cur.commit()con.commit()
cur.execute(q, 80)cur.execute(q, (80,))

Expand it

SQL
Structured Query Language
DBMS
Database Management System
RDBMS
Relational DBMS
DDL · DML
Data Definition · Data Manipulation Language
DQL
Data Query Language