Skip to content
7 MIN LESSON · COMPUTER SCIENCE

Class 12 Relational Databases and SQL: Complete Concepts and Practice

Computer Science — Database concepts and the relational model (relation, attribute, tuple, domain, degree, cardinality), candidate, primary, alternate and foreign keys, and SQL in MySQL: DDL and DML commands, constraints, data types, operators, DISTINCT, WHERE, IN, BETWEEN, LIKE, IS NULL, ORDER BY, aggregate functions, GROUP BY with HAVING, and joining two tables (Cartesian product, equi-join, natural join), with every query result tested.

Big picture

A database stores related data in an organised way so it can be searched, updated and shared easily. A relational database stores data in tables (relations) that can be linked through common columns. SQL (Structured Query Language) is the language used to create these tables and query them.

The board paper always includes SQL queries on one or two given tables: write the query, or predict its output. Precision matters: a missing quote, the wrong use of WHERE instead of HAVING, or forgetting that aggregate functions ignore NULL can cost marks. Every query in this lesson was run to check its output.

Learning goals

  • Explain the need for databases and the advantages of a DBMS.

  • Define relational model terms and identify the degree and cardinality of a table.

  • Identify candidate, primary, alternate and foreign keys.

  • Use SQL DDL commands (CREATE, ALTER, DROP, DESCRIBE) and DML commands (INSERT, UPDATE, DELETE, SELECT).

  • Use constraints, operators, DISTINCT, aliases, WHERE, IN, BETWEEN, LIKE, IS NULL and ORDER BY.

  • Use aggregate functions, GROUP BY and HAVING.

  • Join two tables and predict the results.

Core ideas

1. Databases and DBMS

A file system stores data in separate files, which causes redundancy (the same data repeated), inconsistency (copies don't match), and difficulty in access and sharing. A database management system (DBMS), such as MySQL, manages a database and provides:

  • reduced redundancy and improved consistency;

  • data sharing among many users;

  • data security through access control;

  • data integrity through constraints;

  • easy querying and backup.

2. The relational model

Term

Meaning

Relation

A table

Attribute

A column (field)

Tuple

A row (record)

Domain

The set of allowed values for an attribute

Degree

Number of attributes (columns)

Cardinality

Number of tuples (rows)

Sample tables used in this lesson:

EMP

EmpID

Name

Dept

Salary

DeptNo

101

Asha

Sales

45000

1

102

Ravi

IT

62000

2

103

Neha

IT

58000

2

104

Arun

HR

38000

3

105

Meera

Sales

51000

1

106

Kabir

NULL

40000

NULL

DEPT

DeptNo

DName

City

1

Sales

Mumbai

2

IT

Pune

3

HR

Delhi

EMP has degree 5 and cardinality 6.

3. Keys

Key

Meaning

In EMP and DEPT

Candidate key

Any attribute (or set) that can uniquely identify each tuple

EmpID (and possibly a unique email column)

Primary key

The candidate key chosen to identify tuples; can't be NULL or repeated

EmpID in EMP; DeptNo in DEPT

Alternate key

A candidate key not chosen as primary key

e.g. an Aadhaar number column, if present

Foreign key

An attribute in one table that refers to the primary key of another table, linking them

DeptNo in EMP refers to DeptNo in DEPT

4. SQL data types and constraints

Data type

Use

CHAR(n)

Fixed-length string of n characters (padded with spaces)

VARCHAR(n)

Variable-length string up to n characters

INT

Integer

FLOAT

Number with a decimal part

DATE

Date in 'YYYY-MM-DD' format

Constraints: NOT NULL (value must be given), UNIQUE (no duplicates), PRIMARY KEY (NOT NULL + UNIQUE), DEFAULT (a value used when none is given), FOREIGN KEY (references another table).

5. DDL commands (Data Definition Language)

CREATE DATABASE company;
USE company;
SHOW TABLES;

CREATE TABLE EMP (
    EmpID   INT PRIMARY KEY,
    Name    VARCHAR(20) NOT NULL,
    Dept    VARCHAR(10),
    Salary  INT,
    DeptNo  INT
);

DESCRIBE EMP;                                   -- shows the table structure
ALTER TABLE EMP ADD Phone CHAR(10);             -- add a column
ALTER TABLE EMP DROP Phone;                     -- remove a column
ALTER TABLE EMP ADD PRIMARY KEY (EmpID);        -- add a primary key
ALTER TABLE EMP DROP PRIMARY KEY;               -- remove it
DROP TABLE EMP;                                 -- delete the table and its data

6. DML commands (Data Manipulation Language)

INSERT INTO EMP VALUES (107, 'Isha', 'HR', 41000, 3);
INSERT INTO EMP (EmpID, Name) VALUES (108, 'Dev');   -- other columns become NULL
UPDATE EMP SET Salary = Salary + 2000 WHERE Dept = 'HR';
DELETE FROM EMP WHERE EmpID = 108;

UPDATE or DELETE without a WHERE clause affects every row. DELETE removes rows but keeps the table; DROP TABLE removes the table itself.

7. SELECT queries

Feature

Example

Result on EMP

Specific columns

SELECT Name, Salary FROM EMP;

All names and salaries

DISTINCT

SELECT DISTINCT Dept FROM EMP;

Sales, IT, HR, NULL

Alias and expression

SELECT Name, Salary*12 AS Annual FROM EMP;

Annual salary column

BETWEEN (inclusive)

SELECT Name FROM EMP WHERE Salary BETWEEN 40000 AND 55000 ORDER BY Name;

Asha, Kabir, Meera

IN

SELECT Name FROM EMP WHERE Dept IN ('HR', 'IT') ORDER BY Salary DESC;

Ravi, Neha, Arun

LIKE with % (any number of characters)

SELECT Name FROM EMP WHERE Name LIKE 'A%';

Asha, Arun

LIKE with _ (exactly one character)

SELECT Name FROM EMP WHERE Name LIKE '_e%';

Neha, Meera (second letter e)

IS NULL

SELECT Name FROM EMP WHERE Dept IS NULL;

Kabir

ORDER BY

ORDER BY Salary DESC

Descending; ASC is the default

NULL means "no value". It can't be compared with =; use IS NULL or IS NOT NULL.

Operators: arithmetic (+ − * / %), relational (= < > <= >= <> or !=), logical (AND, OR, NOT).

8. Aggregate functions

Aggregate (multiple-row) functions return one value for a group of rows. They ignore NULL values, except COUNT(*).

Query

Result

SELECT COUNT(*), COUNT(Dept) FROM EMP;

6, 5 (Kabir's Dept is NULL)

SELECT MAX(Salary), MIN(Salary), SUM(Salary) FROM EMP;

62000, 38000, 294000

SELECT AVG(Salary) FROM EMP WHERE Dept = 'Sales';

48000

9. GROUP BY and HAVING

GROUP BY collects rows with the same value into groups, so aggregates are calculated per group. HAVING filters groups (using aggregate conditions), while WHERE filters rows before grouping.

SELECT Dept, AVG(Salary) FROM EMP
WHERE Dept IS NOT NULL
GROUP BY Dept;
-- HR 38000, IT 60000, Sales 48000

SELECT Dept, COUNT(*) FROM EMP
GROUP BY Dept
HAVING COUNT(*) > 1;
-- IT 2, Sales 2

Order of clauses: SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY ….

10. Joining two tables

Cartesian product: every row of one table is combined with every row of the other. SELECT * FROM EMP, DEPT; gives 6 × 3 = 18 rows; its degree is 5 + 3 = 8 columns.

Equi-join: a Cartesian product filtered by equality of the common column:

SELECT Name, City FROM EMP E, DEPT D
WHERE E.DeptNo = D.DeptNo AND City = 'Pune';
-- Ravi Pune, Neha Pune

(Table aliases E and D shorten the query. The common column appears twice in SELECT * of an equi-join.)

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

A reliable routine for SQL questions

  1. Identify the table(s) and columns needed.

  2. Write WHERE for row conditions, using quotes for text and IS NULL for nulls.

  3. For "per department" or "each city", use GROUP BY; filter groups with HAVING.

  4. For data from two tables, join on the common column.

  5. For output questions, apply WHERE, then GROUP BY, then HAVING, then ORDER BY, and remember NULL rules.

Connections that matter

  • Python–SQL connectivity runs these queries from Python programs.

  • Informatics Practices: advanced SQL covers the same SQL with more functions.

  • Computer networks: database servers are accessed over a network.

Common mistakes

  • Using `= NULL` instead of `IS NULL`.

  • Using `WHERE` with an aggregate condition (use HAVING).

  • Forgetting that `BETWEEN` includes both end values.

  • Mixing up `%` (any length) and `_` (exactly one character) in LIKE.

  • Mixing up degree and cardinality. Degree counts columns; cardinality counts rows.

  • Writing `DELETE` or `UPDATE` without WHERE when only some rows should change.

Revision checklist

  • I can explain DBMS advantages and the relational model terms.

  • I can identify all four types of keys.

  • I can write DDL and DML commands with constraints.

  • I can write SELECT queries with WHERE, IN, BETWEEN, LIKE, IS NULL, DISTINCT and ORDER BY.

  • I can use aggregate functions, GROUP BY and HAVING.

  • I can join two tables and predict the number of rows and columns.

Practise this topic →

Discussion

Sign in to join the discussion.

Sign in

No comments yet. Be the first to share your thoughts.