This chapter introduces Structured Query Language (SQL), the standard language for creating, managing and querying relational databases. It explains core RDBMS concepts (tables, rows, columns, keys, relationships) and shows how SQL commands are grouped into DDL, DML, DCL and TCL to define schema, manipulate data, control access and manage transactions. The chapter emphasizes practical skills: creating tables with constraints, inserting/updating/deleting records, retrieving data using SELECT with filtering, sorting, aggregation, grouping and joining multiple tables, and writing subqueries and views. Importance is stressed through real-world applications (data storage, reporting, analytics, backend of web and enterprise apps), data integrity and consistency, and transferable problem‑solving skills. By the end, students will be able to design simple schemas, write correct SQL queries for common tasks, interpret query results, and integrate SQL thinking into software projects.
Learning Objectives
Define basic SQL terms such as table, row, column, schema and primary key
Differentiate the purpose and syntax of DDL, DML, DCL and TCL statements
Construct SELECT queries to retrieve specific columns and rows using WHERE and comparison/logical operators
Apply ORDER BY and LIMIT/TOP to sort and restrict query results
Use aggregate functions (COUNT, SUM, AVG, MIN, MAX) with GROUP BY and HAVING to summarize data
Demonstrate inner, left, right and full outer JOINs to combine data from multiple tables
Write subqueries including single-row, multi-row and correlated subqueries to solve nested-query problems
Employ set operations (UNION, INTERSECT, EXCEPT/MINUS) to combine result sets
Topics in this chapter
18 topics · tap a topic title to jump straight to it.
💻1
Introduction to SQL
💻 COMPUTER SCIENCE / IT
Introduction to SQL
Key Point: Basic SELECT pattern: SELECT FROM
WHERE ORDER BY ;
What is SQL? SQL (Structured Query Language) is a standard language used to communicate with Relational Database Management Systems (RDBMS). It is used to create, read, update and delete (CRUD) data stored in tables. SQL is declarative: you state what result you want and the DBMS figures out how to obtain it.
Why SQL matters (Class 12 context) Many applications — school systems, banks, e-commerce, libraries — store data in relational tables. Knowing SQL lets you retrieve reports, calculate aggregates (totals, averages), join related data (e.g., students and marks), and ensure data integrity (primary/foreign keys, constraints).
Basic concepts
Database: collection of related tables.
Table: rows (records) and columns (fields). Each column has a data type (INT, VARCHAR, DATE, etc.).
Primary Key (PK): uniquely identifies each row in a table (e.g., student_id).
Foreign Key (FK): a column that references a primary key in another table to maintain relationships.
Schema: the structure (definitions) of tables and relationships.
Categories of SQL commands
DDL (Data Definition Language): CREATE TABLE, ALTER TABLE, DROP TABLE — used to define and modify schema.
DML (Data Manipulation Language): INSERT, UPDATE, DELETE, SELECT — used to work with data.
DCL (Data Control Language): GRANT, REVOKE — manage privileges.
TCL (Transaction Control Language): COMMIT, ROLLBACK — manage transactions.
Common SQL statements (short explanation)
CREATE TABLE: define a new table and columns.
INSERT INTO: add new rows.
SELECT ... FROM ... WHERE ...: retrieve rows that match conditions.
ORDER BY: sort results.
GROUP BY + aggregate functions (COUNT, SUM, AVG, MAX, MIN): summarize data.
HAVING: filter groups (used with GROUP BY).
JOIN (INNER, LEFT, RIGHT, FULL): combine rows from two or more tables based on related columns.
COMMIT / ROLLBACK: finalize or undo a transaction.
Example snippets (syntax)
-- Create table
CREATE TABLE Student (
student_id INT PRIMARY KEY,
name VARCHAR(50),
class INT,
dob DATE
);
-- Insert data
INSERT INTO Student (student_id, name, class, dob)
VALUES (1, 'Riya', 12, '2007-05-18');
-- Simple select
SELECT name, class FROM Student WHERE class = 12 ORDER BY name;
-- Aggregate and group
SELECT class, COUNT(*) AS students_count, AVG(marks) AS avg_marks
FROM StudentMarks
GROUP BY class
HAVING AVG(marks) >= 60;
-- Join two tables
SELECT s.name, m.marks
FROM Student s
JOIN StudentMarks m ON s.student_id = m.student_id
WHERE m.subject = 'Mathematics';
-- Transaction
BEGIN;
UPDATE Account SET balance = balance - 500 WHERE account_no = 101;
UPDATE Account SET balance = balance + 500 WHERE account_no = 202;
COMMIT; -- or ROLLBACK on error
Good practices
Use meaningful column and table names.
Define primary keys and appropriate constraints (NOT NULL, UNIQUE, FOREIGN KEY) to ensure data integrity.
Use transactions for multi-step updates to keep data consistent.
Use indexes for faster searches on large tables (but avoid over-indexing).
Where SQL is used in real life Connecting to databases behind web apps (school portals, online stores), generating reports (monthly sales, attendance), analytics queries, and storing user data for mobile apps and banking systems.
📌 Examples
Student database: List all Class 12 students with marks > 75 in Mathematics.
SQL: SELECT s.name, m.marks FROM Student s JOIN StudentMarks m ON s.student_id = m.student_id WHERE s.class = 12 AND m.subject = 'Mathematics' AND m.marks > 75;
Library system: Find overdue books and contact borrowers.
SQL: SELECT b.book_title, u.name, l.due_date FROM Loans l JOIN Users u ON l.user_id = u.user_id JOIN Books b ON l.book_id = b.book_id WHERE l.due_date < CURRENT_DATE;
E-commerce orders: Total monthly sales for last 6 months.
SQL: SELECT DATE_TRUNC('month', order_date) AS month, SUM(total_amount) AS monthly_sales FROM Orders WHERE order_date >= (CURRENT_DATE - INTERVAL '6 months') GROUP BY month ORDER BY month;
Bank transfer transaction: Move money between two accounts using a transaction.
SQL: BEGIN; UPDATE Account SET balance = balance - 2000 WHERE account_no = 5001; UPDATE Account SET balance = balance + 2000 WHERE account_no = 6002; COMMIT;
Attendance report: Percentage attendance of students in a class.
SQL: SELECT student_id, (SUM(CASE WHEN status = 'Present' THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) AS attendance_percent FROM Attendance WHERE class = 12 GROUP BY student_id;
🧮 Formulas
\[Basic SELECT pattern: SELECT <columns> FROM <table> WHERE <condition> ORDER BY <column>;\]
\[MIN(col) — often used with GROUP BY: SELECT col\]
\[COUNT(*) FROM table GROUP BY col\]
\[Group filter: GROUP BY col HAVING aggregate_condition (e.g.\]
\[HAVING AVG(marks) > 60)\]
\[Join pattern: SELECT a.cols\]
\[b.cols FROM A [INNER|LEFT|RIGHT|FULL] JOIN B ON A.key = B.key\]
📊2
SQL Data Types
💻 COMPUTER SCIENCE / IT
SQL Data Types
Key Point: DECIMAL(p,s): total digits = p; digits after decimal = s; integer digits = p - s. Example: DECIMAL(5,2) stores from -999.99 to 999.99 (max magnitude ≈ 10^(p-s) - 10^-s).
What are SQL Data Types?
SQL data types define the kind of values a column can hold (numbers, text, dates, binary, etc.). Choosing the right data type affects correctness, storage, indexing and performance.
Main categories and key types
Numeric
INT / SMALLINT / BIGINT — integers for counters, ids. Typical sizes: SMALLINT (2 bytes), INT (4 bytes), BIGINT (8 bytes).
DECIMAL(p,s) / NUMERIC(p,s) — exact fixed-point (money). p = precision (total digits), s = scale (digits after decimal).
FLOAT / REAL / DOUBLE — approximate floating-point (scientific values, measurements). Not recommended for money.
Character / String
CHAR(n) — fixed-length strings (padded). Good for codes of known length.
VARCHAR(n) — variable-length strings (efficient when length varies).
TEXT (or CLOB) — large text blocks (descriptions, articles).
Date & Time
DATE — calendar date (YYYY-MM-DD).
TIME — time of day (HH:MM:SS).
DATETIME / TIMESTAMP — combined date and time (timestamp often used for UTC/timezone-aware values).
Binary / Large Objects
BLOB — binary large objects (images, files).
Boolean & Enumerations
BOOLEAN (TRUE/FALSE), ENUM or SET (vendor-specific) for limited choices.
NULL — indicates absence of a value; columns may allow or disallow NULL.
Important distinctions & best practices
Use DECIMAL(p,s) for monetary values to avoid rounding errors of floating point.
Choose fixed-size CHAR for truly fixed-length fields (like country codes), and VARCHAR for variable-length text to save space.
Store identifiers that are not used for arithmetic (phone numbers, ZIP codes) as strings (VARCHAR), not integers.
Smaller types reduce storage and improve index performance. Don’t over-allocate (e.g., avoid VARCHAR(1000) if 50 chars suffice).
Be aware of DBMS-specific behavior (storage overhead, max lengths, ENUM availability).
Example CREATE TABLE
<code>CREATE TABLE Employees (
EmpID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100) NOT NULL,
Phone VARCHAR(15), -- stored as text to preserve leading zeros
BirthDate DATE,
Salary DECIMAL(10,2), -- precise currency
Rating FLOAT, -- approximate measurement
Photo BLOB,
IsActive BOOLEAN DEFAULT TRUE
);
</code>
Choosing a type — quick decision guide
If exact arithmetic (money) → DECIMAL(p,s).
If fixed-width code (2-letter country) → CHAR(2).
If variable text (names) → VARCHAR(n).
If large text → TEXT/CLOB.
If binary data (image) → BLOB.
📌 Examples
CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(80), DOB DATE, CGPA DECIMAL(3,2)); -- CGPA like 9.75
Data Definition Language (DDL) is the subset of SQL commands used to define, modify and remove database structures such as tables, schemas and indexes. DDL commands affect the database schema (structure) but do not directly manipulate the data stored (that is handled by DML).
Common DDL commands
CREATE — create a new database object (table, view, index, schema).
ALTER — modify the structure of an existing object (add/drop/modify columns, constraints).
DROP — remove an object permanently from the database.
TRUNCATE — remove all rows from a table quickly while keeping the table definition.
RENAME — change the name of a database object.
COMMENT — add descriptive comments to database objects (supported in some DBMS).
Key characteristics
DDL commands change the schema and are usually auto-committed (most DBMS perform an implicit COMMIT before and after DDL).
DDL affects metadata stored in the data dictionary (catalog).
DDL is generally used by DBAs and developers when designing or changing the database layout.
Example elements of a CREATE TABLE
Column name and data type (e.g., name VARCHAR(50)).
Column constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK.
Table-level constraints such as composite primary keys or foreign keys.
Difference between DDL and DML
DDL (CREATE, ALTER, DROP...) defines and alters structure. DML (INSERT, UPDATE, DELETE, SELECT) manipulates data inside those structures.
Practical notes
Use DROP with caution — it permanently removes structure and usually the data within.
TRUNCATE is faster than DELETE for removing all rows but cannot be rolled back in many DBMS.
When altering production schemas, plan migrations, backups, and downtime to avoid data loss.
Small code examples
CREATE TABLE Student (
roll_no INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
class VARCHAR(10),
dob DATE
);
ALTER TABLE Student ADD COLUMN mobile VARCHAR(15);
DROP TABLE Student;
TRUNCATE TABLE Student;
RENAME TABLE Student TO Student_Info; -- syntax varies by DBMS
📌 Examples
School database: create a Student table
SQL: CREATE TABLE Student (roll_no INT PRIMARY KEY, name VARCHAR(50) NOT NULL, class VARCHAR(10), dob DATE); — used to define where student records will be stored.
Add new column to track email addresses
SQL: ALTER TABLE Student ADD COLUMN email VARCHAR(100); — modifies schema to hold new information.
Remove an unused table
SQL: DROP TABLE Old_Results; — permanently deletes table structure and data.
Clear all rows but keep table definition
SQL: TRUNCATE TABLE Temp_Entries; — fast removal of all rows (usually not transaction-safe).
Create related tables with foreign key
SQL: CREATE TABLE Course (course_id INT PRIMARY KEY, title VARCHAR(100)); CREATE TABLE Enrollment (enroll_id INT PRIMARY KEY, roll_no INT, course_id INT, FOREIGN KEY (roll_no) REFERENCES Student(roll_no), FOREIGN KEY (course_id) REFERENCES Course(course_id)); — enforces referential integrity.
\[ALTER TABLE table_name DROP COLUMN column_name\]
\[-- syntax may differ by DBMS\]
\[ALTER TABLE table_name RENAME TO new_table_name\]
\[-- or: RENAME TABLE old TO new\]
\[DROP TABLE table_name\]
\[-- permanently deletes structure and data\]
\[TRUNCATE TABLE table_name\]
\[-- removes all rows but keeps structure\]
📊4
Data Manipulation Language (DML)
💻 COMPUTER SCIENCE / IT
Data Manipulation Language (DML)
Key Point: SELECT column_list FROM table_name [WHERE condition] [GROUP BY columns] [HAVING condition] [ORDER BY columns];
Definition: Data Manipulation Language (DML) is the subset of SQL commands used to retrieve, insert, modify and delete data stored in a relational database. DML operations act on table rows and are used in everyday application tasks.
Primary DML commands:
SELECT — retrieve data (reads).
INSERT — add new rows (creates).
UPDATE — change existing rows (modifies).
DELETE — remove rows (deletes).
MERGE — conditional insert/update (upsert) in some RDBMS.
Notes: DML changes the data within tables. Transaction control (COMMIT, ROLLBACK) belongs to TCL — you usually commit or rollback DML operations to make changes permanent or undo them.
Important concepts:
WHERE clause: restricts which rows are affected; omitting WHERE on UPDATE/DELETE affects all rows — use carefully.
SELECT modifiers: ORDER BY, GROUP BY, HAVING, DISTINCT, JOINs and aggregate functions (COUNT, SUM, AVG, MIN, MAX) are commonly used with SELECT.
Transactions: group multiple DML statements into an atomic unit so either all succeed (COMMIT) or none (ROLLBACK).
Permissions: users need appropriate rights (INSERT, UPDATE, DELETE, SELECT) to run DML commands.
Example snippets:
-- SELECT
SELECT student_id, name, marks FROM students WHERE class = 12 ORDER BY marks DESC;
-- INSERT
INSERT INTO students(student_id, name, class, marks)
VALUES (101, 'Asha', 12, 86);
-- UPDATE
UPDATE students SET marks = marks + 5 WHERE student_id = 101;
-- DELETE
DELETE FROM students WHERE student_id = 101;
-- MERGE (pseudo-syntax varies by RDBMS)
MERGE INTO inventory AS tgt
USING (SELECT 'P100' AS code, 50 AS qty) AS src
ON (tgt.code = src.code)
WHEN MATCHED THEN UPDATE SET tgt.qty = tgt.qty + src.qty
WHEN NOT MATCHED THEN INSERT (code, qty) VALUES (src.code, src.qty);
Best practices: always test UPDATE/DELETE with a SELECT using the same WHERE first, use transactions for multi-step changes (especially for financial updates), and add appropriate indexes to speed up SELECTs.
📌 Examples
Student marks retrieval: SELECT name, marks FROM students WHERE class = 12 ORDER BY marks DESC; -- shows Class 12 students sorted by marks.
Add new product to inventory: INSERT INTO products(product_id, name, qty, price) VALUES ('P107', 'USB Cable', 120, 199.00); -- inserts a new product row.
Update inventory after sale (with transaction): BEGIN TRANSACTION; UPDATE products SET qty = qty - 2 WHERE product_id = 'P107'; -- if qty becomes negative or error occurs then ROLLBACK; otherwise COMMIT; -- ensures atomicity for stock updates.
Delete obsolete records: DELETE FROM employees WHERE status = 'resigned' AND resignation_date < '2022-01-01'; -- removes old resigned employees.
Combine data from two tables (read-only DML SELECT with JOIN): SELECT s.name, c.course_name FROM students s JOIN courses c ON s.course_id = c.course_id WHERE c.duration > 6;
🧮 Formulas
\[SELECT column_list FROM table_name [WHERE condition] [GROUP BY columns] [HAVING condition] [ORDER BY columns];\]
\[INSERT INTO table_name (column1\]
\[column2, ...) VALUES (value1\]
\[value2, ...)\]
\[INSERT INTO table_name (col1\]
\[col2, ...) SELECT colA\]
\[colB FROM other_table WHERE ...\]
\[-- insert from query\]
\[UPDATE table_name SET column1 = value1\]
\[column2 = expression WHERE condition\]
\[DELETE FROM table_name WHERE condition\]
\[-- to remove rows\]
\[MERGE INTO target_table USING source_table ON (join_condition) WHEN MATCHED THEN UPDATE ..\]
\[WHEN NOT MATCHED THEN INSERT (...)\]
📊5
Data Control and Transaction Control
💻 COMPUTER SCIENCE / IT
Data Control and Transaction Control
Key Point: GRANT privilege_list ON object TO grantee [ WITH GRANT OPTION ];
Overview
In SQL, controlling access to data and ensuring correctness of multi-step operations are handled by two groups of commands:
Data Control Language (DCL) — commands that grant and revoke privileges on database objects.
Transaction Control Language (TCL) — commands that manage transactions to ensure integrity (ACID properties).
Data Control Language (DCL)
DCL controls who can do what in the database. Typical commands:
GRANT — give specific privileges (SELECT, INSERT, UPDATE, DELETE, ALTER, etc.) to a user or role.
REVOKE — remove previously granted privileges.
Key points:
Privileges can be granted on objects: tables, views, procedures, etc.
WITH GRANT OPTION allows the grantee to pass the same privilege to others.
Revoking a privilege may cascade, removing privileges that were granted by the revoked user if the system supports cascade behavior.
Transaction Control Language (TCL)
TCL commands manage transactions — a transaction is a sequence of SQL statements treated as a single logical unit. Transactions must satisfy ACID:
Atomicity — all steps succeed or none do.
Consistency — transaction moves DB from one valid state to another.
Isolation — concurrent transactions do not interfere (controlled via isolation levels).
Durability — once committed, changes persist even after failures.
Common TCL commands:
START TRANSACTION or BEGIN — begin a transaction (some DBMS implicitly start transactions or use autocommit).
COMMIT — make all changes in the current transaction permanent.
ROLLBACK — undo all changes since the start of the transaction or since a savepoint.
SAVEPOINT name — create a point within a transaction to which you can rollback partially.
ROLLBACK TO SAVEPOINT name — revert changes only back to the savepoint.
How DCL and TCL interact
Privileges (DCL) determine what operations a user can run. TCL ensures that multi-step operations by allowed users are completed reliably. For example, a user with UPDATE privilege can run a transaction that updates several rows; TCL ensures either all rows are updated (COMMIT) or none (ROLLBACK) if an error occurs.
Practical considerations
Many DBMSs run in autocommit mode by default (every statement committed immediately). Disable autocommit for multi-statement transactions.
Use SAVEPOINTs for complex transactions where partial rollback is useful.
Carefully manage GRANT/REVOKE to follow least-privilege principle (give users only necessary rights).
Small example (MySQL-style)
-- Grant read and update on employees table to user1
GRANT SELECT, UPDATE ON company.employees TO 'user1'@'localhost';
-- Start a transaction
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 101; -- debit
UPDATE accounts SET balance = balance + 100 WHERE id = 202; -- credit
-- if both succeed
COMMIT;
-- if an error occurs
ROLLBACK;
Summary
DCL secures who can access or modify database objects. TCL secures how multi-statement changes are applied, making sure operations are atomic, consistent, isolated, and durable.
📌 Examples
GRANT SELECT, INSERT ON school.students TO 'teacher1'@'localhost'; -- Give teacher permission to view and add student records
REVOKE INSERT ON school.students FROM 'teacher1'@'localhost'; -- Remove insert privilege when no longer needed
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE acc_no = 3001;
UPDATE accounts SET balance = balance + 500 WHERE acc_no = 7002;
COMMIT; -- Transfer 500 between two accounts (atomic operation)
START TRANSACTION;
SAVEPOINT deduct_done;
UPDATE inventory SET qty = qty - 1 WHERE item_id = 55;
-- error in subsequent step (e.g., payment failure)
ROLLBACK TO SAVEPOINT deduct_done;
ROLLBACK; -- undo inventory change and abort transaction
Real-life: Bank fund transfer — debit and credit must both happen. Use a transaction so that in case of failure the balances are not inconsistent.
Real-life: E-commerce order processing — create order, reduce stock, charge card; if payment fails, rollback stock and order creation.
🧮 Formulas
\[GRANT privilege_list ON object TO grantee [ WITH GRANT OPTION ];\]
\[REVOKE privilege_list ON object FROM grantee;\]
\[START TRANSACTION\]
\[-- or BEGIN\]
\[-- SQL statements
COMMIT\]
\[-- make changes permanent
-- or
ROLLBACK\]
\[-- undo all changes\]
\[SAVEPOINT savepoint_name\]
\[ROLLBACK TO SAVEPOINT savepoint_name\]
\[-- partial undo\]
\[ACID (properties): Atomicity\]
\[Consistency\]
\[Isolation\]
\[Durability\]
💻6
Constraints and Keys
💻 COMPUTER SCIENCE / IT
Constraints and Keys
Key Point: Functional dependency: A -> B (A determines B) — basis for keys
Overview In SQL a constraint is a rule applied on table columns to enforce data integrity and correctness. Keys are special constraints/attributes used to uniquely identify rows and to establish relationships between tables.
Why they matter Constraints prevent invalid data (e.g., nulls where not allowed, duplicate IDs, or invalid values). Keys let the database enforce uniqueness and referential integrity (e.g., linking orders to customers).
Common constraints
NOT NULL — column must have a value.
UNIQUE — values in a column (or column set) must be distinct.
PRIMARY KEY — combination of NOT NULL + UNIQUE; uniquely identifies a row.
FOREIGN KEY — value(s) in a column must match a primary (or unique) key in another table; enforces referential integrity.
CHECK — enforces a condition (e.g., salary >= 0).
DEFAULT — supplies a default value when none is provided.
Key types (relational concepts)
Superkey — any set of columns that uniquely identifies rows.
Candidate key — minimal superkey (no subset is a superkey).
Primary key — chosen candidate key for row identification.
Alternate key — candidate keys not chosen as primary.
Composite key — primary key made of multiple columns.
Foreign key — references a primary/unique key in another table.
Typical SQL syntax examples
CREATE TABLE Student (
roll_no INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
age INT CHECK (age BETWEEN 5 AND 25)
);
CREATE TABLE Enrollment (
enroll_id INT PRIMARY KEY,
student_roll INT,
course_id INT,
FOREIGN KEY (student_roll) REFERENCES Student(roll_no) ON DELETE CASCADE
);
-- Add constraint later
ALTER TABLE Student ADD CONSTRAINT chk_salary CHECK (salary >= 0);
Behavior & enforcement When data-modifying statements (INSERT/UPDATE/DELETE) would violate a constraint, the DBMS rejects the operation and returns an error. Foreign keys may also specify actions (CASCADE, SET NULL, RESTRICT) for deletes/updates on referenced rows.
📌 Examples
School: Student table uses roll_no as PRIMARY KEY so each student is uniquely identified; class_id in Attendance table is a FOREIGN KEY referencing Class table.
E-commerce: OrderItem table has a composite PRIMARY KEY (order_id, product_id) to uniquely identify an item within an order.
Banking: Account number is UNIQUE and NOT NULL. Transaction.account_no is a FOREIGN KEY referencing Account(account_no) to ensure transactions belong to valid accounts.
HR: Employee.email set as UNIQUE to prevent duplicate email addresses; salary has CHECK (salary >= 0).
Library: BookISBN (PRIMARY KEY) and Issue.book_isbn (FOREIGN KEY) linking issued books to the catalog.
Web app: Users table sets username UNIQUE and password NOT NULL; sessions table references users.id as FOREIGN KEY with ON DELETE CASCADE to remove sessions if a user is deleted.
🧮 Formulas
\[Functional dependency: A -> B (A determines B) — basis for keys\]
\[UNIQUE & NOT NULL combination yields uniqueness and presence requirements\]
💻7
Basic SQL SELECT and Clauses
💻 COMPUTER SCIENCE / IT
Basic SQL SELECT and Clauses
Key Point: SELECT [DISTINCT] column1, column2, ... FROM table_name;
Overview: The SELECT statement is the fundamental SQL command used to retrieve data from one or more tables. It is combined with clauses (FROM, WHERE, GROUP BY, HAVING, ORDER BY, DISTINCT, LIMIT) to filter, group, sort and shape the result set.
Basic syntax:
SELECT <columns> FROM <table> [WHERE <condition>] [GROUP BY <columns>] [HAVING <group_condition>] [ORDER BY <columns> [ASC|DESC]] [LIMIT <n>];
Key parts explained:
SELECT <columns> — list columns or expressions to return. Use * to select all columns.
FROM <table> — the source table(s) or subqueries.
WHERE — row-level filter using comparison (=, <>, <, >, <=, >=), logical operators (AND, OR, NOT), BETWEEN, IN, LIKE.
GROUP BY — aggregate rows into groups (used with aggregate functions like COUNT, SUM, AVG, MIN, MAX).
HAVING — filter groups created by GROUP BY (acts like WHERE but for groups).
ORDER BY — sort result rows by one or more columns (ASC default, DESC for descending).
DISTINCT — remove duplicate rows from the result set.
LIMIT / OFFSET — restrict number of returned rows and paginate.
Aliases (AS) — give temporary names to columns or tables for clarity.
Aggregate functions: COUNT(), SUM(), AVG(), MIN(), MAX(). Aggregates are often used with GROUP BY.
Order of evaluation (conceptual): FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Understanding this helps when writing queries that mix aggregates and row filters.
Best practices: specify explicit column names rather than SELECT * in production; use WHERE to reduce scanned rows; use aliases for readability; test queries with LIMIT during development.
📌 Examples
Example 1 — Select columns: SELECT name, class, marks FROM Students; -- returns name, class and marks for all students
Example 2 — WHERE filter: SELECT name, marks FROM Students WHERE marks >= 80 AND class = '12A'; -- students in class 12A with marks >= 80
Example 3 — DISTINCT: SELECT DISTINCT department FROM Employees; -- list of unique departments
Example 4 — ORDER BY: SELECT product_name, price FROM Products ORDER BY price DESC LIMIT 5; -- top 5 most expensive products
Example 5 — Aggregation and GROUP BY: SELECT class, AVG(marks) AS avg_marks FROM Students GROUP BY class; -- average marks per class
Example 6 — GROUP BY + HAVING: SELECT product_category, SUM(quantity) AS total_sold FROM Sales GROUP BY product_category HAVING total_sold > 100; -- categories with more than 100 items sold
🧮 Formulas
\[SELECT [DISTINCT] column1\]
\[column2, ..\]
\[FROM table_name\]
\[SELECT column_list FROM table WHERE condition1 [AND|OR condition2] [ORDER BY column [ASC|DESC]] [LIMIT n];\]
\[SELECT group_columns\]
\[AGG_FUNC(column) FROM table GROUP BY group_columns [HAVING aggregate_condition]\]
\[-- AGG_FUNC: COUNT\]
\[SUM\]
\[AVG\]
\[MIN\]
\[MAX\]
\[COUNT: SELECT COUNT(*) FROM table WHERE condition\]
\[-- counts rows matching condition\]
\[SUM/AVG: SELECT SUM(amount)\]
\[AVG(amount) FROM Sales WHERE year = 2024\]
\[-- total and average\]
\[Wildcard and pattern: column LIKE 'pattern' -- % (any sequence), _ (single char)\]
\[e.g\]
\[LIKE 'A%'\]
💻8
Filtering and Conditional Operators
💻 COMPUTER SCIENCE / IT
Filtering and Conditional Operators
Key Point: BETWEEN a AND b ≡ value >= a AND value <= b
Overview: Filtering in SQL means selecting only those rows from a table that satisfy a condition. This is done using the WHERE clause and various conditional (comparison and logical) operators. Filtering reduces result sets to relevant data.
Key building blocks:
WHERE clause: Applies conditions to rows. Syntax: SELECT columns FROM table WHERE condition;
Logical operators: AND, OR, NOT to combine or invert conditions.
Range and list tests: BETWEEN ... AND ... (inclusive) and IN (val1, val2,...) (matches any listed value).
Pattern matching: LIKE with wildcards % (zero or more chars) and _ (single char).
NULL checks: Use IS NULL or IS NOT NULL because = NULL does not work.
Existence tests: EXISTS (subquery) checks whether subquery returns any row.
Operator precedence: NOT evaluated first, then AND, then OR. Use parentheses (...) to force grouping.
Examples of use (short snippets):
-- students scoring more than 75
SELECT name, marks FROM Students WHERE marks > 75;
-- employees in Sales with salary >= 50000
SELECT emp_id, name FROM Employees WHERE dept = 'Sales' AND salary >= 50000;
-- products priced between 100 and 500
SELECT prod_id, price FROM Products WHERE price BETWEEN 100 AND 500;
-- customers whose name starts with 'A'
SELECT name FROM Customers WHERE name LIKE 'A%';
-- orders with NULL delivery_date
SELECT order_id FROM Orders WHERE delivery_date IS NULL;
-- rows where a related record exists
SELECT c.customer_id FROM Customers c WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.customer_id = c.customer_id);
Good practices:
Use parentheses for clarity when combining multiple logical operators.
Prefer indexed columns for WHERE conditions to improve performance.
Use EXISTS for correlated-subquery existence checks; use IN for small lists.
📌 Examples
Select students with marks above 90: SELECT roll_no, name FROM Students WHERE marks > 90;
Find employees in departments 'HR' or 'Finance': SELECT emp_id, name FROM Employees WHERE dept IN ('HR','Finance');
List products with price between 50 and 200: SELECT prod_id, name FROM Products WHERE price BETWEEN 50 AND 200;
Retrieve customers whose email ends with '@gmail.com': SELECT name, email FROM Customers WHERE email LIKE '%@gmail.com';
Get orders that are not delivered: SELECT order_id FROM Orders WHERE delivery_status <> 'Delivered' OR delivery_date IS NULL;
🧮 Formulas
\[BETWEEN a AND b ≡ value >= a AND value <= b\]
\[value IN (v1\]
\[v2\]
\[v3) ≡ value = v1 OR value = v2 OR value = v3\]
\[LIKE 'abc%' matches any string that starts with 'abc' (e.g., 'abcd')\]
\[LIKE '%xyz' matches strings that end with 'xyz' (e.g., 'axyz')\]
\[Precedence: NOT > AND > OR (use parentheses to change evaluation order)\]
\[Truth table (AND): true AND true = true\]
\[otherwise false\]
💻9
Aggregate Functions and Grouping
📐 MATHEMATICAL FORMULA / THEOREM
Aggregate Functions and Grouping
Key Point: COUNT(*) — counts all rows, including rows with NULL values in other columns. Syntax: SELECT COUNT(*) FROM table;
What are Aggregate Functions? Aggregate functions perform calculations on a set of rows and return a single value. They are used to summarize data. Common aggregate functions in SQL are COUNT, SUM, AVG, MIN, and MAX. Aggregate functions ignore NULL values except where noted (e.g., COUNT(*) counts rows including NULLs).
Basic usage (no grouping) When used without GROUP BY, an aggregate function computes a result across all selected rows. Example: SELECT AVG(marks) FROM Students; returns the average marks of all students.
Grouping rows: GROUP BY GROUP BY divides rows into groups based on the values of one or more columns. Aggregate functions then compute a value per group. Example: SELECT class, AVG(marks) FROM Students GROUP BY class; computes the average marks for each class.
Filtering groups: HAVING vs WHERE Use WHERE to filter rows before aggregation. Use HAVING to filter groups after aggregation. Example: SELECT class, COUNT(*) FROM Students GROUP BY class HAVING COUNT(*) > 30; lists classes with more than 30 students.
Multiple aggregates and grouping columns You can compute several aggregates at once and group by multiple columns: SELECT department, gender, AVG(salary), MAX(salary) FROM Employees GROUP BY department, gender;
NULL behavior and DISTINCT NULL values are ignored by SUM, AVG, MIN, MAX. Use COUNT(*) to count all rows; use COUNT(column) to count non-NULL values. Use DISTINCT inside aggregates to remove duplicates, e.g. COUNT(DISTINCT city).
Examples of SQL patterns
-- Aggregate across whole table
SELECT COUNT(*) AS total_students, AVG(marks) AS avg_marks FROM Students;
-- Grouping
SELECT class, AVG(marks) AS avg_marks
FROM Students
GROUP BY class
ORDER BY avg_marks DESC;
-- Grouping with HAVING
SELECT product_category, SUM(units_sold) AS total_units
FROM Sales
GROUP BY product_category
HAVING SUM(units_sold) > 1000;
-- Multiple grouping columns
SELECT region, product, SUM(revenue) FROM Sales
GROUP BY region, product;
When to use Aggregate functions and grouping are used whenever you need summary statistics: totals, averages, counts, minima/maxima per category, distributions, comparisons between groups, etc. They are essential in reports, dashboards and data analysis.
📌 Examples
Example 1 — Student average by class: SQL: SELECT class, ROUND(AVG(marks),2) AS avg_marks FROM Students GROUP BY class ORDER BY class; Explanation: Computes the average marks for each class.
Example 2 — Monthly sales total: SQL: SELECT MONTH(sale_date) AS month, SUM(amount) AS total_sales FROM Sales WHERE YEAR(sale_date)=2024 GROUP BY MONTH(sale_date) ORDER BY month; Explanation: Gives total sales per month for 2024.
Example 3 — Number of employees per department with more than 10 employees: SQL: SELECT department, COUNT(*) AS emp_count FROM Employees GROUP BY department HAVING COUNT(*) > 10; Explanation: Lists departments whose employee count exceeds 10.
Example 4 — Distinct cities served: SQL: SELECT COUNT(DISTINCT city) AS cities_served FROM Customers; Explanation: Counts unique cities in Customers table.
Example 5 — Highest and lowest salary by department: SQL: SELECT department, MAX(salary) AS max_sal, MIN(salary) AS min_sal FROM Employees GROUP BY department; Explanation: Finds salary range in each department.
🧮 Formulas
\[COUNT(*) — counts all rows\]
\[including rows with NULL values in other columns\]
\[Syntax: SELECT COUNT(*) FROM table\]
\[COUNT(column) — counts non-NULL values in a column\]
Overview Scalar (built-in) functions in SQL are predefined routines that take one or more input values (usually from a single row) and return a single value. They are applied to individual column values and are different from aggregate functions (like SUM, AVG) that work on groups of rows.
Key characteristics
Operate on a single value (per row) and return one result per row.
Used in SELECT lists, WHERE, ORDER BY, HAVING, and expressions.
Built-in categories: string, numeric, date/time, conversion, NULL-handling and system functions.
Many SQL dialects (MySQL, Oracle, SQL Server) provide similar functions but names/syntax can differ slightly.
Conditional: return conditional results. Example: CASE ... WHEN ... THEN ... END.
How they are used (patterns)
Normalizing data: SELECT UPPER(name) FROM students; ensures consistent casing before grouping or comparing.
Formatting output: SELECT TO_CHAR(join_date, 'DD-MON-YYYY') FROM employees;
Calculations per row: SELECT salary, ROUND(salary * 0.12, 2) AS tax FROM employees;
Nesting functions: SELECT UPPER(SUBSTR(name,1,1)) FROM students;
NULL handling: SELECT COALESCE(mobile, 'Not Given') FROM contacts;
Important notes
Order and nesting matter: functions are evaluated from inner to outer.
Functions may return NULL if input is NULL (unless specifically handling NULLs with COALESCE/NVL).
Performance: using functions on columns in WHERE clauses can prevent index usage (e.g., avoid WHERE UPPER(col) = 'X' on large indexed tables; better store normalized data or use functional indexes).
Short example queries (conceptual)
-- Show students with formatted names and rounded percentages
SELECT id,
UPPER(name) AS name_upper,
ROUND(marks * 100.0 / max_marks, 2) AS percent
FROM students;
-- Fill missing phone numbers
SELECT id, name, COALESCE(phone, 'No Phone') FROM students;
-- Create a marks-range label
SELECT CASE
WHEN marks >= 90 THEN '90+'
WHEN marks >= 80 THEN '80-89'
WHEN marks >= 70 THEN '70-79'
ELSE 'Below 70'
END AS range_label,
COUNT(*)
FROM students
GROUP BY range_label;
This covers the essentials of scalar and built-in functions for Class 12 Computer Science: what they do, major types, usage patterns, and best practices.
📌 Examples
Normalize names before grouping: SELECT UPPER(name) AS name_norm, COUNT(*) FROM students GROUP BY UPPER(name);
Calculate tax per employee: SELECT emp_id, salary, ROUND(salary * 0.12, 2) AS tax FROM employees;
Replace NULL mobile numbers: SELECT id, name, COALESCE(mobile, 'Not Given') FROM contacts;
Extract year of joining: SELECT name, EXTRACT(YEAR FROM join_date) AS join_year FROM employees;
Student marks range distribution: SELECT CASE WHEN marks >= 90 THEN '90+' WHEN marks >=80 THEN '80-89' WHEN marks >=70 THEN '70-79' ELSE 'Below 70' END AS range, COUNT(*) FROM students GROUP BY range ORDER BY range;
🧮 Formulas
\[String: UPPER(column)\]
\[LOWER(column)\]
\[LENGTH(column)\]
\[SUBSTR(column\]
\[start\]
\[length)\]
\[CONCAT(a,b)\]
\[Numeric: ABS(expr)\]
\[ROUND(expr\]
\[n)\]
\[CEIL(expr)\]
\[FLOOR(expr)\]
\[MOD(a,b)\]
\[POWER(a,b)\]
\[SQRT(expr)\]
\[Date/time: CURRENT_DATE\]
\[NOW()\]
\[EXTRACT(part FROM date)\]
\[DATE_ADD(date\]
\[INTERVAL n DAY) (MySQL)\]
\[ADD_MONTHS(date\]
\[n) (Oracle)\]
\[Conversion: CAST(expr AS datatype)\]
\[TO_CHAR(date, 'format')\]
\[TO_DATE('str','format')\]
\[NULL handling: COALESCE(a\]
\[b, ...)\]
\[NVL(a\]
\[b) (Oracle)\]
\[NULLIF(a,b)\]
\[Conditional: CASE WHEN condition THEN result [WHEN ...] [ELSE result] END\]
💻11
Joins and Related Concepts
💻 COMPUTER SCIENCE / IT
Joins and Related Concepts
Key Point: Cartesian product size: |A × B| = |A| × |B| (if A has m rows and B has n rows, result has m × n rows).
What is a JOIN? A JOIN combines rows from two (or more) tables based on a related column between them. Joins let you query related data stored separately (for normalization) and present it as a single result set.
Core idea: When two tables are joined, rows are matched by a condition (usually equality on keys). If no condition is specified, the result is a Cartesian product (every row of table A paired with every row of table B).
Common types of joins:
INNER JOIN (Equijoin) — returns rows that have matching values in both tables. Syntax: SELECT ... FROM A INNER JOIN B ON A.key = B.key. This is the most used join.
CROSS JOIN — Cartesian product. If A has m rows and B has n rows, result has m × n rows. Syntax: FROM A CROSS JOIN B or FROM A, B (comma form).
LEFT (OUTER) JOIN — returns all rows from the left table; matched rows from the right table; unmatched right columns are NULL. Syntax: FROM A LEFT JOIN B ON ....
RIGHT (OUTER) JOIN — returns all rows from the right table; matched rows from the left table; unmatched left columns are NULL. Syntax: FROM A RIGHT JOIN B ON ....
FULL (OUTER) JOIN — returns rows when there is a match in either table; unmatched columns from either side are NULL. Syntax: FROM A FULL JOIN B ON ... (supported in many DBMS).
SELF JOIN — a table joined with itself. Useful for hierarchical or comparative queries. Use table aliases to distinguish the two instances.
NATURAL JOIN — automatically joins using all columns with the same names in both tables. Use with care (implicit columns can cause unexpected matches).
THETA / NON-EQUI JOIN — join with a condition other than equality, e.g., A.value > B.limit.
Related concepts:
Primary key / Foreign key — foreign keys define referential relationships used for joins (e.g., student_id in Enrollment references Student(id)).
Referential integrity — ensures that foreign key values match primary key values (or are NULL), keeping joins meaningful.
NULL handling — outer joins produce NULLs for missing matches; use COALESCE() or IS NULL checks to handle them.
Using ON vs USING — ON allows arbitrary join conditions; USING (col) simplifies syntax when both tables share the same column name and you want to join on it.
Performance — indexes on join columns speed up joins. Join order and query plan matter for large tables.
Notes for Class 12 level:
INNER JOIN is the same as writing explicit equality conditions (equijoin).
Cartesian product (CROSS JOIN) is rarely useful directly, but important to understand as the default when no condition is provided.
Outer joins are used when you want to retain non-matching rows from one or both tables.
📌 Examples
Students and Enrollments (INNER JOIN):
Tables: Students(id, name), Enrollments(student_id, course_id)
Query: SELECT S.id, S.name, E.course_id FROM Students S INNER JOIN Enrollments E ON S.id = E.student_id;
Description: Lists only students who are enrolled in at least one course.
Students and Enrollments (LEFT JOIN):
Query: SELECT S.id, S.name, E.course_id FROM Students S LEFT JOIN Enrollments E ON S.id = E.student_id;
Description: Lists all students; students with no enrollments will show NULL for course_id.
Employees and Departments (RIGHT JOIN example):
Tables: Employees(emp_id, name, dept_id), Departments(dept_id, dept_name)
Query: SELECT E.name, D.dept_name FROM Employees E RIGHT JOIN Departments D ON E.dept_id = D.dept_id;
Description: Lists all departments; departments without employees show NULL for employee name.
Products and Suppliers (CROSS JOIN example):
Tables: Products(p_id, p_name), Suppliers(s_id, s_name)
Query: SELECT P.p_name, S.s_name FROM Products P CROSS JOIN Suppliers S;
Description: Pairs every product with every supplier (m × n rows).
Self join to find manager names:
Table: Employees(emp_id, name, manager_id)
Query: SELECT E.name AS employee, M.name AS manager FROM Employees E LEFT JOIN Employees M ON E.manager_id = M.emp_id;
Description: Shows each employee with their manager name; NULL if no manager.
NATURAL JOIN (use cautiously):
Tables: A(id, name, dept), B(id, dept, salary)
Query: SELECT * FROM A NATURAL JOIN B;
Description: Joins on all columns with same names (here: id and dept).
🧮 Formulas
\[Cartesian product size: |A × B| = |A| × |B| (if A has m rows and B has n rows\]
\[result has m × n rows).\]
\[INNER JOIN syntax (equijoin): SELECT columns FROM A INNER JOIN B ON A.key = B.key;\]
\[LEFT JOIN syntax: SELECT columns FROM A LEFT JOIN B ON A.key = B.key\]
\[(All rows from A retained.)\]
\[RIGHT JOIN syntax: SELECT columns FROM A RIGHT JOIN B ON A.key = B.key\]
\[(All rows from B retained.)\]
\[FULL JOIN syntax: SELECT columns FROM A FULL JOIN B ON A.key = B.key\]
\[(Rows from either side retained.)\]
\[SELF JOIN syntax: SELECT A.col\]
\[B.col FROM Table A JOIN Table B ON A.some = B.some\]
\[(A and B are aliases of same table.)\]
💻12
Subqueries
💻 COMPUTER SCIENCE / IT
Subqueries
Key Point: Scalar subquery: SELECT ... WHERE column = (SELECT aggregate FROM table WHERE ...)
What is a subquery? A subquery (also called an inner query or nested query) is a SELECT statement placed inside another SQL statement (the outer query). The subquery returns a value or a set of values that the outer query uses to filter, compare or compute results.
Why use subqueries? They let you break complex questions into simpler parts, compute values (like averages, maxima) on the fly, and write queries that depend on results of other queries without creating temporary tables.
Types of subqueries
Non-correlated (independent) subquery: runs once and its result is used by the outer query.
Correlated subquery: references columns from the outer query and is re-evaluated for each row of the outer query.
Scalar subquery: returns exactly one value (one row, one column) and can be used wherever an expression is allowed.
Row subquery: returns one row with multiple columns and can be used in comparisons like (col1, col2) = (subquery).
Multiple-row subquery: returns many rows; used with IN, ANY, ALL, EXISTS, etc.
Common operators with subqueries
IN (list of values): col IN (subquery)
= : col = (scalar subquery)
ANY / SOME : col > ANY (subquery) — true if col is greater than at least one returned value
ALL : col > ALL (subquery) — true if col is greater than every returned value
EXISTS : EXISTS (subquery) — true if subquery returns at least one row (often used with correlated subqueries)
Syntax examples
-- Non-correlated scalar subquery
SELECT student_name
FROM students
WHERE marks > (SELECT AVG(marks) FROM students);
-- Correlated subquery: employees with salary > department average
SELECT e.emp_name, e.salary, e.dept_id
FROM employee e
WHERE e.salary > (SELECT AVG(salary) FROM employee WHERE dept_id = e.dept_id);
-- EXISTS example: customers who placed at least one order
SELECT customer_id, name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
-- IN example: products not sold
SELECT product_name
FROM product
WHERE product_id NOT IN (SELECT product_id FROM sales);
Notes & best practices
Use scalar subqueries only when you are sure they return one value (or use an aggregate that returns a single value).
EXISTS with correlated subqueries can be faster than IN for large tables, because EXISTS stops at the first match.
Avoid SELECT * in subqueries; select only needed columns (often SELECT 1 or a single column).
Be careful with NULLs—IN with NULLs behaves differently; EXISTS ignores returned column values and tests row existence.
📌 Examples
Find students scoring above the class average:
SELECT name, marks FROM students WHERE marks > (SELECT AVG(marks) FROM students);
Employees earning more than their department average (correlated subquery):
SELECT e.emp_name, e.salary FROM employee e WHERE e.salary > (SELECT AVG(salary) FROM employee WHERE dept_id = e.dept_id);
List customers who have made at least one order (EXISTS):
SELECT customer_id, name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
Products that have never been sold (NOT IN):
SELECT product_name FROM product WHERE product_id NOT IN (SELECT product_id FROM sales);
Find the student with the highest marks (scalar subquery):
SELECT name FROM students WHERE marks = (SELECT MAX(marks) FROM students);
Find items priced greater than every item in category 'A' (ALL):
SELECT item_name FROM items WHERE price > ALL (SELECT price FROM items WHERE category = 'A');
🧮 Formulas
\[Scalar subquery: SELECT ..\]
\[WHERE column = (SELECT aggregate FROM table WHERE ...)\]
\[Multiple-row IN: WHERE column IN (SELECT column FROM table WHERE ...)\]
\[EXISTS (correlated): WHERE EXISTS (SELECT 1 FROM other WHERE other.key = outer.key AND ...)\]
\[ANY / SOME: WHERE column > ANY (SELECT column FROM table WHERE ...)\]
\[ALL: WHERE column > ALL (SELECT column FROM table WHERE ...)\]
⚖️13
Set Operations
💻 COMPUTER SCIENCE / IT
Set Operations
Key Point: A ∪ B (set union) ↔ SELECT ... FROM A
UNION
SELECT ... FROM B
Overview Set operations in SQL combine the result sets of two or more SELECT queries as if they were mathematical sets. The main operations are UNION, UNION ALL, INTERSECT, and EXCEPT (called MINUS in Oracle). They let you merge, intersect, or subtract rows returned by separate queries.
Requirements
Each SELECT must return the same number of columns.
Corresponding columns must have compatible data types (SQL will implicit-cast if possible).
Column names in the final result are taken from the first SELECT (some DBs allow aliasing the final result).
Behavior of each operation
UNION: returns unique rows present in either result; duplicates are removed (equivalent to set union).
UNION ALL: returns all rows from both results, including duplicates (multiset union).
INTERSECT: returns rows common to both results; duplicates removed (set intersection).
EXCEPT / MINUS: returns rows in the first result that are not in the second; duplicates removed (set difference).
Notes & edge cases
ORDER BY applies to the final combined result; in many DBs it must appear once at the end (after the last SELECT and operation).
NULLs: for set-operation duplicate elimination, NULLs are treated as equal (i.e., two rows that differ only by NULL in the same column are considered duplicates).
Some DBMS (Postgres) support INTERSECT ALL and EXCEPT ALL for multiset behavior; others do not.
Performance: UNION/INTERSECT/EXCEPT typically require sorting or hashing to remove duplicates — UNION ALL is faster because it skips deduplication.
Common syntax
SELECT col1, col2, ... FROM tableA
UNION [ALL]
SELECT col1, col2, ... FROM tableB
[ORDER BY col1];
-- INTERSECT
SELECT ... FROM tableA
INTERSECT
SELECT ... FROM tableB;
-- EXCEPT (or MINUS in Oracle)
SELECT ... FROM tableA
EXCEPT
SELECT ... FROM tableB;
When to use
UNION to merge non-overlapping lists (e.g., two departments' employee lists) while removing duplicates.
UNION ALL to concatenate results when duplicates are meaningful (e.g., aggregating event logs from two sources).
INTERSECT to find common entries (e.g., students enrolled in both course A and B).
EXCEPT to get exclusive items (e.g., customers who purchased in January but not in February).
📌 Examples
Merge customer lists from two months (remove duplicates):
SELECT customer_id, name FROM jan_customers
UNION
SELECT customer_id, name FROM feb_customers;
Concatenate logs from two servers keeping duplicates (each occurrence matters):
SELECT event_time, message FROM server1_logs
UNION ALL
SELECT event_time, message FROM server2_logs;
Find students enrolled in both Math and Physics:
SELECT student_id FROM math_enrollments
INTERSECT
SELECT student_id FROM physics_enrollments;
Find customers who bought in January but NOT in February (exclusive):
SELECT customer_id FROM jan_customers
EXCEPT
SELECT customer_id FROM feb_customers;
-- In Oracle use MINUS instead of EXCEPT
Keep only rows with exactly the same columns/types: queries must match column count and compatible types. Example of aliasing final result columns:
SELECT id AS student_id, name FROM table1
UNION
SELECT id, name FROM table2
ORDER BY student_id;
\[For UNION ALL (multiset): |A ∪_all B| = |A| + |B|\]
💻14
Views and Virtual Tables
💻 COMPUTER SCIENCE / IT
Views and Virtual Tables
Key Point: Create view (syntax template): CREATE VIEW view_name AS SELECT column_list FROM table_list WHERE conditions;
What is a View (Virtual Table)?
A view is a saved SQL query treated like a table. It does not store rows itself (unless materialized) but provides a virtual representation of data derived from one or more base tables. When you query a view, the DBMS runs the underlying SELECT and returns the result as if it were a table.
Why use Views?
Security: expose only selected columns/rows to users (hide sensitive data).
Simplicity: present a complex join/aggregation as a simple table for users.
Reusability & maintenance: centralize complex queries in one object.
Logical data independence: change base table structure internally while keeping view interface stable.
Types of Views
Simple (updatable) view: Derived from a single table, without GROUP BY, DISTINCT, aggregate functions or joins — often updatable.
Complex (non-updatable) view: Uses joins, aggregates, GROUP BY, DISTINCT — usually not updatable.
Materialized view (summary table): Stores results physically and must be refreshed; used for performance (note: not every DBMS uses materialized views under the generic name "view").
Updatable Views & Rules
An INSERT/UPDATE/DELETE on a view affects base tables only when the view is updatable.
Typical conditions for updatability: the view references a single base table, contains key columns, and does not contain aggregates, DISTINCT, GROUP BY, or set operations.
WITH CHECK OPTION: ensures modifications through the view remain visible in the view (row must satisfy the view's WHERE clause).
How Views Work (conceptual flow)
User issues: SELECT * FROM view_name;
DBMS retrieves the stored view definition (the SELECT statement).
DBMS substitutes the view SELECT into the user query and executes against base tables.
Result set returned to user as if from a table.
Advantages
Improved security and simpler user interface.
Encapsulation of complex logic; easier reporting.
Consistent data presentation across applications.
Limitations
Performance: complex views executed repeatedly can be slow (materialized views mitigate this).
Not all views are updatable.
Dependency: dropping/changing base tables can invalidate views.
Common SQL Statements
-- Create a view
CREATE VIEW view_name AS
SELECT column_list
FROM table1 [JOIN table2 ...]
WHERE conditions;
-- Select from a view
SELECT * FROM view_name;
-- Create an updatable view with CHECK OPTION
CREATE VIEW dept_emps AS
SELECT emp_id, name, dept_id, salary
FROM employees
WHERE dept_id = 10
WITH READ ONLY; -- or WITH CHECK OPTION
-- Drop a view
DROP VIEW view_name;
Summary
Views are virtual tables — saved queries that present data from base tables in a convenient, secure and reusable way. They improve logical data independence but have rules and performance considerations for updates.
📌 Examples
Example 1 — Simple view: Hide salaries from students
SQL:
CREATE VIEW StudentContact AS
SELECT student_id, name, email, phone
FROM Students;
Usage:
SELECT * FROM StudentContact; -- shows contact details without marks or fees fields
Example 2 — Department-wise employees using join
SQL:
CREATE VIEW DeptEmp AS
SELECT e.emp_id, e.name, d.dept_name
FROM Employees e JOIN Departments d ON e.dept_id = d.dept_id
WHERE d.dept_name = 'Accounts';
Usage:
SELECT * FROM DeptEmp; -- list of employees in Accounts
Example 3 — View with aggregation (non-updatable)
SQL:
CREATE VIEW CourseEnrollment AS
SELECT course_id, COUNT(student_id) AS enrolled_students
FROM Enrollments
GROUP BY course_id;
Usage:
SELECT * FROM CourseEnrollment; -- shows enrollment counts; cannot INSERT into this view
Example 4 — View with WITH CHECK OPTION
SQL:
CREATE VIEW SalesRegion AS
SELECT order_id, cust_id, amount
FROM Orders
WHERE region = 'North'
WITH CHECK OPTION;
Effect:
Any INSERT/UPDATE through SalesRegion must have region = 'North', otherwise it is rejected.
Example 5 — Masking sensitive data (security)
SQL:
CREATE VIEW PublicEmployees AS
SELECT emp_id, name, department, '***' AS ssn_masked
FROM Employees;
Effect:
Users of PublicEmployees cannot see real SSN values.
🧮 Formulas
\[Create view (syntax template): CREATE VIEW view_name AS SELECT column_list FROM table_list WHERE conditions;\]
\[Updatable view requirement (informal rule): view SELECT must reference a single base table + no GROUP BY/DISTINCT/aggregates + include key columns (DBMS-specific).\]
\[WITH CHECK OPTION (syntax): CREATE VIEW view_name AS SELECT ..\]
\[WHERE ..\]
\[WITH CHECK OPTION\]
\[Drop view: DROP VIEW view_name;\]
💻15
Indexes
💻 COMPUTER SCIENCE / IT
Indexes
Key Point: Selectivity = distinct_values_in_column / total_rows (closer to 0 means low selectivity; closer to 1 means high selectivity).
What is an index? An index is a database structure that improves the speed of data retrieval operations on a table by providing quick access paths to rows. It works like the index at the back of a book: instead of scanning every page (row), the index points you to the exact pages (row locations).
Why use indexes? Indexes reduce the number of disk reads and CPU operations required to satisfy queries (especially SELECT with WHERE, JOINs and ORDER BY). They are essential for performance when tables grow large.
How indexes are organized Most DBMS use B-tree (balanced tree) or hash structures for indexes:
B-tree (or B+ tree): A balanced tree where leaf nodes contain pointers to rows. Good for range queries, ORDER BY and equality searches. Typical lookup cost: O(log n).
Hash index: Uses a hash table for direct equality lookups. Very fast for exact-match queries (approaching O(1)), but cannot support range queries.
Types of indexes
Primary key index: Automatically created by most DBMS for primary key columns; enforces uniqueness.
Non-unique (regular) index: Speeds lookups but allows duplicates.
Composite (multi-column) index: Index on two or more columns; useful when queries filter on multiple columns together.
Clustered vs Non-clustered: Clustered index defines the physical order of rows (one per table). Non-clustered index stores pointers to rows and many can exist.
How a query uses an index When a query has a WHERE clause on an indexed column, the optimizer can choose the index. The DBMS traverses the index (e.g., B-tree) to find the row location(s) and then fetches the full row from the table if needed. If the index contains all columns needed by the query (covering index), the DBMS can return results directly from the index without reading the table data.
Advantages
Faster SELECT queries and quicker JOINs.
Enforced uniqueness when using unique indexes.
Can speed ORDER BY and GROUP BY when index order matches.
Poor choice of indexes can degrade performance (too many or low-selectivity indexes).
When to create an index (guidelines)
Columns frequently used in WHERE, JOIN, ORDER BY or GROUP BY.
Columns with high selectivity (many distinct values).
Avoid indexing small lookup tables where full table scans are cheaper.
SQL syntax (examples)
-- Create a simple index
CREATE INDEX idx_student_name ON Student(name);
-- Create a unique index
CREATE UNIQUE INDEX idx_student_email ON Student(email);
-- Create a composite index
CREATE INDEX idx_product_cat_price ON Product(category_id, price);
-- Drop an index (syntax varies by DBMS)
DROP INDEX idx_student_name; -- MySQL: DROP INDEX idx_student_name ON Student;
Practical tips
Prefer indexes on columns used in selective WHERE conditions.
Use composite indexes to match the leading column order of query predicates.
Monitor index usage and remove unused indexes to save space and reduce write overhead.
Use EXPLAIN (or EXPLAIN PLAN) to check whether queries use an index.
📌 Examples
Library catalog: An index on 'author' and 'title' lets you quickly find all books by an author without scanning the entire collection.
Student table: CREATE INDEX idx_student_name ON Student(name); — Speeds up: SELECT * FROM Student WHERE name='Rahul';
Unique constraint: CREATE UNIQUE INDEX idx_student_email ON Student(email); — Prevents duplicate emails and speeds lookups by email.
Composite index for multi-column filter: CREATE INDEX idx_order_customer_date ON Orders(customer_id, order_date); — Speeds queries filtering by customer and date range.
E-commerce search: Index on Product(category_id, price) helps queries like SELECT * FROM Product WHERE category_id=5 AND price BETWEEN 100 AND 500;
🧮 Formulas
\[Selectivity = distinct_values_in_column / total_rows (closer to 0 means low selectivity\]
\[closer to 1 means high selectivity).\]
\[B-tree lookup cost ≈ O(log n) (n = number of index entries).\]
\[Hash lookup cost for equality ≈ O(1) on average (not usable for range queries).\]
\[Index storage estimate ≈ rows * (key_size + pointer_size) — gives a rough idea of index size.\]
\[Estimated pages for index ≈ ceil(index_size / page_size) — used for disk I/O cost estimates.\]
💻16
NULLs and Conditional Logic
💻 COMPUTER SCIENCE / IT
NULLs and Conditional Logic
Key Point: IS NULL / IS NOT NULL — tests for NULL; example: column IS NULL
What is NULL? NULL represents the absence of a value in a column — not the same as an empty string (''), a space, or zero. It means “unknown” or “not applicable.”
Key differences
NULL <> '' (empty string) and NULL <> 0 (zero).
Arithmetic or comparison with NULL yields UNKNOWN (three-valued logic): TRUE, FALSE, UNKNOWN.
Three-valued logic (brief) When SQL evaluates expressions with NULL, results can be TRUE, FALSE or UNKNOWN. WHERE filters keep only TRUE rows; UNKNOWN behaves like FALSE in WHERE and HAVING clauses.
Testing NULL
Use IS NULL and IS NOT NULL. Do not use = NULL or <> NULL — they return UNKNOWN.
Common NULL-handling functions
COALESCE(expr1, expr2, ...) — returns the first non-NULL argument.
Conditional logic in SQL
CASE is the standard conditional expression:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result_default
END
It permits multiple conditions and returns the first matching THEN value. DECODE (Oracle) and IIF (some systems) provide shortcuts.
How NULL interacts with conditional logic
A CASE WHEN column = value THEN ... will not match when column is NULL. To handle NULL explicitly, use WHEN column IS NULL THEN ....
COALESCE and NVL let you supply defaults for NULL inside CASE or SELECT projections (useful for display).
Aggregates: functions like SUM, AVG, COUNT(column) ignore NULLs. Use COUNT(*) to count rows regardless of NULLs.
Examples of usage (short)
-- Find rows with missing phone number
SELECT id, name FROM students WHERE phone IS NULL;
-- Replace NULL with default in output
SELECT name, COALESCE(phone, 'NoPhone') AS phone_display FROM students;
-- Conditional grade with NULL marks
SELECT name,
CASE
WHEN marks IS NULL THEN 'Absent'
WHEN marks >= 90 THEN 'A+'
WHEN marks >= 75 THEN 'A'
ELSE 'B or below'
END AS grade
FROM exam_results;
-- Avoid division by NULL (or NULL result)
SELECT id, total, COALESCE(total,0)/NULLIF(count,0) AS avg_per_item
FROM purchases;
Practical notes
Use IS NULL in WHERE/HAVING, and COALESCE/NVL when you want default display values.
Be careful with joins: outer joins produce NULLs for missing matching rows (e.g., customers with no orders).
Remember aggregates ignore NULLs — that affects averages and counts.
Concise summary: NULL means unknown/absent. Use IS NULL/IS NOT NULL to test. Use COALESCE/NVL/IFNULL to provide defaults. Use CASE for rich conditional logic and explicitly handle NULL when needed.
📌 Examples
Real-life: Customer table where some customers have no secondary phone. Query to list those customers: SELECT id, name FROM customers WHERE secondary_phone IS NULL;
Student marks: Mark NULL means absent. Use CASE to show 'Absent' explicitly: SELECT name, CASE WHEN marks IS NULL THEN 'Absent' WHEN marks>=33 THEN 'Pass' ELSE 'Fail' END AS result FROM students;
E-commerce: Delivery date may be NULL if not shipped. Use COALESCE to show 'Pending': SELECT order_id, COALESCE(delivery_date, 'Pending') AS delivery_status FROM orders;
Avoid divide-by-zero/NULL: SELECT order_id, total, COALESCE(total,0)/NULLIF(items,0) AS per_item FROM orders; -- NULLIF(items,0) returns NULL if items=0, preventing divide-by-zero
Outer join producing NULLs: List all employees and their manager names (NULL if no manager): SELECT e.name AS emp, m.name AS mgr FROM emp e LEFT JOIN emp m ON e.manager_id=m.id;
🧮 Formulas
\[IS NULL / IS NOT NULL — tests for NULL\]
\[example: column IS NULL\]
\[COALESCE(expr1\]
\[expr2, ...) — returns first non-NULL argument\]
\[NVL(expr\]
\[replacement) — Oracle shorthand to replace NULL (similar to COALESCE with two args)\]
\[IFNULL(expr\]
\[replacement) / ISNULL(expr\]
\[replacement) — MySQL/SQLServer replacements\]
\[NULLIF(expr1\]
\[expr2) — returns NULL if expr1 = expr2\]
\[else returns expr1\]
\[CASE WHEN condition THEN value [WHEN ...] [ELSE value] END — conditional expression\]
💻17
Aliases, Expressions and Formatting
💻 COMPUTER SCIENCE / IT
Aliases, Expressions and Formatting
Key Point: Column alias: SELECT expression AS alias
Overview In SQL, aliases, expressions and formatting are used to make query results readable, compute values on-the-fly, and present values in a desired visual form. These features are temporary and affect only the result set (they do not rename columns or tables permanently).
Aliases A column alias gives a temporary name to a column or expression in the output. A table alias gives a short name for a table reference (useful in joins and when the table name is long).
Syntax (column): SELECT column_expression AS alias or SELECT column_expression alias
Syntax (table): FROM table_name AS t or FROM table_name t
Usage notes: Aliases improve readability and are required when the SELECT item is an expression. Aliases generally cannot be used in the WHERE clause of the same SELECT (use a subquery or repeat the expression). Many DBMS allow aliases in ORDER BY.
Expressions Expressions are computations inside SELECT (or WHERE, HAVING, ORDER BY). They include arithmetic, string operations, date arithmetic, aggregate expressions and conditional expressions.
Date: add/subtract intervals — order_date + INTERVAL '7' DAY (some DBs) or DATEADD(day,7,order_date) (SQL Server)
Conditional: CASE WHEN score >= 90 THEN 'A' WHEN ... END
Aggregate expressions: sums and averages with aliases: SUM(amount) AS total_sales
Formatting Formatting changes how values appear — rounding numbers, adding currency symbols, padding text, formatting dates. Different DBMS provide different functions; common ones:
ROUND(number, decimals) — round numeric values
CAST(expr AS type) / CONVERT(...) — change data type
TO_CHAR(date,'DD-MON-YYYY') (Oracle) or DATE_FORMAT(date, '%d-%m-%Y') (MySQL) — format dates
LPAD, RPAD — pad strings; TRIM, UPPER, LOWER — text formatting
Practical rules
Use aliases to clarify column headings in result sets (e.g., AS Total_Marks).
If you need to use a computed column in WHERE/GROUP BY, either repeat the expression or wrap the SELECT as a subquery and filter/aggregate outside.
Be aware of DBMS-specific functions (TO_CHAR vs FORMAT vs DATE_FORMAT).
Example explanation (quick) To compute and present student percentage with a clean heading:
SELECT roll_no,
(marks1+marks2+marks3) AS Total_Marks,
ROUND((marks1+marks2+marks3)/300.0*100,2) AS Percentage
FROM Students;
Here aliases make headings meaningful and ROUND formats the numeric precision.
📌 Examples
Student total & percentage (MySQL): SELECT roll_no, CONCAT(first_name,' ',last_name) AS Student_Name, (maths+physics+chemistry) AS Total_Marks, ROUND((maths+physics+chemistry)/300*100,2) AS Percentage FROM Students;
Employee salary and tax (MySQL): SELECT emp_id, name, salary, ROUND(salary*0.12,2) AS Tax, CONCAT('₹',FORMAT(salary - ROUND(salary*0.12,2),2)) AS Net_Pay FROM Employee;
Sales summary with aliases (Oracle style): SELECT p.product_name AS Product, SUM(s.quantity) AS Units_Sold, TO_CHAR(SUM(s.quantity * s.price),'FM999,999,990') AS Revenue FROM Sales s JOIN Products p ON s.prod_id = p.id GROUP BY p.product_name;
Date formatting (MySQL): SELECT order_id, DATE_FORMAT(order_date,'%d-%b-%Y') AS Order_Date FROM Orders;
Using table alias in join: SELECT e.name AS Employee, d.name AS Department FROM Employee e JOIN Department d ON e.dept_id = d.id;
🧮 Formulas
\[Column alias: SELECT expression AS alias\]
\[Table alias: FROM table_name AS t (or FROM table_name t)\]
\[Arithmetic expression: SELECT col1 + col2 AS Sum\]
Key Point: Selectivity = matching_rows / total_rows
Explanation: lower selectivity (small fraction) means an index on that column is more useful.
Overview Practical query writing and optimization means writing SQL that is correct, readable and performs well on real datasets. Good queries return correct results and use minimal resources (CPU, memory, I/O). Optimization is about reducing rows scanned, avoiding unnecessary work, and letting the database engine use indexes and efficient join methods.
Write precise SELECTs: select only needed columns (avoid SELECT *) to reduce I/O and network transfer.
Filter early: apply restrictive WHERE predicates so the engine reduces rows as soon as possible.
Use appropriate joins: choose INNER/LEFT/RIGHT correctly and put join conditions in ON, not in WHERE for clarity and correctness.
Prefer set-based operations: avoid row-by-row processing (cursors) in favor of single SQL statements that operate on sets.
Index wisely: create indexes on columns used in WHERE, JOIN, ORDER BY and GROUP BY, but avoid creating too many indexes (overhead on writes).
Use EXPLAIN/EXPLAIN ANALYZE: inspect the execution plan to see which indexes are used and how many rows are estimated/scanned.
Avoid functions on indexed columns: wrapping a column in a function often prevents index usage (e.g., WHERE UPPER(name) = 'X').
Prefer EXISTS over IN for subqueries: for correlated subqueries, EXISTS is often faster and avoids reading a large list into memory.
Limit and paginate efficiently: use keyset pagination (seek method) rather than OFFSET for large offsets.
Use UNION ALL when duplicates are not a concern: avoids the distinct step of UNION.
Batch writes: insert/update/delete in batches rather than one row at a time.
Denormalize selectively: for heavy read workloads, denormalization or materialized views can reduce expensive joins.
Practical workflow
Start with a correct, readable query.
Use EXPLAIN to see the plan and row estimates.
Identify the expensive steps (full table scans, large sorts, expensive joins).
Try adding an index or rewriting the join/subquery and compare plans.
Test on realistic data volumes, measure latency and resource usage.
Common mistakes
Using SELECT * in production queries.
Applying functions to indexed columns in WHERE clauses.
Using OFFSET with large offsets (causes scanning/skipping many rows).
Creating indexes on low-cardinality columns (e.g., gender with values M/F) which give little benefit.
Tools and commands
EXPLAIN [ANALYZE] — inspect the query plan and real execution stats.
ANALYZE / VACUUM / OPTIMIZE — keep statistics and storage healthy so the planner makes good decisions.
SHOW INDEX / DESCRIBE — view indexes and table schemas.
Example of an optimization cycle (summary)
1) Write query -> 2) EXPLAIN -> 3) Find full scan or expensive join -> 4) Add/adjust index or rewrite query -> 5) Measure again
📌 Examples
Example 1 — Avoid SELECT *:
-- Bad
SELECT * FROM students WHERE class = '12A';
-- Better (only needed columns)
SELECT student_id, name, marks FROM students WHERE class = '12A';
Why: Reduces I/O and network transfer if the table has many columns.
Example 2 — Use index-friendly WHERE:
-- Bad: function on column prevents index use
SELECT * FROM employees WHERE UPPER(last_name) = 'SMITH';
-- Better: store normalized data or use case-insensitive collation
SELECT * FROM employees WHERE last_name = 'Smith';
Why: Avoid applying functions to indexed columns so the index can be used.
Example 3 — Rewrite IN to EXISTS for correlated subquery:
-- Potentially slow
SELECT c.* FROM customers c WHERE c.id IN (SELECT customer_id FROM orders WHERE total > 1000);
-- Better
SELECT c.* FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.total > 1000);
Why: EXISTS can short-circuit and is often more efficient for large subqueries.
Example 4 — Use proper join and index:
-- Ensure an index on orders.customer_id
CREATE INDEX idx_orders_customer ON orders(customer_id);
-- Then
SELECT c.name, SUM(o.total) total_spent
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.order_date >= '2024-01-01'
GROUP BY c.name;
Why: Index on join column speeds lookup; filtering on order_date reduces rows early.
Example 5 — Keyset pagination (seek) vs OFFSET:
-- Bad for large offsets
SELECT id, title FROM articles ORDER BY id LIMIT 10 OFFSET 100000;
-- Better (keyset)
SELECT id, title FROM articles WHERE id > 100000 ORDER BY id LIMIT 10;
Why: OFFSET makes DB scan/skip many rows; keyset uses the index to seek to the next rows.
🧮 Formulas
\[Selectivity = matching_rows / total_rows
Explanation: lower selectivity (small fraction) means an index on that column is more useful.\]
\[Index lookup cost (approximate): O(log_b(N) + k)
Where N = number of indexed rows\]
\[b = branching factor of the index (B-tree)\]
\[k = number of matching rows retrieved\]
\[Explanation: cost grows logarithmically to find the start\]
\[plus cost proportional to returned rows.\]
\[Nested loop join cost (approximate): cost ≈ outer_rows * (cost_to_find_matching_inner_row)
If inner is indexed: cost ≈ outer_rows * (log(inner_rows) + matches)
Explanation: nested loop is cheap for small outer sets or when inner has index on join key.\]
\[Hash join cost (approximate): cost ≈ build_cost + probe_cost ≈ rows_build + rows_probe
Explanation: good for large unsorted inputs without useful indexes\]
\[needs memory to build hash table.\]
\[Estimated rows after predicate = total_rows * product_of_selectivities
If WHERE has independent predicates p1\]
\[p2: estimated_rows ≈ total_rows * sel(p1) * sel(p2)
Explanation: helps the planner decide join order and whether to use indexes.\]
Key Concepts
Database
A structured collection of related data stored and accessed electronically.
DBMS
Database Management System — software to create, manage and query databases.
RDBMS
Relational DBMS — stores data in tables with rows and columns and supports relations between tables.
SQL
Structured Query Language — standard language for querying and modifying relational databases.
DDL
Data Definition Language — SQL commands that define or modify database structure (tables, schemas).
DML
Data Manipulation Language — SQL commands to insert, update, delete and retrieve data.
DCL
Data Control Language — SQL commands to control access to data (privileges, roles).
TCL
Transaction Control Language — commands to manage transactions (commit, rollback).
CREATE TABLE
DDL command to create a new table with specified columns and constraints.
ALTER TABLE
DDL command to modify an existing table's structure (add/drop/modify columns).
DROP TABLE
DDL command to permanently remove a table and its data from the database.
SELECT
DML command to retrieve data from one or more tables.
INSERT
DML command to add new rows into a table.
UPDATE
DML command to modify existing rows in a table.
DELETE
DML command to remove rows from a table based on a condition.
WHERE
Clause to filter rows returned or affected by a SQL statement using conditions.
JOIN
Operation to combine rows from two or more tables based on a related column.
PRIMARY KEY
A column or set of columns that uniquely identifies each row in a table; cannot be NULL.
FOREIGN KEY
A column that creates a link between data in two tables, referencing a primary key in another table.
VIEW
A virtual table defined by a query; presents data from one or more tables without storing it separately.
Practice Questions
Classify SQL commands into their four categories with one command each. / SQL कमांड्स को उनकी चार श्रेणियों में एक-एक कमांड सहित वर्गीकृत कीजिए।
Show answer
DDL (CREATE), DML (SELECT/INSERT), DCL (GRANT), and TCL (COMMIT). / DDL (CREATE), DML (SELECT/INSERT), DCL (GRANT), तथा TCL (COMMIT)।
Why should DECIMAL(p,s) be used instead of FLOAT for storing money? / पैसा संग्रहीत करने के लिए FLOAT के बजाय DECIMAL(p,s) क्यों प्रयोग करना चाहिए?
Show answer
DECIMAL(p,s) stores exact fixed-point values avoiding rounding errors, whereas FLOAT is approximate and can introduce errors in currency calculations. / DECIMAL(p,s) सटीक फिक्स्ड-पॉइंट मान संग्रहीत करता है और राउंडिंग त्रुटियाँ टालता है, जबकि FLOAT अनुमानित है और मुद्रा गणना में त्रुटियाँ ला सकता है।
Write the conceptual order of evaluation of clauses in a SELECT query. / SELECT क्वेरी में क्लॉज़ के मूल्यांकन का संकल्पनात्मक क्रम लिखिए।
Show answer
FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT. / FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT।
Differentiate between WHERE and HAVING clauses. / WHERE और HAVING क्लॉज़ में अंतर बताइए।
Show answer
WHERE filters individual rows before aggregation; HAVING filters groups after aggregation (used with GROUP BY). / WHERE एग्रीगेशन से पहले व्यक्तिगत पंक्तियों को फ़िल्टर करता है; HAVING एग्रीगेशन के बाद समूहों को फ़िल्टर करता है (GROUP BY के साथ)।
Write an SQL query to display each class and its average marks for classes whose average exceeds 60. / उन कक्षाओं के लिए प्रत्येक कक्षा और औसत अंक दर्शाने हेतु SQL क्वेरी लिखिए जिनका औसत 60 से अधिक हो।
Show answer
SELECT class, AVG(marks) FROM Students GROUP BY class HAVING AVG(marks) > 60; / SELECT class, AVG(marks) FROM Students GROUP BY class HAVING AVG(marks) > 60;
How does COUNT(*) differ from COUNT(column) in handling NULLs? / NULL को संभालने में COUNT(*) और COUNT(column) कैसे भिन्न हैं?
Show answer
COUNT(*) counts all rows including those with NULLs; COUNT(column) counts only non-NULL values in that column. / COUNT(*) सभी पंक्तियाँ गिनता है जिनमें NULL वाली भी शामिल हैं; COUNT(column) उस कॉलम में केवल नॉन-NULL मान गिनता है।
State the ACID properties of a transaction. / ट्रांज़ैक्शन के ACID गुण बताइए।
Show answer
Atomicity (all or none), Consistency (valid state to valid state), Isolation (concurrent transactions do not interfere), Durability (committed changes persist). / एटॉमिसिटी (सब या कुछ नहीं), कंसिस्टेंसी (वैध से वैध स्थिति), आइसोलेशन (समवर्ती ट्रांज़ैक्शन हस्तक्षेप नहीं करते), ड्यूरेबिलिटी (कमिट किए गए परिवर्तन बने रहते हैं)।
Why is TRUNCATE faster than DELETE, and what is its key limitation? / TRUNCATE, DELETE से तेज़ क्यों है, और इसकी मुख्य सीमा क्या है?
Show answer
TRUNCATE quickly removes all rows while keeping the table structure (minimal logging), but in many DBMS it cannot be rolled back and ignores row-by-row conditions. / TRUNCATE सभी पंक्तियाँ तेज़ी से हटाता है पर टेबल संरचना रखता है (न्यूनतम लॉगिंग), परंतु कई DBMS में इसे रोलबैक नहीं किया जा सकता और यह पंक्ति-दर-पंक्ति शर्त नहीं मानता।