SQL Overview: Schemas, Data Types, and Table Definitions (DDL)
Overview: A table definition decides which values future rows may contain.
What is SQL?
- SQL (Structured Query Language) is the universal, standardized programming language used by developers worldwide to communicate with…
- Originally developed at IBM by Donald Chamberlin and Raymond Boyce in the 1970s (originally named SEQUEL).
- It is a Declarative language: you tell the database what data you want, and the DBMS query engine figures out the most optimized…
Classification of SQL Sub-Languages
- SQL commands are divided into five fundamental functional sub-languages:
- 1. DDL (Data Definition) Defines & alters table structures.
- 2. DML (Data Manipulation) Inserts, modifies & queries records.
- 3. DCL (Data Control) Manages user security & permissions.
- 4. TCL (Transaction Control) Manages database transactions.
View diagram · The Sub-Languages of SQL
Standard SQL Data Types and Domains
- Before creating a table, columns must be assigned specific storage data types:
INTorINTEGER: Whole numbers without decimals (positive or negative)NUMERIC(p, s)orDECIMAL(p, s): Exact precision numbers (p= total digits,s= decimal places)CHAR(n): Fixed-length string (pads unused space with blanks)VARCHAR(n): Variable-length string (only consumes memory for actual text)DATE: Calendar date format (YYYY-MM-DD)TIME/TIMESTAMP: Time (HH:MM:SS) or combined Date + Time
Creating Tables and Enforcing Constraints (CREATE TABLE)
- The
CREATE TABLEcommand creates a new relation and establishes its column definitions, data domains, and business rules. - The Six Essential Column Constraints:
PRIMARY KEY: Guarantees column values are Unique and NOT NULL. FOREIGN KEY: References the primary key of another table (Referential Integrity).NOT NULL: Prevents a column from ever holding a NULL value.UNIQUE: Ensures all values in a column are distinct (allows NULLs unlessNOT NULLis also specified).CHECK: Validates that data values satisfy a specific boolean condition.DEFAULT: Automatically supplies a fallback value if no value is provided on insertion.
Modifying Tables (ALTER TABLE)
- When business requirements change, you don’t need to delete and recreate tables; use
ALTER TABLE:
Removing Tables: DROP vs. TRUNCATE vs. DELETE
- Students frequently confuse these three commands in university viva and theory exams:
- Language Category: DDL
- What is Removed?: Removes data AND table schema structure permanently from disk
- Speed: Extremely fast
- Rollback Capability: Cannot be rolled back (auto-committed)
- WHERE Clause: Not applicable
SQL Data Manipulation (DML): INSERT, UPDATE, DELETE, and SELECT Queries
Overview: An UPDATE without a WHERE condition can affect every row.
What is Data Manipulation Language (DML)?
- While DDL sets up the empty structure and containers of a database (like tables and columns), DML (Data Manipulation Language) is what…
Database Change Operations: INSERT, UPDATE, and DELETE
- INSERT adds rows and UPDATE changes values in existing rows.
- A. Inserting Data (
INSERT INTO): There are two primary ways to insert data into a table: - B. Modifying Existing Data (
UPDATE): TheUPDATEstatement changes values in existing rows. - C. Removing Data (
DELETE): TheDELETE FROMstatement removes rows from a table.
View diagram · The Three Core Database Change Operations
Querying Data: The Fundamental SELECT Statement
- The
SELECTstatement is the most widely executed statement in database computing.
Filtering Rows with the WHERE Clause
- The
WHEREclause uses comparison and logical operators to filter records:
Special SQL Filtering Operators
- A. The
BETWEENOperator (Range Testing): Tests whether a value falls within an inclusive numerical or date range: - B. The
INOperator (Set Membership): Tests whether a value matches any value in a specified list: - C. The
LIKEOperator (Pattern Matching with Wildcards): Used to search for string patterns using two standard wildcards: - Percent sign (
%): Matches zero, one, or multiple characters. - Underscore (
_): Matches strictly one single character. - D. Testing for NULL Values (
IS NULL/IS NOT NULL): You cannot use= NULLbecause in SQL,NULLrepresents an unknown state, and comparing anything toNULLyieldsUNKNOWN!
SQL Joins: Inner, Left, Right, Full Outer, Cross, and Self Joins
Overview: An inner join of Student and Payment includes students with matching payments.
Why Do We Need Joins in SQL?
- In a normalized database, data is deliberately split across multiple related tables to prevent redundancy (e.g., student details in
Student…
Visual Overview of SQL Joins
- Matching keys produce joined rows and repeated keys can produce several matches.
- INNER JOIN Returns ONLY rows that have matching values in both tables.
- LEFT OUTER JOIN Returns ALL rows from Left table + matching rows from Right table.
- RIGHT OUTER JOIN Returns ALL rows from Right table + matching rows from Left table.
- FULL OUTER JOIN Returns ALL rows from BOTH tables; unmatched fields become NULL.
View diagram · Visualizing SQL Joins (Venn Diagram Perspective)
Sample Data Used for Examples:
- 101: Aman
- 102: Priya
- 103: Rohan
- 104: Sneha
- 1: Computer Science
- 2: Management
- 3: Commerce
INNER JOIN (The Default Join)
- Returns only records that have matching values in both tables:
- Notice that
Sneha(Dept_ID is NULL) andCommerce(no students enrolled) are both excluded! - 101: Aman
- 102: Priya
- 103: Rohan
LEFT OUTER JOIN (or LEFT JOIN)
- Returns all rows from the left table (
Student), even if there are no matching rows in the right table (Department). - 101: Aman
- 102: Priya
- 103: Rohan
- 104: Sneha
- Result: (Sneha is preserved even though she has no department assigned!).
RIGHT OUTER JOIN (or RIGHT JOIN)
- Returns all rows from the right table (
Department), even if no student from the left table belongs to it: - 101: Aman
- 103: Rohan
- 102: Priya
- NULL: NULL
- Result: (Commerce is preserved even though zero students belong to it!).
FULL OUTER JOIN
- Combines the results of both Left and Right joins.
- Result: Shows Aman, Priya, Rohan (matched).
- Shows Sneha with
NULLdepartment. - Shows Commerce with
NULLstudent.
CROSS JOIN (Cartesian Product in SQL)
- Combines every single row of the first table with every single row of the second table without any
ONcondition: - If Table A has 4 rows and Table B has 3 rows: Output has
4 × 3 = 12 rows.
Self Join (Joining a Table with Itself)
- A Self Join is a regular join where a table is joined with itself using table aliases.
SQL Aggregate Functions, GROUP BY, and the HAVING Clause
Overview: If one department has marks 50, 70 and 90, its average is 70.
What are Aggregate Functions?
- In ordinary SQL queries, an operation works on one row at a time (e.g., checking if
Age > 20).
The 5 Core Built-In Aggregate Functions
- COUNT counts qualifying items, while SUM and AVG combine numeric values.
- 1. COUNT() Returns the total number of rows or non-null values.
- 2. SUM() Calculates the total mathematical sum of a numeric column.
- 3. AVG() Calculates the arithmetic mean value of a numeric column.
- 4. MIN() Returns the lowest (minimum) value in a column.
- 5. MAX() Returns the highest (maximum) value in a column.
- Practical Examples of Basic Aggregates: Table:
Employee (Emp_ID, Name, Salary, Dept_ID) - 📌 Important Rule: All aggregate functions (except
COUNT(*)) automatically ignore NULL values during calculations!
View diagram · The Five Built-In Aggregate Functions in SQL
Grouping Rows with the GROUP BY Clause
- The
GROUP BYstatement groups rows that have the same values in specified columns into summary rows (like *“find the average salary for EACH… - Practical Example: ⚠️ The Golden SQL Rule for GROUP BY:
- Every column listed in the
SELECTclause that is NOT enclosed inside an aggregate function MUST be included in theGROUP BYclause!
Filtering Groups with the HAVING Clause
- What if you want to filter out entire groups?
- You CANNOT use
WHEREwith aggregate functions! - Why?
- The
HAVINGclause was introduced specifically to filter groups AFTER aggregation has occurred!
Crucial Comparison: WHERE vs. HAVING
- This is one of the most frequently asked 5-mark questions in DAVV examinations:
- Primary Purpose: Filters individual rows (tuples)
- Execution Timing: Executes BEFORE
GROUP BY - Use with Aggregates: Cannot be used with aggregate functions
- Dependency: Can be used independently without
GROUP BY - Performance: Fast (reduces dataset size early before grouping)
Complete Query Anatomy (Execution Order)
- When a complex SQL query contains all clauses, how does the database execute it?
- Actual Execution Order in the Database Engine:
FROM Employee➔ Locates table on disk. WHERE Age >= 21➔ Discards employees younger than 21.GROUP BY Dept_ID➔ Groups remaining records by department.HAVING COUNT(*) >= 3➔ Discards groups with fewer than 3 employees.SELECT Dept_ID, AVG(Salary)➔ Computes final summary projections.ORDER BY Avg_Sal DESC➔ Sorts the final output in descending order!
SQL Views, Updatability, and Programmatic SQL (Embedded & Cursors)
Overview: A view can present just roll number and total marks to a reporting user.
What is a View in SQL?
- A View is essentially a Virtual Table based on the result-set of an underlying SQL query.
- Unlike a physical base table, a View does NOT store data rows on the hard drive!
- Instead, the DBMS stores only the SQL definition of the view in the Data Dictionary.
- Whenever an application queries the view, the database engine executes the stored query dynamically behind the scenes!
Creating and Using Views (CREATE VIEW)
- Practical Example: Suppose the college database administrator wants examination staff to view student names and course marks, but wants to hide…
Advantages of Using Views
- A view gives a stored name to a query and can simplify repeated joins.
- 1. Security & Access Control Hides sensitive columns (like salaries, passwords) from unauthorized users.
- 2. Query Simplification Hides complex 5-table joins behind a simple SELECT * FROM MyView .
- 3. Logical Data Independence If base tables are restructured, the view definition can be modified without breaking client apps.
- 4. Customized Perspectives Different departments see only the data relevant to their day-to-day operations.
View diagram · The Four Major Benefits of Views
Updatable Views vs. Non-Updatable Views
- Can you run
INSERT,UPDATE, orDELETEstatements on a View? - Yes, BUT ONLY IF THE VIEW IS UPDATABLE!
- If a view is updatable, any change made through the view is immediately propagated down into the underlying physical base table.
- Strict Conditions for a View to Be Updatable: A view is NOT updatable if its
SELECTdefinition contains any of the following: - Aggregate Functions: (
SUM,AVG,COUNT,MAX,MIN). - The
DISTINCTkeyword . - The
GROUP BYorHAVINGclause . - The
UNIONorUNION ALLoperator .
Programmatic SQL: Using SQL with Programming Languages
- SQL is a non-procedural language lacking loops (
for,while),if-elsebranches, and user interface controls. - Two Primary Integration Approaches: Embedded SQL: Standard SQL statements are written directly inside host language source code (prefixed with
EXEC SQL). - Dynamic SQL / APIs (CLI, JDBC, ODBC):
- ODBC (Open Database Connectivity): Standard C/C++ API for database access across different database vendors.
- JDBC (Java Database Connectivity): Standard Java API allowing Java applications to execute SQL queries and process result sets seamlessly.
Database Cursors: Bridging SQL and Host Languages
- The Fundamental Impedance Mismatch: SQL operates on SETS: A
SELECTquery returns a set of 1,000 rows all at once (Set-at-a-time). - Programming Languages operate on VARIABLES: Java or C processes one variable at a time (Record-at-a-time).
- A Cursor is a database mechanism that acts as a pointer or iterator over the active query result set, allowing the host application to…