Database Integration & SQL Fundamentals Reference Guide
This comprehensive reference document summarizes the core database and SQL concepts covered in thedatabase-integration course module. The concepts are illustrated using the Employee Management System project database.
1. Introduction to Databases and SQL
A database is an organized collection of data stored electronically to allow efficient storage, retrieval, updating, and management of information.SQL vs. NoSQL Databases
Databases are broadly classified into two categories:What is SQL?
SQL (Structured Query Language) is a declarative language used to communicate with relational databases. Instead of specifying how to access the data, developers specify what data they want, and the database engine determines the most efficient retrieval plan.2. Relational Database Concepts
Relational databases structure data as a collection of linked tables.Key Database Terminology
- Table: A collection of related data organized in rows (records) and columns (fields/attributes).
- Row / Record: A single horizontal entry in a table representing a complete entity instance (e.g., one employee’s profile).
- Column / Attribute: A vertical entity property shared by all records (e.g.,
salary). - Field: The intersection of a row and a column containing a single datum (value).
- Schema: The structural blueprint of the database defining tables, columns, types, constraints, and relationships.
Keys
- Primary Key (PK): A column (or set of columns) that uniquely identifies each row in a table. It cannot contain
NULLvalues, and each table can have only one PK. - Foreign Key (FK): A column in one table that references the Primary Key of another table, establishing a link/relationship between them.
Table Relationships
- One-to-One (1:1): One record in Table A relates to exactly one record in Table B (e.g.,
Employee ↔ Passport). - One-to-Many (1:N): One record in Table A relates to multiple records in Table B (e.g.,
Department ↔ Employees). This is the primary relationship used in the course project. - Many-to-Many (M:N): Many records in Table A relate to many records in Table B (e.g.,
Students ↔ Courses). This is implemented using a junction (or bridge) table.
Constraints
Constraints are rules enforced on data columns to ensure data accuracy, reliability, and integrity:PRIMARY KEY: Enforces uniqueness and non-nullability.FOREIGN KEY: Enforces referential integrity between related tables.NOT NULL: Prevents a column from accepting empty/NULL values.UNIQUE: Ensures all values in a column are distinct.CHECK: Validates that values satisfy a specific logical condition (e.g.,salary > 0).DEFAULT: Inserts a predefined default value if none is provided.
3. SQLite Data Types & Tools
SQLite is a lightweight, zero-configuration, serverless relational database engine that stores the entire database in a single file on disk.SQLite Storage Classes (Data Types)
SQLite utilizes a flexible system called Type Affinity (which allows storing compatible values of other types in a declared column, e.g., storing50000 in a REAL column). It supports five core storage classes:
INTEGER: Signed whole numbers (e.g.,employee_id,age).REAL: Decimal floating-point numbers (e.g.,salary,rating).TEXT: Character string data (e.g.,employee_name,email).BLOB: Binary Large Object data, stored exactly as input (e.g., images, files). Note: In practice, files are usually stored on disk with their file path stored as text in the database.NULL: Represents a missing, unknown, or non-applicable value.
Common SQLite CLI Commands
To manage SQLite from the command prompt (sqlite3 database.db):
4. SQL Command Categorization
SQL commands are grouped into five major categories based on their purpose:- DQL (Data Query Language): Used to retrieve data.
- Commands:
SELECT
- Commands:
- DDL (Data Definition Language): Defines, alters, or destroys database structures.
- Commands:
CREATE,ALTER,DROP,TRUNCATE(Note: SQLite does not supportTRUNCATE)
- Commands:
- DML (Data Manipulation Language): Inserts, updates, or deletes records.
- Commands:
INSERT,UPDATE,DELETE
- Commands:
- DCL (Data Control Language): Manages user access control and permissions.
- Commands:
GRANT,REVOKE(Note: SQLite does not support DCL because it lacks built-in multi-user management)
- Commands:
- TCL (Transaction Control Language): Manages database transactions.
- Commands:
BEGIN,COMMIT,ROLLBACK,SAVEPOINT
- Commands:
5. Data Definition Language (DDL)
DDL statements modify the database schema rather than the individual row contents.Creating Tables (CREATE TABLE)
Defines a new table structure, columns, types, and constraints:
Altering Tables (ALTER TABLE)
Modifies the structure of an existing table:
- Add a Column:
- Rename a Column:
- Rename a Table:
Dropping Tables (DROP TABLE)
Permanently deletes a table and all its contents:
[!NOTE] SQLite does not natively supportTRUNCATE TABLE. To empty all rows from a table while keeping its structure, useDELETE FROM table_name;.
6. Data Manipulation Language (DML)
DML commands allow you to insert, update, and delete rows in a table.Inserting Data (INSERT)
Adds new rows to a table:
- All Columns (Implicit Column Order):
- Selected Columns (Recommended):
- Multiple Rows:
Updating Data (UPDATE)
Modifies existing columns in matching rows:
Deleting Data (DELETE)
Removes matching rows from a table:
[!WARNING] Running anUPDATEorDELETEstatement without aWHEREclause will modify or delete every single row in the target table.
7. Data Query Language (DQL)
DQL is focused entirely on theSELECT statement to retrieve and format data.
SELECT Fundamentals
- All Columns:
SELECT * FROM employee; - Specific Columns:
SELECT employee_name, salary FROM employee; - Remove Duplicates (
DISTINCT):SELECT DISTINCT city FROM employee; - Aliases (
AS): Rename columns in output for readability:SELECT salary * 12 AS annual_salary FROM employee; - String Concatenation (
||):SELECT employee_name || ' - ' || designation AS details FROM employee; - Built-in Scalar Functions:
UPPER(str),LOWER(str): Change case of text.LENGTH(str): Returns character count.ROUND(val, [dec_places]): Rounds numeric values.DATE('now'): Returns the current date.
- Limiting & Offsetting Output:
LIMIT n: Restricts output tonrows.OFFSET m: Skips the firstmrows before returning.
Filtering (WHERE Clause)
Applies logical filters to rows before grouping or returning:
- Comparison Operators:
=,!=,<>,>,<,>=,<= - Logical Operators:
AND: Both conditions must be true.OR: At least one condition must be true.NOT: Inverts the boolean result of a condition.
- Special Operators:
BETWEEN low AND high: Matches values within an inclusive range.IN (val1, val2, ...): Matches any value in a defined list.LIKE: Pattern matching using wildcards:%: Matches zero or more characters (e.g.,'A%'starts with ‘A’)._: Matches exactly one character (e.g.,'_a%'has ‘a’ as the second character).
IS NULL/IS NOT NULL: Checks for missing or defined values.
Sorting (ORDER BY Clause)
Sorts results based on one or more columns:
ASC: Ascending order (default).DESC: Descending order.- Multi-column Sorting:
ORDER BY department_id ASC, salary DESC;(Sorts by department first, and breaks ties by sorting salary highest-to-lowest).
Summarizing Data (Aggregate Functions)
Perform calculations across multiple rows to return a single value:COUNT(*)orCOUNT(column): Counts records (or non-NULL column values).SUM(column): Calculates total sum of numeric values.AVG(column): Computes average numeric value.MIN(column)/MAX(column): Finds minimum / maximum values (works on numbers, text, and dates).
Grouping (GROUP BY and HAVING)
GROUP BY: Summarizes rows with identical values in specified columns into single summary rows.HAVING: Filters groups after aggregation has occurred (cannot be done withWHERE).
Comparison: WHERE vs. HAVING
SELECT Structure and Execution Order
Understanding the difference between how a query is written (Syntax Order) and how the database processes it (Execution Order) is vital for writing bug-free SQL queries.8. Working with Joins
Joins combine columns from two or more tables based on a shared related column.Join Types
INNER JOIN(or shorthandJOIN): Returns only rows where there is a match in both tables.LEFT JOIN: Returns all rows from the left table, and matching rows from the right table. Non-matching right columns result inNULL.RIGHT JOIN: Returns all rows from the right table, and matching rows from the left table. (Not supported natively in SQLite; simulated by reversing table order in aLEFT JOIN).FULL OUTER JOIN: Returns all matching and non-matching rows from both tables. (Not supported natively in SQLite).CROSS JOIN: Returns the Cartesian product (every combination of rows) of both tables.SELF JOIN: Joining a table with itself (requires unique table aliases, e.g., matching employees to their managers in the same table).
Join Syntax: Explicit vs. Implicit
- Explicit JOIN (Recommended): Uses the
JOINandONkeywords. Clean and standard. - Implicit JOIN (Legacy Style): Uses a comma-separated list of tables and places the join condition in the
WHEREclause.
9. Advanced SQL Concepts
Database Normalization
Normalization organizes database columns and tables to eliminate redundancy (duplicate data) and prevent anomalies (insert, update, delete discrepancies).- First Normal Form (1NF): Eliminate repeating groups. Ensure all values in a column are atomic (a single cell cannot contain list-like values, e.g., comma-separated phone numbers).
- Second Normal Form (2NF): Must be in 1NF. Every non-key column must depend on the entire primary key (removes partial dependencies, primarily relevant to tables with composite PKs).
- Third Normal Form (3NF): Must be in 2NF. Non-key columns must not depend on other non-key columns (removes transitive dependencies, e.g., storing a department name inside an employee table when department ID is already present).
ACID Properties
Transactions (units of work containing one or more SQL statements) must satisfy the ACID contract to guarantee reliability:- Atomicity: “All or nothing.” If any statement fails, the entire transaction is rolled back (
ROLLBACK). If all succeed, changes save permanently (COMMIT). - Consistency: The database transitions from one valid schema-compliant state to another.
- Isolation: Transactions executing concurrently do not interfere with each other.
- Durability: Once committed, transaction data is guaranteed to survive system crashes.
Indexes
An index is a database data structure (typically a B-Tree) that speeds up data retrieval.- Pros: Significantly improves performance for
WHERE,JOIN,ORDER BY, andGROUP BYoperations. - Cons: Consumes disk space and slows down write operations (
INSERT,UPDATE,DELETE) because the index must be rebuilt. - Types: Single-Column, Composite (multi-column), and Unique indexes.
- Syntax:
Views
A view is a virtual table representing the result of a saved SQL query. It does not store physical data itself:Stored Procedures
Pre-compiled collections of SQL queries saved on the database server. They allow reusable business logic and reduce network traffic.[!NOTE] SQLite does not support Stored Procedures. They are supported in enterprise databases like PostgreSQL, MySQL, and SQL Server.
Triggers
An automated database script that fires automatically in response to specific table events (BEFORE or AFTER an INSERT, UPDATE, or DELETE occurs):
SQLAlchemy ORM Essentials
A concise reference guide explaining Object-Relational Mapping (ORM) using Python’s SQLAlchemy library. It demonstrates how to map Python classes to database tables, execute CRUD operations, write queries, and model relationships.1. What is an ORM?
An ORM (Object-Relational Mapper) is a library that acts as a translator between two worlds:- Python World: Deals with classes, objects, attributes, and lists.
- Database World: Deals with tables, rows, columns, and SQL syntax.
2. SQLAlchemy Core Workflow & Building Blocks
Every SQLAlchemy application sets up the database connection and operations in a structured pipeline:Initial Configuration Example
3. Defining Models & Column Configuration
Models represent tables. We use type annotations withMapped and configure columns using mapped_column().
Type Mapping & Constraints
Mapped[Python_Type]: Defines the Python type. SQLAlchemy infers standard DB types (e.g.,int->Integer,str->String).mapped_column(SQLAlchemy_Type): Explicitly defines column configuration (e.g.,String(100),Numeric(10,2)).- Constraints:
primary_key=True,nullable=False,default=val,unique=True,index=True(for search performance).
4. Basic CRUD Operations
Database transactions are managed inside a Session.Create (Insert)
Read (Select)
- Get by Primary Key:
- Get All Matching Rows:
Update
- Object-Based Update (Recommended):
- Direct Query Update (Bulk):
Delete
5. Writing Select Queries (SQL vs. SQLAlchemy ORM)
Below is a syntax map of how common SQL queries translate into SQLAlchemy:Result Extraction Methods
execute(stmt): Runs the statement. Returns a rawResultobject.scalars(): Extracts the main model objects (removes database wrapping).all(): Fetches all matched records as a Python list.first(): Returns the first record, orNoneif empty.one(): Returns exactly one record (raises an error if 0 or 2+ matched).one_or_none(): Returns one record orNone(raises error if 2+ matched).
6. Table Relationships
Relationships link Python classes together, allowing easy navigation (e.g.,student.course).