L
LLLOS.ai
LLOS.ai
L
Class 11 Informatics Practices Chapter 8 of 9

Chapter 8 — Structured Query Language

Overview

Introduction: This chapter introduces Structured Query Language (SQL), the standard language used to create, manage and query relational databases. Students learn how data is stored in tables and how SQL statements allow retrieval, filtering, modification and control of that data. Importance: SQL is a foundational skill for data handling, required in software development, data analysis and database administration. Understanding SQL helps students think logically about data, design simple database schemas, and perform meaningful data queries and updates. Key themes: Basic database concepts (tables, tuples, attributes, keys), categories of SQL commands (DDL, DML, DCL, TCL), table creation and modification, data manipulation (INSERT, UPDATE, DELETE), querying with SELECT (projections, selection, sorting), use of conditions and patterns (WHERE, LIKE), aggregate functions and grouping (COUNT, SUM, AVG, MIN, MAX, GROUP BY, HAVING), joins to combine tables, basic constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL), and simple views and set operations. What the student will learn: By the end of the chapter students will be able to design simple tables, write SQL statements to create…

Learning Objectives

  • Define Structured Query Language (SQL) and state its role in creating, querying and modifying relational databases.
  • Explain the categories of SQL commands (DDL, DML, DCL, TCL) and give one exam-level example of each.
  • Create and modify database tables using CREATE TABLE, ALTER TABLE and DROP TABLE statements with correct syntax.
  • Apply appropriate SQL data types and enforce column constraints such as PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL and CHECK while designing tables.
  • Insert, update and delete records using INSERT, UPDATE and DELETE statements and control transactions using COMMIT and ROLLBACK.
  • Write SELECT queries to retrieve data using WHERE, ORDER BY and DISTINCT clauses and limit results using appropriate syntax.
  • Use aggregate functions (COUNT, SUM, AVG, MIN, MAX) together with GROUP BY and HAVING to answer grouped-query problems.
  • Construct and execute JOIN operations (INNER JOIN, LEFT/RIGHT OUTER JOIN, FULL OUTER JOIN) to combine rows from multiple tables.

Topics in this chapter

20 topics · tap a topic title to jump straight to it.

💻1

Introduction to SQL

SQL (Structured Query Language) is a standard language used to communicate with relational database management systems (RDBMS). It allows users to create, read, update and delete (CRUD) data stored in tables. SQL is not case-sensitive for keywords but writing them in uppercase helps readability.

Key purposes of SQL:

  • Create and modify database structures (tables, indexes).
  • Insert, update and remove data.
  • Retrieve data using flexible queries and filters.
  • Control access and manage transactions.

Basic relational concepts:

  • Table: collection of rows (records) and columns (fields).
  • Row (tuple): a single record in a table.
  • Column: attribute with a data type (INT, VARCHAR, DATE, etc.).
  • Primary Key (PK): unique identifier for each row.
  • Foreign Key (FK): column that references a primary key in another table to maintain relationships.

Major SQL categories:

  • DDL (Data Definition Language): CREATE, ALTER, DROP (define structure).
  • DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE (manipulate data).
  • DCL (Data Control Language): GRANT, REVOKE (permissions).
  • TCL (Transaction Control Language): COMMIT, ROLLBACK (transactions).

Common SQL patterns:

-- Retrieve columns from a table
SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1 DESC;

-- Insert a new row
INSERT INTO table_name (col1, col2) VALUES (val1, val2);

-- Update rows
UPDATE table_name SET col1 = new_value WHERE condition;

-- Delete rows
DELETE FROM table_name WHERE condition;

Important query features:

  • Filtering: WHERE, logical operators (AND, OR, NOT).
  • Aggregation: COUNT(), SUM(), AVG(), MIN(), MAX() with GROUP BY and HAVING.
  • Sorting & limiting: ORDER BY, LIMIT (or TOP in some systems).
  • Join multiple tables: INNER JOIN, LEFT JOIN, RIGHT JOIN to combine related data.
  • Constraints: NOT NULL, UNIQUE, CHECK, DEFAULT to enforce data quality.
  • Indexing: improves query performance by creating indexes on columns used in searches.

Transactions (atomic operations): start a transaction to perform multiple related changes; COMMIT to save or ROLLBACK to undo on error. This ensures data integrity.

Example small schema (concept): Students and Courses

Students(student_id PK, name, class, dob)
Courses(course_id PK, title, credits)
Enrollments(enroll_id PK, student_id FK, course_id FK, grade)
This schema shows relationships (FKs) and typical operations: list students in a course, calculate average grade, add enrollment, etc.

Why learn SQL in Class 11 IP?

  • SQL is widely used in software, business analytics, web apps and scientific research.
  • It teaches structured thinking about data storage and retrieval.
  • Basic SQL skills are immediately useful for school projects and higher studies.
📌 Examples
  • School students scenario: Table Students(student_id, name, class, dob, city). Find all students of class 11 from 'Delhi': SELECT name, student_id FROM Students WHERE class = 11 AND city = 'Delhi';
  • Library management: Tables Books(book_id, title, author, copies) and Borrow(borrow_id, book_id, student_id, borrow_date). Find available copies of a book by title: SELECT copies FROM Books WHERE title = 'Introduction to Biology';
  • Employee payroll: Table Employee(emp_id, name, dept, salary). Increase salary by 10% for employees in 'Sales': UPDATE Employee SET salary = salary * 1.10 WHERE dept = 'Sales';
  • Joining tables: Given Students and Enrollments, get student names with their course IDs: SELECT s.name, e.course_id FROM Students s INNER JOIN Enrollments e ON s.student_id = e.student_id;
  • Aggregation: Calculate average marks in a class from Marks(student_id, subject, marks): SELECT AVG(marks) FROM Marks WHERE subject = 'Mathematics';
🧮 Formulas
  1. SELECT column_list FROM table_name WHERE condition ORDER BY column [ASC|DESC];
  2. SELECT col1, COUNT(*) FROM table GROUP BY col1 HAVING COUNT(*) > n; -- grouping and filtering aggregated results
  3. INSERT INTO table_name (col1, col2) VALUES (val1, val2);
  4. UPDATE table_name SET col = value WHERE condition; -- update specific rows
  5. DELETE FROM table_name WHERE condition; -- remove rows
  6. CREATE TABLE table_name (col1 datatype PRIMARY KEY, col2 datatype, ...);
📊 Visual ideas
Entity-Relationship diagram showing tables (Students, Courses, Enrollments) with primary key and foreign key links — helps visualise relationships.
Schema diagram (table boxes with columns) for a small database to show attributes and data types — useful before writing CREATE TABLE.
Flowchart of query execution: parse -> optimize -> execute -> return result — explains what happens when a SELECT runs.
Venn diagram for JOIN types: visualize INNER JOIN (intersection), LEFT JOIN (left + intersection), RIGHT JOIN (right + intersection).
💻2

Relational Terminology

Relational Terminology — overview

In the relational model a relation is a mathematically defined table. Understanding basic terminology is essential for designing, querying and enforcing integrity of relational databases.

  • Relation: A set of tuples organized in rows and columns; commonly called a table.
  • Tuple: A single row of a relation; an ordered set of attribute values that describes one entity or relationship instance.
  • Attribute: A column of a relation; each attribute has a name and a domain (set of permissible values).
  • Domain: The data type and allowable values for an attribute (for example, integer, varchar, date).
  • Degree: Number of attributes (columns) in a relation. If a table has n columns, degree = n.
  • Cardinality: Number of tuples (rows) in a relation; written as |R|.
  • Relation Schema: The definition of a relation: R(A1, A2, ..., An) where Ai are attributes.
  • Relation Instance / State: The actual set of tuples in a relation at a particular time.
  • Primary Key: An attribute or minimal set of attributes that uniquely identifies each tuple in a relation. Must be NOT NULL (entity integrity).
  • Candidate Key: A minimal superkey; any attribute set that can be chosen as primary key.
  • Superkey: Any superset of a key that uniquely identifies tuples.
  • Composite (Concatenated) Key: A key made of two or more attributes.
  • Foreign Key: An attribute (or set) in one relation whose values refer to primary key values in another relation; enforces referential integrity.
  • Null: A special marker meaning unknown, not applicable or missing value.

Integrity constraints

  • Entity integrity: Primary key attributes must not be null.
  • Referential integrity: Every non-null foreign key value must match an existing primary key value in the referenced relation.
  • Key constraint: Keys must be unique; no two distinct tuples share the same key value(s).

Functional dependency: A expresses that an attribute (or set) X functionally determines an attribute Y, written X -> Y. This underlies keys and normalization.

Why these terms matter: They let us design tables that avoid redundancy, support correct queries, and maintain data consistency through constraints.

📌 Examples
  • Student table: Relation STUDENT(StudentID, Name, DOB, Class). StudentID is primary key (unique, not null). Degree = 4. Cardinality = number of students enrolled.
  • Employee and Department: EMP(EmployeeID, Name, DeptID). DEPT(DeptID, DeptName). DeptID in EMP is a foreign key referencing DEPT.DeptID — enforces that every employee's department exists.
  • Many-to-many example: STUDENT and COURSE with ENROLLMENT(StudentID, CourseID, Grade). ENROLLMENT has a composite primary key (StudentID, CourseID).
  • Library system: BOOK(ISBN, Title, Author) where ISBN is primary key. LOAN(LoanID, ISBN, MemberID, LoanDate). LOAN.ISBN is a foreign key to BOOK.ISBN.
  • Hospital: PATIENT(PatientID, Name), DOCTOR(DoctorID, Name), APPOINTMENT(AppointID, PatientID, DoctorID, Date). PatientID and DoctorID in APPOINTMENT are foreign keys.
🧮 Formulas
  1. Relation schema notation: R(A1, A2, ..., An)
  2. Degree of relation R: degree(R) = n (number of attributes)
  3. Cardinality of relation R: |R| = number of tuples (rows)
  4. Tuple access: t[Ai] = value of attribute Ai in tuple t
  5. Primary key uniqueness: for any two tuples t1 and t2 in R, if t1.pk = t2.pk then t1 = t2
  6. Referential integrity: for relation R with foreign key FK referencing S.PK, for every tuple t in R, either t.FK is NULL or exists s in S such that s.PK = t.FK
📊 Visual ideas
Simple table diagram: a rectangular box with column names listed, mark primary key with 'PK' and foreign key with 'FK'. Use one box per relation to show relation schema and attributes.
Relationship link: two table boxes (e.g., EMP and DEPT) connected by a line from EMP.DeptID (FK) to DEPT.DeptID (PK); annotate cardinality (1-to-many) near the line.
Composite key visual: show a table with two columns highlighted together as the composite primary key (for ENROLLMENT: StudentID + CourseID).
ER-like mapping: small entity boxes for STUDENT and COURSE and a diamond labeled ENROLLS connecting them; show attributes and keys for each entity.
💻3

Categories of SQL Commands

Overview: SQL (Structured Query Language) commands are grouped by purpose. The main categories taught in Class 11 Informatics Practices are:

  • DDL (Data Definition Language): Commands that define or modify database schema (tables, indexes, constraints). Examples: CREATE, ALTER, DROP, TRUNCATE, RENAME.
  • DML (Data Manipulation Language): Commands that change the data stored in tables. Examples: INSERT, UPDATE, DELETE, MERGE.
  • DQL (Data Query Language): Commands used to retrieve data. Primarily the SELECT statement (with clauses such as WHERE, GROUP BY, HAVING, ORDER BY).
  • TCL (Transaction Control Language): Commands that control transactions to ensure data integrity. Examples: COMMIT, ROLLBACK, SAVEPOINT.
  • DCL (Data Control Language): Commands that manage permissions and access. Examples: GRANT, REVOKE.

Why categories matter: Grouping helps understand what will change (schema vs data vs access vs transactions) and prevents accidental changes. For example, DDL changes structure and is often run by DBAs; DML changes row data and usually needs transaction control (TCL) to make operations safe.

Common patterns: CRUD maps to SQL categories: Create → DDL/INSERT, Read → SELECT (DQL), Update → UPDATE (DML), Delete → DELETE (DML). Also, constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, DEFAULT) are defined by DDL.

📌 Examples
  • DDL: CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(50), Class VARCHAR(10), DOB DATE);
  • DDL (alter): ALTER TABLE Students ADD COLUMN Email VARCHAR(100);
  • DML: INSERT INTO Students (StudentID, Name, Class, DOB) VALUES (101, 'Riya Sharma', '11A', '2009-05-12');
  • DML: UPDATE Students SET Email = 'riya@example.com' WHERE StudentID = 101;
  • DML: DELETE FROM Students WHERE StudentID = 105;
  • DQL: SELECT Name, Class FROM Students WHERE Class = '11A' ORDER BY Name;
🧮 Formulas
  1. CREATE TABLE syntax: CREATE TABLE table_name (column1 datatype [constraints], column2 datatype [constraints], ...);
  2. INSERT syntax: INSERT INTO table_name (col1, col2, ...) VALUES (val1, val2, ...);
  3. UPDATE syntax: UPDATE table_name SET col1 = value1, col2 = value2 WHERE condition;
  4. DELETE syntax: DELETE FROM table_name WHERE condition;
  5. SELECT basic: SELECT column_list FROM table_name [WHERE condition] [GROUP BY cols] [HAVING condition] [ORDER BY cols];
  6. JOIN pattern: SELECT a.col, b.col FROM A a INNER JOIN B b ON a.key = b.key; (also LEFT/ RIGHT/ FULL JOIN)
📊 Visual ideas
Classification flowchart: a simple tree with 'SQL Commands' at top branching to DDL, DML, DQL, TCL, DCL. Each leaf lists 2–4 example statements (use colored boxes for each category).
Transaction sequence diagram: show steps Begin Transaction -> multiple DML statements -> COMMIT (success) or ROLLBACK (on error). Annotate with a real-life example like transferring money between accounts.
CRUD mapping diagram: four boxes (Create, Read, Update, Delete) mapped to SQL commands (CREATE/INSERT, SELECT, UPDATE, DELETE) and example use-cases (add student, view marks, change address, remove alumni).
ER / Schema change visual: show a simple ER diagram (Students, Courses, Enrollment) and illustrate a DDL action (adding a column or dropping a table) with before/after snapshots.
📊4

Data Types in SQL

Data types in SQL define the kind of data that can be stored in a column of a table. Choosing the correct data type is essential for correctness, storage efficiency, query performance and data validation. SQL data types are grouped by purpose: numeric, character (string), date/time, boolean, binary, and large objects (LOBs).

  • Numeric types: used for integers and decimals.
    • INT, SMALLINT, BIGINT — integer values with different ranges.
    • DECIMAL(p, s) / NUMERIC(p, s) — fixed precision and scale for exact decimal storage (money, marks).
    • FLOAT, REAL — approximate floating-point numbers (scientific calculations).
  • Character (string) types:
    • CHAR(n) — fixed-length string, padded with spaces if shorter.
    • VARCHAR(n) — variable-length string up to n characters (most commonly used for names, addresses).
    • Some DBs provide TEXT or VARCHAR(MAX) / CLOB for very large text.
  • Date and time types:
    • DATE — calendar date (YYYY-MM-DD).
    • TIME — time of day (HH:MM:SS).
    • TIMESTAMP / DATETIME — date + time, often with timezone options.
  • Boolean: BOOLEAN (or BIT/tinyint in some DBs) for true/false values.
  • Binary and large objects:
    • BINARY, VARBINARY — store raw bytes (files, images).
    • BLOB / CLOB — large binary or character objects for multimedia or long text.
  • Special types: ENUM, SET (MySQL), UUID, JSON types in modern DBs to store structured documents.

Key points and best practices:

  • Use the smallest type that fits the data to save space and improve performance (e.g., SMALLINT instead of INT if values are small).
  • For money or precise decimals, prefer DECIMAL(p,s) over FLOAT to avoid rounding errors.
  • Use CHAR for fixed-length codes (like country codes), VARCHAR for variable-length text (names, emails).
  • Declare NOT NULL when a value is required and use DEFAULT for sensible defaults.
  • Consider indexing and how the type affects index size and search speed.

Example short syntax (illustrative):

CREATE TABLE Students (
  student_id INT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  dob DATE,
  percentage DECIMAL(5,2),
  is_pass BOOLEAN
);

This creates columns appropriate for each kind of data: integer id, variable-length name, a date of birth, a decimal for percentage with 2 digits after the decimal, and a boolean pass/fail flag.

📌 Examples
  • CREATE TABLE Students ( student_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, dob DATE, total_marks DECIMAL(5,2), email VARCHAR(100) );
  • INSERT INTO Students (name, dob, total_marks, email) VALUES ('Anita Sharma', '2006-08-12', 478.50, 'anita.sharma@example.com');
  • CREATE TABLE Products (product_id INT, sku CHAR(8), price DECIMAL(10,2), description TEXT, image BLOB);
  • SELECT * FROM Orders WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01';
🧮 Formulas
  1. Integer ranges (typical): SMALLINT ≈ -2^15..2^15-1, INT ≈ -2^31..2^31-1, BIGINT ≈ -2^63..2^63-1.
  2. DECIMAL(p, s): total digits = p; digits to right of decimal = s; digits to left = p - s. Example DECIMAL(7,2) stores values from -99999.99 to 99999.99.
  3. Storage rules (typical/approximate): CHAR(n) uses n bytes (fixed). VARCHAR(n) uses actual length + 1 or +2 bytes of overhead (varies by DB). FLOAT/REAL storage and precision depend on implementation.
  4. Choose precision so p is the total significant digits you need; set s to required fractional digits (money → DECIMAL(10,2) is common).
📊 Visual ideas
Bar chart comparing typical storage sizes: SMALLINT vs INT vs BIGINT vs DECIMAL(10,2) vs VARCHAR(50) — show bytes on Y axis and data types on X axis.
Stacked bar showing distribution of column types in a sample table (e.g., 30% numeric, 40% varchar, 20% date/time, 10% blobs) to visualize schema composition.
Flowchart for selecting a data type: start → is value numeric? → integer or decimal? → choose INT/SMALLINT/BIGINT or DECIMAL(p,s) → consider range/precision → DONE.
Timeline / axis chart showing DATE vs TIME vs TIMESTAMP: illustrate how TIMESTAMP includes both date and time and can include timezone information.
🧪5

Creating and Modifying Database Objects

Overview: Creating and modifying database objects is about defining the structure that stores data (databases, tables, indexes, views) and changing that structure safely as requirements evolve. SQL commands covered: CREATE, ALTER, DROP, TRUNCATE, RENAME and commands to create indexes and views.

Creating a database: Use CREATE DATABASE db_name; then switch with USE db_name;. A database is a container for tables and other objects.

Creating tables: CREATE TABLE defines columns, data types and constraints. Each column has a name and a data type (e.g., INT, VARCHAR(n), DATE, FLOAT). Constraints enforce rules: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.

Common constraints and effects:

  • PRIMARY KEY: Uniquely identifies rows; cannot be NULL. Enforced as UNIQUE + NOT NULL.
  • FOREIGN KEY: Enforces referential integrity between parent and child tables. Options: ON DELETE CASCADE / SET NULL, ON UPDATE CASCADE, etc.
  • UNIQUE: Ensures column values are unique.
  • NOT NULL: Column must have a value.
  • CHECK: Validates a condition (e.g., CHECK(age >= 0)).
  • DEFAULT: Supplies a default value when none provided.

Modifying tables: ALTER TABLE is used to add, modify, rename or drop columns and constraints. ALTER can also add/drop PRIMARY KEY or FOREIGN KEY constraints. Examples of operations: ADD COLUMN, DROP COLUMN, MODIFY (or ALTER COLUMN depending on DBMS), RENAME TO.

Removing objects: DROP TABLE deletes the table and its data and metadata. TRUNCATE TABLE removes all rows but typically keeps the table structure and is faster (can be non-transactional in some DBMS). DROP DATABASE deletes the entire database.

Indexes and views:

  • CREATE INDEX creates a data structure (often a B-tree) to speed up queries on specified columns. DROP INDEX removes it.
  • CREATE VIEW creates a named query result (virtual table) that can simplify complex queries and provide a level of abstraction/security. Views do not store data (unless materialized).

Rules & best practices:

  • Always define a PRIMARY KEY for tables to uniquely identify rows.
  • Use appropriate data types (e.g., use INT for integers, not VARCHAR).
  • Apply constraints to enforce data integrity rather than relying on application code.
  • When altering live production schemas, plan migrations, back up data, and consider downtime or transactional migrations.
  • Use indexes selectively: they speed reads but slow writes and use space.

Referential integrity and cascading: FOREIGN KEY constraint ensures that a child table row refers to an existing parent row. ON DELETE CASCADE removes child rows automatically when parent is deleted. ON DELETE SET NULL sets the foreign key in child to NULL. Use cascading carefully to avoid accidental data loss.

Example workflow (typical): CREATE DATABASE > USE db > CREATE TABLE(s) with constraints > LOAD or INSERT data > CREATE INDEX for common queries > ALTER TABLE when schema changes are required > DROP/TRUNCATE when removing objects.

📌 Examples
  • Create a database and a table (students): CREATE DATABASE school; USE school; CREATE TABLE students ( roll_no INT PRIMARY KEY, name VARCHAR(50) NOT NULL, dob DATE, class INT DEFAULT 11, avg_marks FLOAT CHECK (avg_marks >= 0 AND avg_marks <= 100) );
  • Add a new column and set NOT NULL: ALTER TABLE students ADD COLUMN email VARCHAR(100); -- later make it NOT NULL after filling values ALTER TABLE students MODIFY COLUMN email VARCHAR(100) NOT NULL;
  • Add a foreign key (library example): CREATE TABLE books ( book_id INT PRIMARY KEY, title VARCHAR(100) ); CREATE TABLE issued ( issue_id INT PRIMARY KEY, roll_no INT, book_id INT, issue_date DATE, FOREIGN KEY (roll_no) REFERENCES students(roll_no) ON DELETE CASCADE, FOREIGN KEY (book_id) REFERENCES books(book_id) );
  • Create an index to speed search by name: CREATE INDEX idx_students_name ON students(name); -- Drop index DROP INDEX idx_students_name ON students;
  • Create a view to get student basic info: CREATE VIEW student_info AS SELECT roll_no, name, class FROM students; -- Use: SELECT * FROM student_info;
  • Remove objects: TRUNCATE TABLE issued; -- removes all rows quickly DROP TABLE issued; -- deletes table definition and data DROP DATABASE school; -- deletes entire database
🧮 Formulas
  1. CREATE DATABASE database_name;
  2. USE database_name;
  3. CREATE TABLE table_name ( column1 datatype [constraint], column2 datatype [constraint], ... );
  4. ALTER TABLE table_name ADD COLUMN column_name datatype [constraint];
  5. ALTER TABLE table_name DROP COLUMN column_name;
  6. ALTER TABLE table_name MODIFY COLUMN column_name new_datatype [constraint];
📊 Visual ideas
ER diagram: Entities (students, books, issued) with primary keys and foreign key relationships (students.roll_no -> issued.roll_no, books.book_id -> issued.book_id).
Schema diagram (table structure): A box for each table listing columns, data types and constraints (highlight primary keys in one color, foreign keys in another).
Before/After schema change: show table layout before ALTER (columns A, B) and after ALTER ADD/ MODIFT/ DROP (columns A, B, C) to visualize migration.
Index visualization: sketch of a B-tree structure for an index on the 'name' column, illustrating faster lookup vs full table scan.
💻6

Keys and Constraints

Overview: In relational databases (SQL), keys and constraints ensure correct, unique and meaningful data. Keys identify tuples (rows) uniquely; constraints enforce rules (e.g., no nulls, valid references, value limits). Together they maintain data integrity.

Types of Keys

  • Superkey: Any set of attributes that uniquely identifies a row. May contain extra attributes (redundant).
  • Candidate key: A minimal superkey (no subset of it is a superkey). There can be multiple candidate keys.
  • Primary key: One chosen candidate key to uniquely identify rows in a table. Cannot be NULL (entity integrity).
  • Alternate key: Candidate keys that are not chosen as primary key.
  • Composite (or Concatenated) key: A key made of two or more attributes together uniquely identifying a row.
  • Foreign key: An attribute (or set) in one table whose values refer to primary key values in another table; enforces referential integrity.

Types of Constraints

  • NOT NULL: Column cannot have NULL values.
  • UNIQUE: Values in the column (or group) must be distinct across rows.
  • PRIMARY KEY: Combination of NOT NULL + UNIQUE; declares the primary identifier for the table.
  • FOREIGN KEY: Enforces that values match existing values in referenced table; optionally specifies actions on update/delete (CASCADE, SET NULL, NO ACTION).
  • CHECK: Ensures column values satisfy a boolean condition (e.g., age >= 0).
  • DEFAULT: Provides a default value when INSERT omits the column.

Integrity Rules

  • Domain constraint: Each column must store values from a defined domain (type, format).
  • Entity integrity: Primary key must not be NULL.
  • Referential integrity: Foreign key values must match existing primary key values (or be NULL if allowed).

SQL examples (creation and alteration)

CREATE TABLE Student (
  roll_no INT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(100) UNIQUE,
  dob DATE,
  admission_date DATE DEFAULT CURRENT_DATE
);

CREATE TABLE Course (
  course_id INT PRIMARY KEY,
  title VARCHAR(100) NOT NULL
);

CREATE TABLE Enrollment (
  student_roll INT,
  course_id INT,
  semester VARCHAR(10),
  PRIMARY KEY (student_roll, course_id), -- composite primary key
  FOREIGN KEY (student_roll) REFERENCES Student(roll_no) ON DELETE CASCADE,
  FOREIGN KEY (course_id) REFERENCES Course(course_id) ON DELETE NO ACTION
);

-- Adding a constraint later
ALTER TABLE Student ADD CONSTRAINT chk_email CHECK (email LIKE '%_@_%_.%');

How constraints affect operations

  • INSERT/UPDATE violating NOT NULL, UNIQUE, PRIMARY KEY or CHECK will fail.
  • Deleting a row referenced by a foreign key will fail unless ON DELETE CASCADE or ON DELETE SET NULL is used.
  • Using constraints improves data quality and enables reliable joins between tables.
📌 Examples
  • Student-College system: Student table uses roll_no as PRIMARY KEY (unique identifier). Email column has UNIQUE to avoid duplicate registrations, and dob has CHECK (dob <= CURRENT_DATE).
  • Library: Book(book_id PRIMARY KEY, isbn UNIQUE, title NOT NULL). Borrow(book_id, member_id, borrow_date) has FOREIGN KEY(book_id) REFERENCES Book(book_id) and FOREIGN KEY(member_id) REFERENCES Member(member_id) with ON DELETE CASCADE to remove borrow records when a member is deleted.
  • Bank account: Account(acc_no PRIMARY KEY, balance DECIMAL CHECK (balance >= 0), created_on DATE DEFAULT CURRENT_DATE) — prevents negative balances and auto-sets opening date.
  • Course enrollment (composite key): Enrollment(student_id, course_id, semester) with PRIMARY KEY (student_id, course_id, semester) ensures a student cannot register for same course and semester twice.
  • Email verification constraint: ALTER TABLE Users ADD CONSTRAINT chk_email_format CHECK (email LIKE '%_@_%_.%'); — rejects badly formed email addresses.
🧮 Formulas
  1. Definitions (set relations): Superkey ⊇ Candidate keys; Candidate keys contain minimal attribute sets; Primary key ∈ Candidate keys (one chosen).
  2. Primary key syntax: CREATE TABLE T (col1 TYPE, col2 TYPE, PRIMARY KEY (col1));
  3. Composite primary key: PRIMARY KEY (colA, colB)
  4. Foreign key syntax: FOREIGN KEY (fk_col) REFERENCES ParentTable(parent_col) [ON DELETE {CASCADE | SET NULL | NO ACTION | RESTRICT}] [ON UPDATE ...];
  5. NOT NULL and UNIQUE usage: col TYPE NOT NULL UNIQUE
  6. CHECK constraint: col TYPE CHECK (condition) — e.g., CHECK (age >= 0 AND age <= 150)
📊 Visual ideas
ER diagram: Student (roll_no PK, name, email) linked to Enrollment (student_roll FK, course_id FK, semester) linked to Course (course_id PK). Show PK fields underlined and FK arrows pointing to referenced PKs.
Relational schema diagram: Boxes for tables with columns listed; mark PRIMARY KEY (PK) and FOREIGN KEY (FK) with arrows. Example: Student.roll_no (PK) ← Enrollment.student_roll (FK).
Venn diagram or set diagram: illustrate Superkeys (largest set), Candidate keys (minimal superkeys inside), and chosen Primary Key highlighted.
Sequence diagram for cascading action: Show steps when a parent row is deleted — with ON DELETE CASCADE display child rows automatically removed; with NO ACTION show deletion blocked.
💻7

INSERT, UPDATE and DELETE

Overview

INSERT, UPDATE and DELETE are the three basic Data Manipulation Language (DML) SQL commands used to add, modify and remove rows in database tables. They operate on table data while keeping the table structure unchanged. Use WHERE clauses to limit UPDATE and DELETE to specific rows; without WHERE they affect all rows.

INSERT

INSERT adds new rows into a table. You can insert one row at a time or multiple rows. You may specify column names (recommended) or rely on the default column order. Constraints (PRIMARY KEY, UNIQUE, NOT NULL, FOREIGN KEY) apply when inserting.

<!-- Syntax -->
INSERT INTO table_name (col1, col2, ...) VALUES (val1, val2, ...);
<!-- Multiple rows -->
INSERT INTO table_name (col1, col2) VALUES (v1a, v2a), (v1b, v2b);
<!-- Insert from another table -->
INSERT INTO table_name (col1, col2) SELECT colA, colB FROM other_table WHERE ...;

UPDATE

UPDATE changes values of existing rows. Always use a WHERE clause to target specific rows; otherwise all rows in the table will be updated. You can update one or more columns at once. You can also use expressions, subqueries or joins (DBMS-specific features may vary).

<!-- Syntax -->
UPDATE table_name
SET col1 = expression1, col2 = expression2, ...
WHERE condition;

DELETE

DELETE removes rows from a table. With a WHERE clause it deletes only matching rows; without WHERE it deletes all rows but leaves the table structure intact. (To remove the table itself use DROP TABLE; to quickly empty a table some DBMS provide TRUNCATE TABLE.)

<!-- Syntax -->
DELETE FROM table_name WHERE condition;
<!-- Delete all rows -->
DELETE FROM table_name;  -- removes all rows

Important Points & Best Practices

  • Always back up important data before running mass UPDATE/DELETE.
  • Use transactions (BEGIN/COMMIT/ROLLBACK) when performing multiple related DML operations so changes can be undone if something goes wrong.
  • Use WHERE to avoid accidental full-table updates/deletes.
  • Prefer specifying column names in INSERT for clarity and safety when table structure changes.
  • Watch constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL) — INSERT/UPDATE may fail if constraints are violated.
  • Many DBMS offer RETURNING (or OUTPUT) clauses to return changed rows (e.g., INSERT ... RETURNING * in PostgreSQL).

Example walkthrough (Student table)

-- Table: Student(rollno INT PRIMARY KEY, name VARCHAR(50), marks INT)

-- 1) Insert a new student
INSERT INTO Student (rollno, name, marks) VALUES (101, 'Asha', 85);

-- 2) Update marks for rollno 101
UPDATE Student SET marks = 90 WHERE rollno = 101;

-- 3) Delete a student record
DELETE FROM Student WHERE rollno = 101;
📌 Examples
  • Insert single row: INSERT INTO Employee (emp_id, name, dept, salary) VALUES (1, 'Ravi', 'Sales', 30000); -- adds one employee
  • Insert multiple rows: INSERT INTO Inventory (item_id, name, qty) VALUES (101, 'Pen', 50), (102, 'Book', 30); -- adds two items
  • Insert from another table: INSERT INTO ArchiveOrders (order_id, cust_id, total) SELECT order_id, cust_id, total FROM Orders WHERE order_date < '2023-01-01';
  • Update specific rows: UPDATE Student SET marks = marks + 5 WHERE class = '11' AND subject = 'Math'; -- give grace marks
  • Update all rows (use with caution): UPDATE Products SET price = price * 1.10; -- increase price by 10% for all products
  • Delete specific rows: DELETE FROM Users WHERE last_login &lt; '2020-01-01'; -- remove inactive users
🧮 Formulas
  1. INSERT INTO table_name (col1, col2, ...) VALUES (val1, val2, ...);
  2. INSERT INTO table_name (col1, col2) SELECT colA, colB FROM other_table WHERE ...;
  3. UPDATE table_name SET col1 = expr1, col2 = expr2 WHERE condition;
  4. DELETE FROM table_name WHERE condition;
  5. DELETE FROM table_name; -- deletes all rows
  6. Transaction pattern: BEGIN; UPDATE ...; DELETE ...; INSERT ...; COMMIT; -- or ROLLBACK to undo
📊 Visual ideas
Before-and-after table diagram: show a table of rows (grid) with highlighted rows to be INSERTed/UPDATEd/DELETEd and then a second grid showing the table after the operation. Use color coding: green for inserted, yellow for updated, red with strikethrough for deleted.
Flowchart of an UPDATE/Delete operation: Start → Evaluate WHERE condition for each row → If TRUE apply change/delete → If FALSE skip → Commit/Rollback. This helps visualize row-by-row processing.
Bar chart showing row counts over time: x-axis = time (days), y-axis = number of rows; mark points where bulk INSERT/DELETE operations occurred to show their effect.
Sequence diagram for a transaction: Client → DB (BEGIN) → DB (execute INSERT/UPDATE/DELETE) → Client (COMMIT or ROLLBACK). Useful to explain atomicity and rollback.
💻8

SELECT Statement and Basic Clauses

Overview
The SELECT statement is the fundamental SQL command used to retrieve data from one or more tables. A SELECT query can pick specific columns, filter rows, sort results, remove duplicates, and compute aggregates.

Basic syntax

SELECT [DISTINCT] column1, column2, ...
FROM table_name
[WHERE condition]
[GROUP BY column_list]
[HAVING aggregate_condition]
[ORDER BY column_list [ASC|DESC]]
[LIMIT n];

Clause explanations

  • SELECT — lists columns or expressions you want returned. Use * to select all columns. You can use column aliases: SELECT name AS student_name.
  • DISTINCT — removes duplicate rows from the result for the selected columns: SELECT DISTINCT city FROM Students.
  • FROM — specifies the table(s) to read data from.
  • WHERE — filters rows using conditions (comparison operators, logical operators, BETWEEN, IN, LIKE, IS NULL). WHERE applies before grouping and aggregation.
  • GROUP BY — groups rows that have the same values in listed column(s). Used with aggregate functions (COUNT, SUM, AVG, MIN, MAX) to summarize data per group.
  • HAVING — filters groups created by GROUP BY based on aggregate conditions (e.g., groups having SUM(sales) > 10000). HAVING is like WHERE but for groups.
  • ORDER BY — sorts the result set by one or more columns or expressions; default is ASC (ascending). Use DESC for descending order.
  • LIMIT / FETCH — (DBMS-specific) restricts the number of rows returned, useful for pagination or previewing results.

Execution (conceptual) order
Although written in the order above, SQL is conceptually processed in this order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT. Understanding this helps write correct queries.

Common aggregate functions: COUNT(column_or_*), SUM(numeric_column), AVG(numeric_column), MIN(column), MAX(column). Aggregates often used with GROUP BY.

Examples explained
1) Filter: SELECT name, marks FROM Students WHERE marks >= 75; — returns names and marks of students who scored 75 or more.
2) Distinct: SELECT DISTINCT city FROM Students; — lists each city represented, once.
3) Group & aggregate: SELECT class, AVG(marks) AS avg_mark FROM Students GROUP BY class; — average marks per class.
4) Having: SELECT class, COUNT(*) AS num_students FROM Students GROUP BY class HAVING COUNT(*) > 30; — classes with more than 30 students.
5) Order & limit: SELECT name, marks FROM Students ORDER BY marks DESC LIMIT 5; — top 5 students by marks.

Tips:

  • Columns in SELECT that are not aggregated must appear in GROUP BY (SQL standard rule).
  • Use parentheses with complex logical conditions in WHERE for clarity: WHERE (city = 'Delhi' OR city = 'Mumbai') AND marks >= 60.
  • Use indexes on columns used in WHERE/ORDER BY to improve performance.

📌 Examples
  • 1) Simple selection: SELECT name, roll_no, class FROM Students;
  • 2) Filter using WHERE: SELECT name, marks FROM Students WHERE marks >= 75 AND class = 'XI';
  • 3) Remove duplicates: SELECT DISTINCT subject FROM Timetable;
  • 4) Sort results: SELECT product_name, price FROM Products WHERE category = 'Stationery' ORDER BY price ASC;
  • 5) Grouping and aggregate: SELECT class, AVG(marks) AS average_marks FROM Students GROUP BY class;
  • 6) HAVING to filter groups: SELECT teacher, COUNT(*) AS classes_taken FROM Classes GROUP BY teacher HAVING COUNT(*) >= 3;
🧮 Formulas
  1. SELECT [DISTINCT] column1, column2 FROM table_name;
  2. Filtering: WHERE column operator value (operators: =, <>, >, <, >=, <=)
  3. Logical: WHERE condition1 AND|OR condition2; Use NOT to negate conditions
  4. Pattern match: WHERE column LIKE 'pattern' (e.g., 'A%', '%son', '_a%')
  5. Set membership: WHERE column IN (value1, value2, ...)
  6. Range: WHERE column BETWEEN value1 AND value2
📊 Visual ideas
Execution order flowchart: boxes showing FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT to explain how SQL processes a query.
Bar chart: Average marks per class (x-axis: class, y-axis: average_marks) produced from GROUP BY + AVG example.
Pie chart: Distribution of students by city using SELECT city, COUNT(*) FROM Students GROUP BY city to show proportions.
Sorted bar chart: Top 5 products by sales using ORDER BY sales DESC LIMIT 5 to visualize highest-selling items.
💻9

Filtering and Conditional Operators

What is filtering? In SQL, filtering means selecting only those rows from a table that satisfy one or more conditions. Filtering is done with the WHERE clause in a SELECT, UPDATE, or DELETE statement.

Basic structure:

SELECT column_list
FROM table_name
WHERE condition;

Comparison operators are used to form simple conditions:

  • = equal to
  • <> or != not equal to
  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to

Logical (conditional) operators combine conditions:

  • AND — both conditions must be true
  • OR — at least one condition must be true
  • NOT — negates a condition

Other useful filtering operators:

  • BETWEEN low AND high — range inclusive (e.g., age BETWEEN 10 AND 15)
  • IN (value1, value2, ...) — matches any value in a list
  • LIKE 'pattern' — pattern matching with wildcards: % (any sequence), _ (single character)
  • IS NULL / IS NOT NULL — test for NULL values

Precedence: NOT is evaluated before AND, which is evaluated before OR. Use parentheses to make evaluation order explicit.

Important note about NULL: Comparisons with NULL (e.g., column = NULL) do not return true. Use IS NULL or IS NOT NULL.

Example queries:

-- Simple filter
SELECT name, marks FROM Students
WHERE marks >= 75;

-- Combined conditions
SELECT * FROM Employees
WHERE department = 'Sales' AND salary > 30000;

-- Range and list
SELECT product_name FROM Products
WHERE price BETWEEN 100 AND 500
  AND category IN ('Electronics', 'Home');

-- Pattern matching
SELECT name FROM Customers
WHERE name LIKE 'A%';

How filtering works in real life: Imagine a school register (table) — you can filter to find students who scored above 80, who are in Grade 11, or whose names start with 'S'. Filtering returns only the rows that match your criteria.

Tips for writing filters:

  • Prefer parentheses for clarity if combining AND/OR.
  • Be careful with NULLs — always use IS NULL rather than equality checks.
  • Use LIKE for simple pattern matches; full-text search or regex may be needed for complex patterns.
📌 Examples
  • Students scoring at least 60: SELECT roll_no, name FROM Students WHERE marks >= 60;
  • Employees in HR or Finance: SELECT emp_id, name FROM Employees WHERE department IN ('HR', 'Finance');
  • Products priced between 200 and 1000: SELECT product_id, product_name FROM Products WHERE price BETWEEN 200 AND 1000;
  • Customers whose names start with 'S': SELECT customer_id, name FROM Customers WHERE name LIKE 'S%';
  • Find records with missing phone numbers: SELECT name, email FROM Contacts WHERE phone IS NULL;
  • Complex condition with precedence: SELECT * FROM Orders WHERE status = 'Delivered' AND (amount &gt; 500 OR priority = 'High');
🧮 Formulas
  1. Basic WHERE: SELECT columns FROM table WHERE condition
  2. Comparison: WHERE column operator value -- operator ∈ {=, !=, <>, <, <=, >, >=}
  3. Range: WHERE column BETWEEN low AND high
  4. List: WHERE column IN (value1, value2, ...)
  5. Pattern: WHERE column LIKE 'pattern' -- use % for any sequence, _ for single character
  6. NULL test: WHERE column IS NULL or WHERE column IS NOT NULL
📊 Visual ideas
Venn diagram showing sets for conditions A AND B (intersection), A OR B (union), and NOT A (complement). Useful to visualize AND/OR/NOT behavior.
Flowchart of WHERE evaluation: start -> apply first condition -> branch (true/false) -> if combined with AND evaluate next -> final decision to include/exclude row. Include parentheses handling as subflow.
Table-before-and-after visualization: show a full table of sample records (e.g., Students with marks) and a filtered result table highlighting only rows that meet the WHERE clause.
Pattern matching illustration: a string-axis showing where patterns like 'A%', '%man', and '_a%' match example names. Show % as wildcards spanning characters and _ as single-character placeholders.
💻10

Aggregate Functions and Grouping

Aggregate functions compute a single value from a set of rows. Common aggregate functions in SQL are COUNT(), SUM(), AVG(), MIN() and MAX(). They are used to get totals, averages, extremes and counts.

GROUP BY groups rows that have the same values in specified columns into summary rows so that aggregate functions can be applied per group. HAVING filters groups after aggregation (unlike WHERE, which filters rows before grouping).

Key behavior notes:

  • Use non-aggregated columns in the SELECT clause only if they appear in GROUP BY.
  • COUNT(column) ignores NULLs; COUNT(*) counts rows including NULL values in other columns.
  • You can use DISTINCT inside aggregates (e.g., COUNT(DISTINCT col)) to count unique values.
  • HAVING is used to restrict groups (e.g., groups with SUM > 1000).

Typical pattern:

SELECT grouping_columns, AGG(column)
FROM table
WHERE row_conditions
GROUP BY grouping_columns
HAVING group_conditions
ORDER BY something;

Examples of use in real life: monthly sales totals, average marks per class, number of customers per city, maximum salary per department.

📌 Examples
  • 1) Count total rows: SELECT COUNT(*) FROM students; -- returns total number of students
  • 2) Count distinct values: SELECT COUNT(DISTINCT city) AS city_count FROM customers; -- number of different cities
  • 3) Sum and group: SELECT city, SUM(sales) AS total_sales FROM orders GROUP BY city; -- total sales per city
  • 4) Average with WHERE: SELECT subject, AVG(marks) AS avg_marks FROM results WHERE year = 2024 GROUP BY subject; -- average marks per subject for 2024
  • 5) Min/Max per group: SELECT department, MIN(salary) AS min_sal, MAX(salary) AS max_sal FROM employees GROUP BY department; -- salary range per dept
  • 6) HAVING to filter groups: SELECT product, SUM(quantity) AS qty_sold FROM sales GROUP BY product HAVING SUM(quantity) > 100; -- products with more than 100 units sold
🧮 Formulas
  1. AVG(column) = SUM(column) / COUNT(column) -- average ignoring NULLs (COUNT(column) excludes NULLs)
  2. COUNT(*) = count of all rows in the group (including NULLs in other columns)
  3. COUNT(column) = count of non-NULL values in column
  4. COUNT(DISTINCT column) = count of unique non-NULL values
  5. GROUP BY syntax: SELECT cols, AGG(col) FROM table GROUP BY cols
  6. Filter groups: use HAVING condition (e.g., HAVING SUM(sales) > 1000)
📊 Visual ideas
Bar chart: x-axis = group (e.g., city), y-axis = aggregate (e.g., total_sales). Use when comparing totals or averages across categories. SQL to produce data: SELECT city, SUM(sales) FROM orders GROUP BY city;
Pie chart: slices = proportion of total (e.g., percent sales per product). Good for showing share. Compute percent with SQL: SELECT product, SUM(amount) AS total, 100.0*SUM(amount)/(SELECT SUM(amount) FROM sales) AS pct FROM sales GROUP BY product;
Line chart: x-axis = time (day/month/year), y-axis = aggregate (sales/visits). Use GROUP BY date_trunc or year/month columns. Example: SELECT month, SUM(sales) FROM orders GROUP BY month ORDER BY month;
Stacked bar chart: x-axis = group (e.g., month), stack = subgroup (e.g., product category) with height = SUM(sales). SQL: SELECT month, category, SUM(sales) FROM orders GROUP BY month, category ORDER BY month;
💻11

Built-in Functions

What are Built-in Functions?
Built-in functions in SQL are predefined routines provided by the database engine to perform common operations on data — such as calculations, text manipulation, date/time extraction, type conversion and null handling. They simplify queries by doing data transformations directly in SELECT, WHERE, HAVING or ORDER BY clauses.

Main categories

  • Aggregate functions — operate on a set of rows and return a single value (e.g., SUM, COUNT, AVG, MIN, MAX). Often used with GROUP BY.
  • String (text) functions — manipulate text values (e.g., CONCAT, UPPER, LOWER, SUBSTRING, TRIM, LENGTH).
  • Numeric functions — numeric processing (e.g., ROUND, CEILING, FLOOR, ABS, MOD, POWER).
  • Date/time functions — extract or format date parts (e.g., NOW(), CURDATE(), YEAR(), MONTH(), DATE_FORMAT).
  • Conversion functions — change data types (e.g., CAST(... AS type), CONVERT(..., type)).
  • Null-handling / conditional — handle NULLs or conditional values (e.g., COALESCE, IFNULL, NULLIF, CASE).

Important notes

  • Aggregate functions ignore NULLs (except COUNT(*)). Use COALESCE to replace NULLs if needed.
  • Use GROUP BY when applying aggregates per category. Use HAVING to filter groups after aggregation.
  • Functions can be nested: e.g., UPPER(TRIM(name)) or ROUND(AVG(price), 2).
  • Some functions and exact names may vary slightly between SQL dialects (MySQL, PostgreSQL, SQL Server). CBSE examples assume standard/common functions.

Typical usage examples (SQL snippets)

-- Aggregates: total sales per product
SELECT product_id, SUM(amount) AS total_sales
FROM Sales
GROUP BY product_id
ORDER BY total_sales DESC;

-- String functions: display full name in uppercase
SELECT UPPER(CONCAT(first_name, ' ', last_name)) AS full_name
FROM Students;

-- Date functions: extract year and month from order_date
SELECT order_id, YEAR(order_date) AS yr, MONTH(order_date) AS mth
FROM Orders;

-- Null handling: show 0 if no bonus
SELECT emp_id, COALESCE(bonus, 0) AS bonus_amount
FROM Employees;

-- Numeric function: round average price to 2 decimals
SELECT category, ROUND(AVG(price), 2) AS avg_price
FROM Products
GROUP BY category;

These built-in functions allow you to process and summarize data directly in queries, enabling concise reports and data cleaning without external tools.

📌 Examples
  • -- 1. Aggregate: count students per class SELECT class, COUNT(*) AS student_count FROM Students GROUP BY class; -- 2. Aggregate + HAVING: classes with more than 30 students SELECT class, COUNT(*) AS student_count FROM Students GROUP BY class HAVING COUNT(*) &gt; 30; -- 3. String functions: format and trim name SELECT TRIM(first_name) AS fn, TRIM(last_name) AS ln, UPPER(CONCAT(TRIM(first_name), ' ', TRIM(last_name))) AS display_name FROM Students; -- 4. Date functions: monthly sales totals SELECT YEAR(sale_date) AS yr, MONTH(sale_date) AS mn, SUM(amount) AS total FROM Sales GROUP BY YEAR(sale_date), MONTH(sale_date) ORDER BY yr, mn; -- 5. Null handling: replace NULL marks with 0 SELECT student_id, COALESCE(marks, 0) AS marks FROM Results; -- 6. CAST / CONVERT: convert string to date (dialect-specific) SELECT order_id, CAST(order_date_str AS DATE) AS order_date FROM OrdersRaw; -- 7. Numeric: highest and lowest salary SELECT MAX(salary) AS max_sal, MIN(salary) AS min_sal FROM Employees;
🧮 Formulas
  1. SUM(expression) — sum of values in a group
  2. COUNT(column) or COUNT(*) — number of non-NULL values / rows (COUNT(*) counts all rows)
  3. AVG(expression) — average of values (ignores NULLs)
  4. MIN(expression) / MAX(expression) — minimum / maximum value
  5. CONCAT(str1, str2, ...) — join strings
  6. UPPER(col) / LOWER(col) — change case
📊 Visual ideas
Bar chart: total sales per product (x-axis: product_id or product_name, y-axis: SUM(amount)). Good to visualize top-selling items.
Line chart: monthly sales trend (x-axis: month-year using YEAR()/MONTH(), y-axis: SUM(amount)). Shows trends over time.
Pie chart: market share by category (slices: categories, values: SUM(sales)). Useful for distribution at a glance.
Stacked bar chart: sales by region and product (x-axis: region, stacks: product categories, values: SUM(amount)). Highlights composition per region.
💻12

Joins and Combining Tables

Overview
In relational databases, data is distributed across multiple tables. Joins and combining operations let you retrieve and analyse related information by linking rows from two or more tables based on related columns or by concatenating result sets. Common join types are INNER, LEFT OUTER, RIGHT OUTER, FULL OUTER, CROSS, NATURAL and SELF JOIN. Other combining operations include UNION, UNION ALL, INTERSECT and EXCEPT/MINUS.

Why joins are used

  • To reconstruct related information stored in normalized tables (for example, customer orders and order items).
  • To filter or aggregate data that depends on relationships (for example, sales by product category).

Key concepts

  • Join condition – a Boolean expression (usually equality of keys) that specifies how rows from tables match (for example A.id = B.a_id).
  • Cartesian product – result of combining every row of one table with every row of another (happens with CROSS JOIN or missing join condition).
  • Matched rows – rows that satisfy the join condition.
  • Unmatched rows – rows that don’t satisfy the join condition (kept by OUTER JOINs with NULLs in missing columns).

Join types (short description)

  • INNER JOIN – returns only rows having matching values in both tables.
  • LEFT OUTER JOIN (LEFT JOIN) – returns all rows from left table; matched rows from right table or NULL where no match.
  • RIGHT OUTER JOIN (RIGHT JOIN) – returns all rows from right table; matched rows from left or NULL when no match.
  • FULL OUTER JOIN (FULL JOIN) – returns rows when there is a match in one of the tables. (Not supported directly in some DBMS; can be simulated using UNION of LEFT and RIGHT.)
  • CROSS JOIN – Cartesian product of two tables (no join condition) – every row of A paired with every row of B.
  • NATURAL JOIN – automatically joins on columns with the same names in both tables (use with caution to avoid unintended matches).
  • SELF JOIN – table joined with itself to compare rows in the same table (use aliases to distinguish copies).

Combining result sets

  • UNION – combines results of two SELECTs and removes duplicates; column list and types must match.
  • UNION ALL – combines results and keeps duplicates.
  • INTERSECT – returns rows common to both result sets (supported in some DBMS).
  • EXCEPT / MINUS – returns rows in the first result set that are not in the second (EXCEPT in standard SQL, MINUS in Oracle).

Performance notes

  • Ensure join columns are indexed (foreign key columns) to speed up joins on large tables.
  • Avoid unnecessary CROSS JOINs and joining more tables than required.
  • Use SELECT of only needed columns rather than SELECT * to reduce IO.

Example workflow
Typical steps when writing a join query: choose the main table, decide which related tables you need, set join types according to whether you want unmatched rows, write join conditions using ON or USING, and filter/aggregate as needed using WHERE, GROUP BY and HAVING.

📌 Examples
  • 1) INNER JOIN (Students and Marks) Tables: STUDENT(id, name) MARKS(student_id, subject, marks) Query: SELECT S.id, S.name, M.subject, M.marks FROM STUDENT S INNER JOIN MARKS M ON S.id = M.student_id; Result: rows where a student has marks (only matching students).
  • 2) LEFT JOIN (Students with optional marks) Query: SELECT S.id, S.name, M.subject, M.marks FROM STUDENT S LEFT JOIN MARKS M ON S.id = M.student_id; Result: all students listed; for students with no marks, subject and marks are NULL.
  • 3) FULL OUTER JOIN (Employees and Departments) – simulate in DBMS without FULL JOIN (e.g., MySQL) Tables: EMP(emp_id, name, dept_id) DEPT(dept_id, dept_name) Query (simulation): SELECT E.emp_id, E.name, D.dept_name FROM EMP E LEFT JOIN DEPT D ON E.dept_id = D.dept_id UNION SELECT E.emp_id, E.name, D.dept_name FROM EMP E RIGHT JOIN DEPT D ON E.dept_id = D.dept_id; Result: employees with departments, and departments with no employees (NULLs where appropriate).
  • 4) CROSS JOIN (Cartesian product) Tables: PRODUCTS(product_id, name), COLORS(color) Query: SELECT P.name AS product, C.color FROM PRODUCTS P CROSS JOIN COLORS C; Result: every product paired with every color (useful when generating combinations like product-color variants).
  • 5) SELF JOIN (Manager-Employee relationship in one table) EMP(emp_id, name, manager_id) Query: SELECT E.name AS employee, M.name AS manager FROM EMP E LEFT JOIN EMP M ON E.manager_id = M.emp_id; Result: lists each employee and their manager (NULL if top-level).
  • 6) UNION vs UNION ALL (Combine two queries) Query: SELECT customer_id FROM ONLINE_CUSTOMERS UNION SELECT customer_id FROM STORE_CUSTOMERS; UNION removes duplicates; use UNION ALL to keep duplicates (faster).
🧮 Formulas
  1. INNER JOIN: SELECT columns FROM A INNER JOIN B ON A.key = B.key;
  2. LEFT JOIN: SELECT columns FROM A LEFT JOIN B ON A.key = B.key; -- all rows from A
  3. RIGHT JOIN: SELECT columns FROM A RIGHT JOIN B ON A.key = B.key; -- all rows from B
  4. FULL JOIN (if supported): SELECT columns FROM A FULL OUTER JOIN B ON A.key = B.key; -- all rows from both, NULLs for missing matches
  5. FULL JOIN (MySQL workaround): SELECT ... FROM A LEFT JOIN B ON ... UNION SELECT ... FROM A RIGHT JOIN B ON ...;
  6. CROSS JOIN: SELECT columns FROM A CROSS JOIN B; -- Cartesian product
📊 Visual ideas
Venn diagrams: show two overlapping circles labelled Table A and Table B. Shade intersection for INNER JOIN; shade left-only area plus intersection for LEFT JOIN; right-only plus intersection for RIGHT JOIN; whole both circles for FULL OUTER JOIN; entire rectangle product area for CROSS JOIN.
Table-projection diagram: draw Table A rows on left and Table B rows on right with lines connecting matching keys (use solid lines for matched rows and dashed lines for unmatched rows filled with NULLs) to illustrate how outer joins preserve unmatched rows from one side.
Result-table mockup: show sample input tables (small 3–4 rows) and a result table for each join type (INNER, LEFT, RIGHT, FULL, CROSS) to visually compare outputs.
Flow diagram for join processing: box for Table A rows -> apply join condition against Table B -> route matched to 'matched' output and unmatched to 'left-only' or 'right-only' according to join type.
💻13

Subqueries (Nested Queries)

What is a subquery? A subquery (or nested query) is an SQL query written inside another SQL query. The inner query runs first and its result is used by the outer query. Subqueries let you break complex questions into smaller queries and express conditions that depend on results computed from the database.

Why use subqueries? They help express conditions using aggregated values, select values from another table, filter rows based on existence, or compare a column to a set of values returned by another query.

Types of subqueries:

  • Single-row (scalar) subquery: Returns one value (one row, one column). Used with operators like =, <, >.
  • Single-column / multiple-row subquery: Returns one column but many rows. Often used with IN, NOT IN, or EXISTS.
  • Correlated subquery: Refers to columns from the outer query. It is evaluated once per outer row.
  • Scalar subquery: A subquery that returns exactly one value (useful in SELECT or WHERE comparisons).

Common subquery forms and keywords:

  • IN / NOT IN — checks membership in a returned set.
  • EXISTS / NOT EXISTS — checks whether the subquery returns any rows.
  • ANY / ALL — compares a value to any or all values from the subquery.
  • Aggregate in subquery — e.g., (SELECT AVG(...)) to compare against group results.

Execution order: For non-correlated subqueries, the DBMS evaluates the inner query first and then the outer query uses its result. For correlated subqueries, the inner query is re-evaluated for each row of the outer query.

When not to use subqueries: For some tasks JOINs are more efficient and easier for the optimizer to handle. Use subqueries when they make the logic clearer (e.g., comparing to aggregate values, existence checks) or when you need nested filtering that depends on intermediate results.

Example patterns (shown below in examples):

-- Compare to aggregate
SELECT name FROM Students WHERE marks > (SELECT AVG(marks) FROM Students);

-- Correlated: find rows relative to their group
SELECT e1.name FROM Employee e1
WHERE salary > (SELECT AVG(e2.salary) FROM Employee e2 WHERE e2.dept = e1.dept);

-- EXISTS: check related rows
SELECT c.customer_id FROM Customers c WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.customer_id = c.customer_id);

-- IN: use set membership
SELECT product_name FROM Products WHERE category_id IN (SELECT id FROM Categories WHERE name = 'Stationery');

Performance note: Correlated subqueries can be slow on large tables because they run per outer row. Rewrite as JOINs or use indexed columns when possible. Use EXPLAIN or execution plans to compare alternatives.

📌 Examples
  • Find students who scored above the class average: SQL: SELECT name FROM Students WHERE marks > (SELECT AVG(marks) FROM Students);
  • Employees earning more than their department average (correlated subquery): SQL: SELECT e1.name, e1.salary, e1.dept FROM Employee e1 WHERE e1.salary > (SELECT AVG(e2.salary) FROM Employee e2 WHERE e2.dept = e1.dept);
  • Customers who have placed at least one order (EXISTS): SQL: SELECT c.customer_id, c.name FROM Customers c WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.customer_id = c.customer_id);
  • Products in categories marked 'On Sale' (IN): SQL: SELECT p.product_id, p.product_name FROM Products p WHERE p.category_id IN (SELECT id FROM Categories WHERE on_sale = 'Y');
  • Top seller(s) — find products whose sales equal the maximum sales (scalar subquery): SQL: SELECT product_name FROM Sales WHERE units_sold = (SELECT MAX(units_sold) FROM Sales);
  • Orders with amount greater than the average order amount for that customer (correlated + aggregate): SQL: SELECT o.order_id, o.amount FROM Orders o WHERE o.amount &gt; (SELECT AVG(o2.amount) FROM Orders o2 WHERE o2.customer_id = o.customer_id);
🧮 Formulas
  1. Single-value: SELECT cols FROM T1 WHERE col = (SELECT agg(col2) FROM T2 WHERE ...);
  2. Set membership: SELECT cols FROM T1 WHERE col IN (SELECT col2 FROM T2 WHERE ...);
  3. Existence: SELECT cols FROM T1 WHERE EXISTS (SELECT 1 FROM T2 WHERE T2.key = T1.key AND ...);
  4. Correlated: SELECT a.* FROM A a WHERE a.x > (SELECT AVG(b.x) FROM B b WHERE b.group = a.group);
  5. ANY/ALL: SELECT cols FROM T WHERE value > ANY (SELECT value FROM Other WHERE ...); -- true if greater than at least one returned value SELECT cols FROM T WHERE value &gt; ALL (SELECT value FROM Other WHERE ...); -- true if greater than every returned value
📊 Visual ideas
Execution flowchart: two-box diagram showing 'Inner query executes first (non-correlated)' -> 'Outer query uses inner result'; and separate path showing 'Correlated subquery: inner executes per outer row' with loop arrows.
Nested-box diagram: draw outer query as a large rectangle and inner query as a nested smaller rectangle inside to show containment and data flow from inner to outer.
Venn diagram or set diagram: show set returned by subquery and how IN or NOT IN filters the outer set; useful to contrast with JOIN (overlap vs pairwise matches).
Bar chart example: compare counts of rows returned by a subquery vs counts after outer filter (e.g., total students vs students above average) to illustrate filtering effect.
⚖️14

Set Operations

What are Set Operations?

In SQL, set operations combine the result sets of two or more SELECT queries as if each result were a mathematical set. The main set operations are UNION (and UNION ALL), INTERSECT, and EXCEPT (or MINUS in some SQL dialects). They let you merge, find common rows, or subtract rows between queries.

Requirements and behaviour

  • All SELECTs combined by a set operator must return the same number of columns, and each corresponding column must have compatible data types.
  • Column names in the final result are taken from the first SELECT statement.
  • By default set operations treat rows as sets: duplicates are removed. (UNION is equivalent to UNION DISTINCT.) Use UNION ALL to preserve duplicates.
  • ORDER BY applies to the final combined result (and usually must appear at the end). Use parentheses to control the order of operations when mixing operators.
  • NULLs: for the purpose of duplicate elimination and comparison in set operations, rows with NULLs in the same positions are considered the same.

Basic syntax

SELECT col1, col2, ... FROM table1
UNION [ALL]
SELECT col1, col2, ... FROM table2;

SELECT ... FROM ...
INTERSECT
SELECT ... FROM ...;

SELECT ... FROM ...
EXCEPT | MINUS
SELECT ... FROM ...;

Notes on precedence

SQL dialects may evaluate set operators left-to-right. To avoid ambiguity when combining operators (e.g., UNION with INTERSECT), put SELECT blocks in parentheses and add a final ORDER BY if needed.

📌 Examples
  • Example 1 — UNION (combine two class lists, remove duplicates): Tables: ClassA(student_id, name) contains (1,'Asha'), (2,'Ravi'); ClassB contains (2,'Ravi'), (3,'Neha'). Query: SELECT student_id, name FROM ClassA UNION SELECT student_id, name FROM ClassB; Result: (1,'Asha'), (2,'Ravi'), (3,'Neha'). (Duplicates removed.)
  • Example 2 — UNION ALL (keep duplicates): Same tables as Example 1. Query: SELECT student_id, name FROM ClassA UNION ALL SELECT student_id, name FROM ClassB; Result: (1,'Asha'), (2,'Ravi'), (2,'Ravi'), (3,'Neha'). (Notice 'Ravi' appears twice.)
  • Example 3 — INTERSECT (common rows): Tables: EmpDeptA(emp_id, emp_name) contains (101,'Anil'), (102,'Sunita'); EmpDeptB contains (102,'Sunita'), (103,'Mohan'). Query: SELECT emp_id, emp_name FROM EmpDeptA INTERSECT SELECT emp_id, emp_name FROM EmpDeptB; Result: (102,'Sunita'). (Returns only rows present in both result sets.)
  • Example 4 — EXCEPT / MINUS (rows in first not in second): Tables: CustomersA contains (C1,'Priya'), (C2,'Aman'); CustomersB contains (C2,'Aman'). Query (SQL Server/Postgres): SELECT cust_id, name FROM CustomersA EXCEPT SELECT cust_id, name FROM CustomersB; (or Oracle: ... MINUS ...) Result: (C1,'Priya'). (Returns customers in A who are not in B.)
🧮 Formulas
  1. UNION syntax: SELECT cols FROM t1 UNION [ALL] SELECT cols FROM t2
  2. INTERSECT syntax: SELECT cols FROM t1 INTERSECT SELECT cols FROM t2
  3. EXCEPT / MINUS syntax: SELECT cols FROM t1 EXCEPT|MINUS SELECT cols FROM t2
  4. Rules: number_of_columns(SELECT1) = number_of_columns(SELECT2); corresponding column data types must be compatible
  5. Duplicates: UNION (distinct) removes duplicates; UNION ALL preserves duplicates
  6. ORDER BY: applies to final combined result; put ORDER BY at the end (use parentheses to control grouping of set ops)
📊 Visual ideas
Two-set Venn diagram labeled A and B: shade A ∪ B for UNION; shade overlapping region A ∩ B for INTERSECT; shade A \ B (only A part) for EXCEPT/MINUS.
Three-set Venn diagram to illustrate more complex combinations (e.g., (A ∪ B) \ C or (A ∩ B) ∪ C).
Small table-to-table visualization: draw two tables with rows; highlight which rows move into final result for UNION / UNION ALL / INTERSECT / EXCEPT (use arrows to a result table).
Flowchart showing sequence: run SELECT1 -> run SELECT2 -> apply set operator (merge/remove duplicates) -> optional ORDER BY -> final output. Useful to explain why ORDER BY is at the end.
💻15

Views

What is a View?

A view is a virtual table defined by a SQL query. It does not store data itself (unless it's a materialized view); rather it presents data stored in one or more base tables using a SELECT statement. Users can query a view the same way they query a table.

Why use Views?

  • Security: restrict access to specific columns/rows without giving access to the underlying table.
  • Simplification: hide complex joins/filters behind a simple table-like interface.
  • Reusability: centralize commonly used queries so multiple users/programs can reuse them.
  • Abstraction: present data in a form that matches business needs without changing base tables.

Basic Syntax

CREATE VIEW view_name AS
SELECT column_list
FROM table_list
WHERE conditions;

-- Example: CREATE OR REPLACE VIEW view_name AS ...
-- DROP VIEW view_name;

Types of Views

  • Simple view: based on a single table, may be updatable (INSERT/UPDATE/DELETE) if it meets certain rules.
  • Complex view: uses JOINs, GROUP BY, aggregate functions, DISTINCT, subqueries — usually not updatable.
  • Materialized view: stores the result set physically to improve performance. It must be refreshed when base data changes.

Updatable Views and WITH CHECK OPTION

Some views can be used to change (INSERT/UPDATE/DELETE) the underlying table. To enforce that changes through a view do not violate the view's conditions, use:

CREATE VIEW v AS SELECT ... FROM ... WHERE ...
WITH CHECK OPTION;

WITH CHECK OPTION prevents changes through the view that would cause rows to disappear from the view (i.e., violate the WHERE condition).

Advantages

  • Security control: grant SELECT on a view but not on the base table.
  • Consistency: present a stable interface even if table structures change.
  • Reduced complexity for end-users and application code.

Limitations

  • Performance: complex views (especially nested views) can be slower; materialized views trade freshness for speed.
  • Not all views are updatable; DBMS-specific rules decide updatability.
  • Views do not automatically reflect aggregated historical snapshots unless materialized.

Permissions

You can GRANT or REVOKE privileges on views just like tables. Granting SELECT on a view does not automatically grant privileges on the underlying tables.

Common operations (examples shown)

-- Create a view for students with average marks > 75
CREATE VIEW TopStudents AS
SELECT s.student_id, s.name, (m.math + m.science + m.english)/3.0 AS avg_marks
FROM Students s JOIN Marks m ON s.student_id = m.student_id
WHERE (m.math + m.science + m.english)/3.0 > 75;

-- Query the view
SELECT * FROM TopStudents;

-- Create an updatable view for employee phone numbers
CREATE VIEW EmpPhones AS
SELECT emp_id, name, phone
FROM Employees;

-- With check option to ensure phone updates keep emp in view conditions
CREATE VIEW ActiveEmployees AS
SELECT emp_id, name, dept
FROM Employees
WHERE status = 'ACTIVE'
WITH CHECK OPTION;

-- Drop a view
DROP VIEW TopStudents;

Best Practices

  • Give meaningful names to views indicating their purpose (e.g., CurrentOrders, DeptSalesSummary).
  • Keep views simple where possible; avoid deep nesting of views.
  • Document whether a view is intended to be updatable or read-only.
  • Use materialized views only when query performance is critical and data staleness is acceptable.
📌 Examples
  • School report: Create a view TopStudents that lists student_id, name and average marks where average &gt; 75. Teachers can query TopStudents without seeing full marks details or other sensitive info.
  • HR restricted access: An EmployeesPublic view shows emp_id, name, dept but hides salary and home address. HR has access to the base table; other staff get only the view.
  • Sales summary: Create a view MonthlySalesSummary that aggregates sales by product and month. Business users query the summary view rather than writing GROUP BY queries themselves.
  • Application abstraction: An e-commerce app uses a ProductAvailability view that joins Products and Inventory to present only in-stock items to the front-end.
  • Updatable view: EmpPhones (emp_id, name, phone) created from Employees table can allow helpdesk staff to update phone numbers without exposing other employee details.
🧮 Formulas
  1. CREATE VIEW view_name AS SELECT column_list FROM table_list WHERE conditions;
  2. CREATE OR REPLACE VIEW view_name AS SELECT ...; (replace existing view)
  3. DROP VIEW view_name; (remove view)
  4. CREATE VIEW view_name AS SELECT ... WITH CHECK OPTION; (prevent updates violating view conditions)
  5. SELECT * FROM view_name; (query a view as if it were a table)
📊 Visual ideas
Entity-View-User flow diagram: boxes for Base Tables (Students, Marks) -> arrow to View (TopStudents) -> arrow to Users (Teachers). Annotate to show that users query the view but not base tables.
View definition diagram: show SQL SELECT → parsing → virtual table output. Indicate that the view is a stored SELECT statement, not duplicated data.
Permission diagram: Base Table with restricted columns (salary, address) and View exposing only allowed columns; show GRANT SELECT on view but not on base table.
Performance comparison chart: bar chart comparing query time for (a) direct complex join on base tables, (b) querying a view (same as a), (c) querying a materialized view (fastest).
💻16

Indexes

What is an index?
An index is a database structure that improves the speed of data retrieval operations on a table at the cost of additional writes and storage. It works like the index in a book — instead of scanning every page (full table scan), the DBMS uses the index to jump directly to the relevant rows.

Why use indexes?

  • Faster SELECT queries that use WHERE, JOIN, ORDER BY or GROUP BY on indexed columns.
  • Can enforce uniqueness (unique index).

Types of indexes (common types taught in Class 11 IP):

  • Single-column index — index on one column: CREATE INDEX idx_name ON table(column);
  • Composite (multi-column) index — index on multiple columns: CREATE INDEX idx_name ON table(col1, col2); useful when queries filter on col1 and col2 in that order.
  • Unique index — enforces that indexed column(s) contain no duplicate values: CREATE UNIQUE INDEX ui_name ON table(column);
  • Primary key index — automatically created for primary keys; often a clustered index.
  • Clustered vs Non-clustered — clustered index defines physical order of rows (one per table); non-clustered stores pointers to rows (many possible).
  • Index implementations — B-tree (general purpose), hash (good for equality), bitmap (low cardinality). In students' curriculum focus on B-tree conceptually.

How indexes help (conceptual):
A B-tree index reduces search cost from scanning n rows (O(n)) to a tree traversal cost approximately O(log n). The DBMS finds the location via the tree and retrieves only relevant rows.

SQL examples:

-- Create a single-column index
CREATE INDEX idx_students_roll ON Students(roll_no);

-- Create a unique index
CREATE UNIQUE INDEX ux_students_email ON Students(email);

-- Create a composite index
CREATE INDEX idx_students_class_name ON Students(class, last_name);

-- Drop index (syntax varies by DBMS; example for MySQL)
DROP INDEX idx_students_roll ON Students;

-- Alternative using ALTER TABLE (MySQL)
ALTER TABLE Students ADD INDEX idx_join_col (class);

Using EXPLAIN to check index usage:

EXPLAIN SELECT * FROM Students WHERE roll_no = 101;
-- The output will show if the index idx_students_roll is being used

Advantages:

  • Greatly speeds up read operations (SELECT).
  • Can enforce uniqueness.

Disadvantages / trade-offs:

  • Indexes consume storage space.
  • Every INSERT/UPDATE/DELETE that changes indexed columns must update the index — slower write performance.
  • Poor choice of indexes (low selectivity) may not help performance.

When to create an index?

  • Columns frequently used in WHERE, JOIN, ORDER BY, GROUP BY.
  • Columns with high selectivity (many distinct values).
  • Not on small lookup tables, frequently updated columns, or low-cardinality columns (like boolean fields) unless part of specialized indexes.

Important terms:

  • Selectivity — how many distinct values a column has relative to rows; higher is better for indexing.
  • Covering index — an index that contains all columns needed by a query so the DBMS can answer the query using only the index without touching the table.

Practical notes for students: Practice creating/dropping indexes and use EXPLAIN to compare query plans. Observe how indexed queries run faster for large tables but inserts become slower.

📌 Examples
  • Library catalogue (real-life): The index at the back of a book lists topics and page numbers allowing you to jump to pages directly, instead of reading every page. Similarly, a database index points to rows with particular values.
  • School database (SQL example): Create an index on Students table to speed up search by roll number - CREATE INDEX idx_students_roll ON Students(roll_no); Then queries like SELECT * FROM Students WHERE roll_no = 10; run much faster on large tables.
  • E-commerce site: Create composite index on (category_id, price) to speed up queries that filter by category and sort or filter by price.
🧮 Formulas
  1. Full table scan cost ≈ O(n) where n = number of rows.
  2. Indexed search (B-tree) cost ≈ O(log_b n) where b = branching factor (fan-out) of the tree. For simplicity often written as O(log n).
  3. Selectivity = (number of distinct values in column) / (total number of rows). High selectivity (close to 1) makes an index more effective.
  4. Expected rows returned for equality on a column ≈ total_rows / distinct_values.
  5. Approximate index storage (conceptual): index_size ≈ number_of_rows × (key_size + pointer_size) + overhead
📊 Visual ideas
Line graph: X-axis = number of rows; Y-axis = query time. Two lines: with index vs without index (without index grows linearly, with index grows logarithmically).
Bar chart: Comparison of average query time (ms) for SELECT on a large table: no index, single-column index, composite index, showing performance improvements.
Pie chart: Storage usage breakdown showing table data vs total index storage (to show overhead of indexes).
Diagram: B-tree schematic showing root node, internal nodes, leaf nodes with pointers to records — useful to visualize how index search reduces comparisons.
🧪17

Transactions and ACID Properties

Transaction — Definition
A transaction is a logical unit of work that groups one or more SQL operations (INSERT/UPDATE/DELETE/SELECT) so they execute together. A transaction moves the database from one consistent state to another.

Why use transactions?
To ensure data integrity, recoverability and correct concurrent behavior when multiple users access/modify the database.

Transaction control commands (SQL)

BEGIN TRANSACTION;   -- start transaction (some systems use START TRANSACTION)
... SQL statements ...
COMMIT;              -- make changes permanent
ROLLBACK;            -- undo changes since transaction began
SAVEPOINT sp_name;   -- create a point to roll back to
ROLLBACK TO sp_name; -- roll back to that savepoint

ACID properties

  • Atomicity — "all or nothing". Either all operations in a transaction succeed and are committed, or if any step fails, all changes are undone (rolled back). Example: in a bank transfer, debiting one account and crediting another must both occur, or neither.
  • Consistency — Transactions must preserve database rules, constraints and integrity (primary keys, foreign keys, triggers, custom constraints). If the database was consistent before the transaction, it must be consistent after it (assuming the transaction commits).
  • Isolation — Concurrent transactions should not interfere with each other. The intermediate states of a transaction are invisible to other transactions until it commits. Different isolation levels (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE) control trade-offs between performance and isolation.
  • Durability — Once a transaction commits, its changes are permanent even if the system crashes immediately after. Durability is usually implemented by writing redo logs or commit records to stable storage.

Common concurrency anomalies

  • Dirty Read — Transaction A reads uncommitted changes made by Transaction B (possible under READ UNCOMMITTED).
  • Non-repeatable Read — A row read twice in the same transaction returns different values because another transaction updated and committed between reads (possible under READ COMMITTED).
  • Phantom Read — A query returns a different set of rows in the same transaction because another transaction inserted or deleted rows (possible under lower isolation levels).
  • Lost Update — Two transactions update the same row; one update overwrites the other.

Transaction lifecycle (brief)

  • Active — Transaction is executing statements.
  • Partially Committed — Last statement executed but commit not complete.
  • Committed — Changes permanently recorded.
  • Failed/Aborted — Error occurred and transaction rolled back.
  • Terminated — Transaction ended (committed or rolled back).

Practical tips for students

  • Wrap multi-step operations (bank transfer, stock decrement + order create) in a transaction to avoid inconsistencies.
  • Use SAVEPOINT to avoid rolling back entire work when only part must be undone.
  • Choose an isolation level appropriate for the application: high consistency (SERIALIZABLE) for critical financial ops, lower levels for read-heavy apps to improve performance.
📌 Examples
  • Bank transfer: Transfer 5,000 from A to B involves: BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 5000 WHERE id = A; UPDATE accounts SET balance = balance + 5000 WHERE id = B; COMMIT; If the second update fails, ROLLBACK undoes the debit so no money is lost.
  • Online ticket booking: Two users try to book the last seat at the same time. A transaction with appropriate isolation prevents double-booking by locking or serializing access to seat availability.
  • E-commerce order: Reduce inventory and create order record in one transaction. If inventory update succeeds but order creation fails, ROLLBACK prevents inconsistent stock.
  • Exam grading: Update student marks and compute grade in a transaction so constraints (e.g., max marks) remain satisfied upon commit.
🧮 Formulas
  1. Basic transaction template: BEGIN TRANSACTION; -- SQL operations COMMIT; -- or ROLLBACK;
  2. Use SAVEPOINT: SAVEPOINT sp1; -- operations ROLLBACK TO sp1; -- revert to savepoint without leaving transaction COMMIT;
  3. Atomicity principle (conceptual): If any(statement_i fails) then ROLLBACK else COMMIT
  4. Isolation levels (ordered weakest -> strongest): READ UNCOMMITTED < READ COMMITTED < REPEATABLE READ < SERIALIZABLE
  5. Durability mechanism (conceptual): On COMMIT -> write commit record to stable storage (log) -> then acknowledge success
📊 Visual ideas
Transaction lifecycle flowchart showing states: Active -> Partially Committed -> Committed OR Failed/Aborted -> Terminated.
Sequence diagram for a bank transfer: Client -> DB: BEGIN; DB <- Client: UPDATE debit; DB <- Client: UPDATE credit; DB <- Client: COMMIT. Show error path rolling back.
Isolation effects timeline: two parallel transactions reading/updating the same row. Show dirty read, non-repeatable read, phantom read differences across isolation levels (four horizontal lanes for levels, vertical time axis).
ACID Venn-style visual: four labeled areas (Atomicity, Consistency, Isolation, Durability) with short one-line definitions under each.
💻18

Privileges and Security

What are privileges and security? Privileges (or permissions) control what a database user can do (read, write, modify, execute). Security is the set of practices, configurations and controls that protect data confidentiality, integrity and availability. In SQL, privileges are used to authorize actions on database objects (tables, views, procedures) and system actions (create user, create database).

Types of privileges

  • Object privileges: apply to specific schema objects. Common ones: SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, INDEX, REFERENCES, EXECUTE.
  • System/Administrative privileges: global actions such as CREATE USER, CREATE TABLE, CREATE DATABASE, GRANT ANY PRIVILEGE, etc.
  • Role-based privileges: roles group privileges. Roles simplify privilege management by assigning a role to users instead of many individual privileges.

Key SQL commands

  • GRANT — give privilege(s) to a user or role.
  • REVOKE — remove previously granted privilege(s).
  • CREATE ROLE / DROP ROLE — create or remove roles.

Important options and behaviors

  • WITH GRANT OPTION: allows the grantee to grant that privilege to others.
  • Privilege hierarchy / ownership: object owners and DBAs typically have full control. Public is a special pseudo-user to give privileges to all users.
  • Definer vs Invoker rights: stored routines can run with the privileges of the definer (creator) or invoker (caller) — affects access control.

Security best practices

  • Follow the principle of least privilege: grant only the privileges needed to perform tasks.
  • Use roles to manage privileges centrally (easier auditing and changes).
  • Use views to expose only necessary columns/rows (column- and row-level security).
  • Enforce strong authentication (complex passwords, account lockout, multi-factor where supported).
  • Protect against SQL injection: use parameterized queries / prepared statements and validate input.
  • Use encryption for data at rest and in transit (SSL/TLS), and secure backups.
  • Audit and log privilege changes and access patterns.

How it works (flow)

  1. A user authenticates (username/password or other method).
  2. The DBMS checks user roles and privileges.
  3. If a requested action matches a granted privilege, the operation proceeds; otherwise it is denied.

Common classroom examples include granting SELECT to reporting users, creating a role for HR staff with SELECT/UPDATE on employee tables, and creating read-only views for interns.

📌 Examples
  • Granting SELECT on a table to a user: GRANT SELECT ON employees TO alice;
  • Granting multiple privileges: GRANT SELECT, INSERT, UPDATE ON employees TO hr_role;
  • Creating and using a role: CREATE ROLE hr_role; GRANT SELECT, UPDATE ON employees TO hr_role; GRANT hr_role TO bob;
  • Grant with ability to re-grant: GRANT SELECT ON employees TO alice WITH GRANT OPTION; (alice can grant SELECT to others)
  • Revoking a privilege: REVOKE UPDATE ON employees FROM alice; (removes UPDATE right from alice)
  • Using a view for column-level access: CREATE VIEW emp_public AS SELECT id, name, department FROM employees; GRANT SELECT ON emp_public TO intern;
🧮 Formulas
  1. GRANT <privilege_list> ON <object> TO <user_or_role> [WITH GRANT OPTION];
  2. REVOKE <privilege_list> ON <object> FROM <user_or_role> [CASCADE];
  3. CREATE ROLE <role_name>; DROP ROLE <role_name>;
  4. GRANT <role_name> TO <user_name>; REVOKE <role_name> FROM <user_name>;
  5. CREATE VIEW <view_name> AS <SELECT_statement>; -- then GRANT SELECT ON <view_name> TO <user>;
📊 Visual ideas
Role-Based Access Control (RBAC) node diagram: nodes for Users, Roles, and Privileges. Draw arrows: Users -> Roles (membership), Roles -> Privileges (granted actions). Useful to show how granting a role grants multiple privileges at once.
Privilege matrix heatmap: rows = users (or roles), columns = privileges (SELECT, INSERT, UPDATE, DELETE, EXECUTE). Color or mark cells where privilege exists. Good for audits and quick overview.
GRANT/REVOKE flowchart: boxes for Authenticate -> Check Roles/Privileges -> Allow/Block -> Log Event. Include decision node for 'WITH GRANT OPTION' to show propagation step.
Object-level access diagram: tables as boxes with columns; overlay which columns are exposed by a view (shaded) and which users can access that view. Demonstrates column-level security.
📊19

Referential Actions and Data Integrity

Overview

Referential Actions and Data Integrity ensure that relationships between tables remain consistent. Referential integrity enforces that a foreign key (FK) in a child table must either match a primary key (PK) value in a parent table or be NULL (if allowed). Referential actions define what the database should do to child rows when the referenced parent row is updated or deleted.

Types of Data Integrity

  • Entity integrity: Primary key values must be unique and NOT NULL.
  • Referential integrity: Foreign keys must reference existing primary keys (or be NULL).
  • Domain integrity: Column values must be from a valid domain (type, range, format).
  • User-defined integrity: Business rules implemented via constraints, triggers, or application logic.

Referential Actions (ON DELETE / ON UPDATE)

When defining a foreign key, you can specify actions the DBMS performs if the referenced row is updated or deleted:

  • CASCADE: Propagates the change to child rows. ON DELETE CASCADE removes child rows when the parent is deleted. ON UPDATE CASCADE updates child FK values when the parent PK changes.
  • SET NULL: Sets the child FK to NULL when the parent is deleted/updated. Use only if the FK column allows NULL.
  • SET DEFAULT: Sets the child FK to a default value when the parent is deleted/updated (requires a DEFAULT defined).
  • RESTRICT: Prevents the delete/update on the parent if any child rows reference it. The delete/update is rejected immediately.
  • NO ACTION: Standard SQL behavior similar to RESTRICT in many DBMSs; difference arises when constraint checking is deferred (NO ACTION defers checking until end of transaction, RESTRICT checks immediately).

Typical SQL syntax

CREATE TABLE Child (
  child_id INT PRIMARY KEY,
  parent_id INT,
  FOREIGN KEY (parent_id) REFERENCES Parent(parent_id)
    ON DELETE CASCADE
    ON UPDATE NO ACTION
);

Behavior examples (summary)

  • Parent row deleted + ON DELETE CASCADE → child rows deleted automatically.
  • Parent row deleted + ON DELETE SET NULL → child foreign key values become NULL.
  • Parent row deleted + ON DELETE RESTRICT/NO ACTION → delete is refused if child rows exist.

When to use each action

  • CASCADE: Use when child rows are meaningful only in context of parent (e.g., order items when an order is removed).
  • SET NULL / SET DEFAULT: Use when child can exist without a parent but should lose the reference (e.g., employee's manager removed).
  • RESTRICT/NO ACTION: Use when parent must not be removed if dependents exist (e.g., customer must not be deleted if they have orders).

Important notes

  • Many DBMSs default to NO ACTION if no referential action is specified.
  • Multi-level cascades will propagate through chains of FK relationships; be careful to avoid accidental large deletions.
  • Changing a primary key value is rare; ON UPDATE CASCADE helps keep child FKs consistent if you do.
📌 Examples
  • Orders and OrderItems (ON DELETE CASCADE): Real-life: If an order is canceled and removed from the system, its order items should also be removed. SQL: CREATE TABLE OrderItems (item_id INT PRIMARY KEY, order_id INT, FOREIGN KEY(order_id) REFERENCES Orders(order_id) ON DELETE CASCADE);
  • Customers and Orders (ON DELETE RESTRICT): Real-life: Prevent deleting a customer record if they have placed orders. SQL: CREATE TABLE Orders (order_id INT PRIMARY KEY, customer_id INT, FOREIGN KEY(customer_id) REFERENCES Customers(customer_id) ON DELETE RESTRICT);
  • Departments and Employees (ON DELETE SET NULL): Real-life: If a department is closed, employees remain but their department_id becomes NULL until reassignment. SQL: CREATE TABLE Employees (emp_id INT PRIMARY KEY, dept_id INT, FOREIGN KEY(dept_id) REFERENCES Departments(dept_id) ON DELETE SET NULL);
  • Products and OrderDetails (ON UPDATE CASCADE): Real-life: If product codes are changed centrally, all related order detail rows update automatically. SQL: CREATE TABLE OrderDetails (detail_id INT PRIMARY KEY, product_code VARCHAR(20), FOREIGN KEY(product_code) REFERENCES Products(code) ON UPDATE CASCADE);
🧮 Formulas
  1. Referential integrity (logical): For every child tuple c, either c.FK IS NULL OR EXISTS parent tuple p such that p.PK = c.FK.
  2. Formal: ∀c ∈ Child, (c.FK = NULL) ∨ (∃p ∈ Parent: p.PK = c.FK).
  3. SQL foreign key template: FOREIGN KEY (<child_column>) REFERENCES <Parent>(<parent_column>) [ON DELETE {CASCADE | SET NULL | SET DEFAULT | RESTRICT | NO ACTION}] [ON UPDATE {same options}].
  4. Constraint check rule for ON DELETE CASCADE: DELETE FROM Parent WHERE PK = x ⇒ DELETE FROM Child WHERE FK = x (propagate to further children).
📊 Visual ideas
ER diagram: Parent table box (PK) with an arrow to Child table box (FK). Label arrow with chosen action (CASCADE / SET NULL / RESTRICT).
Before/After table snapshots: two small tables showing parent and child rows before deletion and after applying ON DELETE CASCADE (child rows removed) and ON DELETE SET NULL (child FK = NULL).
Cascade propagation tree: a directed tree showing Parent A → Child B → Grandchild C. Visualize deletion at A and cascading deletions along arrows to B and C.
Flowchart of delete operation: Start → Check FK constraints → If child exists then apply action (CASCADE: delete child; SET NULL: update child; RESTRICT/NO ACTION: abort) → End.
💻20

Practical Query Techniques and Best Practices

Overview: Practical Query Techniques and Best Practices teach how to write correct, readable, secure and efficient SQL queries. The goal is to retrieve and manipulate data reliably while minimizing resource use and response time.

Stepwise approach to build queries

  • Identify the exact columns required — avoid SELECT * to reduce I/O and transfer time.
  • Filter rows as early as possible with WHERE (row-level filtering) rather than later stages.
  • Choose appropriate joins to combine related tables; prefer INNER JOIN when you only want matching rows.
  • Aggregate only after filtering; use GROUP BY and HAVING correctly (WHERE filters rows before aggregation; HAVING filters grouped results).
  • Limit result sets for paging (LIMIT/OFFSET) in UI-driven queries.

Readability & maintainability

  • Use meaningful aliases for tables and columns (e.g., s for students, m for marks).
  • Break complex queries into CTEs (WITH ... AS) or views for clarity.
  • Comment non-obvious logic so others (and future you) understand intent.

Performance & optimization

  • Use indexes for columns used in WHERE, JOIN ON and ORDER BY — they speed lookups. Avoid functions on indexed columns in WHERE (e.g., WHERE UPPER(name) = 'A') since they can prevent index use.
  • Prefer INDEX-supported comparisons and equality predicates; aim for selective predicates (high selectivity returns few rows).
  • Avoid unnecessary DISTINCT, ORDER BY or GROUP BY when not needed — they cause sorting/aggregation overhead.
  • Use EXPLAIN/EXPLAIN ANALYZE to inspect query execution plans and identify full table scans or expensive operations.
  • Consider proper join order and join types; databases optimize joins, but reducing input size with early filters helps.

Correct use of subqueries, EXISTS, IN and joins

  • Use JOIN to combine columns from related tables when you need columns from both tables.
  • Use EXISTS for semi-joins (check existence) and correlated subqueries when dependent on outer row values; EXISTS can be faster than IN for large subquery result sets.
  • Use IN for fixed lists or small subquery results; for large lists use joins or temporary tables.

Safety, transactions & parameters

  • Use parameterized queries or prepared statements to prevent SQL injection — never concatenate user input into SQL strings.
  • Wrap multiple DML statements (INSERT/UPDATE/DELETE) in transactions to enforce atomicity (COMMIT/ROLLBACK).
  • Perform backups and test destructive queries (DELETE/UPDATE) first with SELECT to verify affected rows.

Practical habits

  • Test queries on a sample dataset before running on production.
  • Profile slow queries and add targeted indexes rather than indexing everything.
  • Use pagination for web apps and fetch only required columns for mobile apps to save bandwidth.

Summary: Combine clear, well-structured SQL with filtering-first logic, judicious use of indexes, safe parameterized execution, and analysis of execution plans. These practices produce correct results, better performance and easier maintenance.

📌 Examples
  • -- 1. Select specific columns and filter early SELECT student_id, name, grade FROM students WHERE grade >= 9 ORDER BY name ASC;
  • -- 2. Inner join to combine student info with marks SELECT s.student_id, s.name, m.subject, m.marks FROM students s INNER JOIN marks m ON s.student_id = m.student_id WHERE m.marks >= 75;
  • -- 3. Aggregation with GROUP BY and HAVING (total sales by product, only top sellers) SELECT product_id, SUM(amount) AS total_sales FROM sales WHERE sale_date >= '2025-01-01' GROUP BY product_id HAVING SUM(amount) > 10000 ORDER BY total_sales DESC;
  • -- 4. Correlated subquery (students scoring above class average) SELECT s.student_id, s.name, s.total_marks FROM students s WHERE s.total_marks > ( SELECT AVG(total_marks) FROM students WHERE class = s.class );
  • -- 5. EXISTS vs IN (customers with orders) -- Using EXISTS SELECT c.customer_id, c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id); -- Using IN (works well when subquery returns a reasonably small set) SELECT c.customer_id, c.name FROM customers c WHERE c.customer_id IN (SELECT DISTINCT customer_id FROM orders);
  • -- 6. Pagination for web result lists SELECT product_id, name, price FROM products ORDER BY name LIMIT 20 OFFSET 40; -- page 3 with 20 rows per page
🧮 Formulas
  1. Basic select template: SELECT column_list FROM table_name WHERE condition ORDER BY column_list LIMIT n;
  2. Join template: SELECT A.col1, B.col2 FROM A [INNER|LEFT|RIGHT|FULL] JOIN B ON A.key = B.key WHERE ...;
  3. Aggregation template: SELECT group_col, AGG_FUNC(col) FROM table WHERE ... GROUP BY group_col HAVING AGG_FUNC(col) condition;
  4. Correlated subquery template: SELECT * FROM T1 WHERE col OP (SELECT AGG(col2) FROM T2 WHERE T2.fk = T1.pk);
  5. EXISTS template: SELECT * FROM A WHERE EXISTS (SELECT 1 FROM B WHERE B.fk = A.pk AND ...);
  6. Selectivity (useful concept): Selectivity = distinct_values(column) / total_rows (lower is less selective; higher selectivity filters more)
📊 Visual ideas
Bar chart: Total sales by product. X-axis = product name, Y-axis = SUM(amount). SQL to prepare data: SELECT product_name, SUM(amount) AS total_sales FROM sales GROUP BY product_name ORDER BY total_sales DESC;
Line chart: Monthly revenue trend. X-axis = month, Y-axis = SUM(amount). SQL: SELECT DATE_TRUNC('month', sale_date) AS month, SUM(amount) FROM sales GROUP BY month ORDER BY month;
Pie chart: Market share by product category. Slice = SUM(amount) per category. SQL: SELECT category, SUM(amount) FROM sales GROUP BY category;
Stacked bar chart: Sales by region and product category. X-axis = region, stacks = category sales. SQL: SELECT region, category, SUM(amount) FROM sales GROUP BY region, category;

Key Concepts

SQL
Structured Query Language used to create, retrieve, modify and manage data in relational databases.
DDL
Data Definition Language — SQL commands that define or modify database schema (CREATE, ALTER, DROP).
DML
Data Manipulation Language — SQL commands to manipulate data (INSERT, UPDATE, DELETE, SELECT).
DCL
Data Control Language — commands to control access to data (GRANT, REVOKE).
TCL
Transaction Control Language — commands to manage transactions (COMMIT, ROLLBACK, SAVEPOINT).
CREATE TABLE
DDL command used to create a new table with specified columns and data types.
DROP TABLE
DDL command that deletes a table and all its data and structure from the database.
ALTER TABLE
DDL command to modify an existing table structure (add/drop/modify columns).
SELECT
DML statement used to retrieve data from one or more tables.
INSERT
DML statement used to add new rows into a table.
UPDATE
DML statement used to modify existing row(s) in a table.
DELETE
DML statement used to remove row(s) from a table.
WHERE
Clause used to specify conditions that filter which rows are selected or affected.
ORDER BY
Clause used to sort the result set by one or more columns (ASC or DESC).
GROUP BY
Clause used to group rows that have the same values into summary rows for aggregate functions.
HAVING
Clause used to filter groups created by GROUP BY based on aggregate conditions.
JOIN
Operation to combine rows from two or more tables based on a related column (INNER, LEFT, RIGHT, FULL).
PRIMARY KEY
A column or set of columns that uniquely identify each row in a table and cannot be NULL.
FOREIGN KEY
A column or set of columns in one table that refer to the PRIMARY KEY of another table to enforce referential integrity.
Aggregate Function
Functions that perform a calculation on a set of values and return a single value (SUM, COUNT, AVG, MAX, MIN).

End-of-Chapter Trial Paper & Test Questions

Topic-wise questions to test your understanding of every concept in this chapter.

  1. Explain the four categories of SQL commands (DDL, DML, DCL, TCL) and give one example command of each. / SQL कमांड की चार श्रेणियों (DDL, DML, DCL, TCL) को समझाइए और प्रत्येक का एक उदाहरण कमांड दीजिए।
    Show answer

    DDL defines structure (e.g., CREATE), DML manipulates data (e.g., INSERT), DCL manages permissions (e.g., GRANT), and TCL controls transactions (e.g., COMMIT). / DDL संरचना परिभाषित करती है (जैसे CREATE), DML डेटा में हेरफेर करती है (जैसे INSERT), DCL अनुमतियाँ प्रबंधित करती है (जैसे GRANT), और TCL लेन-देन नियंत्रित करती है (जैसे COMMIT)।

  2. Write a CREATE TABLE statement for a Students table with student_id as an integer primary key, name as a non-null variable string of length 50, and dob as a date. / Students तालिका के लिए एक CREATE TABLE कथन लिखिए जिसमें student_id पूर्णांक प्राथमिक कुंजी हो, name लंबाई 50 का गैर-शून्य (non-null) चर स्ट्रिंग हो, और dob एक तिथि हो।
    Show answer

    CREATE TABLE Students (student_id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, dob DATE); This makes student_id unique and not null, forces name to always have a value, and stores dob as a date type. / CREATE TABLE Students (student_id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, dob DATE); यह student_id को विशिष्ट व non-null बनाता है, name में सदैव मान अनिवार्य करता है, और dob को तिथि प्रकार में संग्रहीत करता है।

  3. What is the difference between the WHERE and HAVING clauses in a SELECT query? / SELECT क्वेरी में WHERE और HAVING क्लॉज़ के बीच क्या अंतर है?
    Show answer

    WHERE filters individual rows before grouping and aggregation, whereas HAVING filters groups after GROUP BY based on aggregate conditions such as SUM or COUNT. For example, HAVING COUNT(*) > 30 selects only groups with more than 30 rows. / WHERE समूहन और एकत्रीकरण से पहले अलग-अलग पंक्तियों को छानता है, जबकि HAVING, GROUP BY के बाद समूहों को SUM या COUNT जैसी एकत्रित शर्तों के आधार पर छानता है। उदाहरण के लिए, HAVING COUNT(*) > 30 केवल 30 से अधिक पंक्तियों वाले समूह चुनता है।

  4. Distinguish between DELETE, TRUNCATE and DROP commands. / DELETE, TRUNCATE और DROP कमांड में अंतर कीजिए।
    Show answer

    DELETE removes selected rows (with a WHERE clause) or all rows while keeping the table structure; TRUNCATE quickly removes all rows but keeps the table structure; DROP removes the entire table including its data and definition. / DELETE चयनित पंक्तियाँ (WHERE क्लॉज़ के साथ) या सभी पंक्तियाँ हटाता है पर तालिका संरचना बनाए रखता है; TRUNCATE तेज़ी से सभी पंक्तियाँ हटाता है पर तालिका संरचना रखता है; DROP डेटा व परिभाषा सहित पूरी तालिका हटा देता है।

  5. Write an SQL query to find the average marks per class from a Students(student_id, name, class, marks) table, showing only classes whose average exceeds 60. / Students(student_id, name, class, marks) तालिका से प्रति कक्षा औसत अंक ज्ञात करने हेतु एक SQL क्वेरी लिखिए, केवल उन कक्षाओं को दिखाते हुए जिनका औसत 60 से अधिक है।
    Show answer

    SELECT class, AVG(marks) AS avg_marks FROM Students GROUP BY class HAVING AVG(marks) > 60; This groups rows by class, computes each class's average, and HAVING keeps only those above 60. / SELECT class, AVG(marks) AS avg_marks FROM Students GROUP BY class HAVING AVG(marks) > 60; यह पंक्तियों को कक्षा अनुसार समूहित करता है, प्रत्येक कक्षा का औसत निकालता है, और HAVING केवल 60 से ऊपर वालों को रखता है।

  6. Explain the difference between CHAR(n) and VARCHAR(n), and state which is better for storing student names. / CHAR(n) और VARCHAR(n) के बीच अंतर समझाइए, और बताइए कि छात्रों के नाम संग्रहीत करने के लिए कौन-सा बेहतर है।
    Show answer

    CHAR(n) is a fixed-length string padded with spaces to n characters, while VARCHAR(n) is variable-length and uses only as much space as needed up to n. VARCHAR is better for student names because names vary in length, saving storage. / CHAR(n) एक निश्चित-लंबाई स्ट्रिंग है जो n वर्णों तक रिक्त स्थानों से भरी जाती है, जबकि VARCHAR(n) परिवर्तनशील-लंबाई का है और n तक केवल आवश्यक स्थान उपयोग करता है। छात्रों के नाम के लिए VARCHAR बेहतर है क्योंकि नाम लंबाई में भिन्न होते हैं, जिससे भंडारण बचता है।

  7. What does the LIKE operator do, and what is matched by the patterns 'A%' and '_a%'? / LIKE ऑपरेटर क्या करता है, और पैटर्न 'A%' तथा '_a%' द्वारा क्या मेल खाता है?
    Show answer

    LIKE performs pattern matching using wildcards: % matches any sequence of characters and _ matches a single character. 'A%' matches any value starting with A, and '_a%' matches values whose second character is 'a' (any first character). / LIKE वाइल्डकार्ड का उपयोग करके पैटर्न मिलान करता है: % किसी भी वर्ण क्रम से मेल खाता है और _ एकल वर्ण से मेल खाता है। 'A%' A से शुरू होने वाले किसी भी मान से मेल खाता है, और '_a%' उन मानों से मेल खाता है जिनका दूसरा वर्ण 'a' है (कोई भी पहला वर्ण)।

  8. Describe the purpose of an INNER JOIN and give an example combining Students and Enrollments on student_id. / INNER JOIN का उद्देश्य बताइए और student_id पर Students तथा Enrollments को मिलाने वाला एक उदाहरण दीजिए।
    Show answer

    An INNER JOIN combines rows from two tables where the join condition matches, returning only the matching records. Example: SELECT s.name, e.course_id FROM Students s INNER JOIN Enrollments e ON s.student_id = e.student_id; / INNER JOIN दो तालिकाओं की उन पंक्तियों को जोड़ता है जहाँ जॉइन शर्त मेल खाती है, केवल मेल खाने वाले अभिलेख लौटाता है। उदाहरण: SELECT s.name, e.course_id FROM Students s INNER JOIN Enrollments e ON s.student_id = e.student_id;

Related Laws & Principles

Explore all

Foundational laws & principles behind this chapter. Each one opens a full page — what it says, why it matters, five practice questions and the mistakes to avoid.

Loading related laws…
Sourced from 261 content files · LLOS Learn · browse all chapters