SQL Fundamentals: DDL/DML, Tables, and Basic Queries
Overview of Relational DBs and SQL
- Relational database schema stores data in interrelated tables; tables connect via primary key and foreign key relationships.
- Goals when working with a database:
- Data Definition: change the database structure (create/drop tables, modify table schemas).
- Data Manipulation: modify the data inside tables (insert, update, delete).
- Data Retrieval: query and retrieve information from the database using SQL.
- SQL (Structured Query Language) is a language for managing data in a relational database.
- Not a full programming language; has a standard core with vendor-specific dialects (e.g., MySQL, SQL Server).
- In this course, MySQL is used.
- SQL is divided into DDL (data definition language) and DML (data manipulation language).
- DDL focuses on the table structure (create/drop/alter tables).
- DML focuses on the data itself (insert/update/delete/select).
- Statements vs queries:
- A statement is any SQL command that interacts with the database.
- A query is a statement that retrieves information from the database.
- Execution environments and permissions:
- DDL operations often require higher privileges (often restricted to DB admins).
- In class environments, permissions may prevent creating/dropping tables on the server; practice often occurs on a local server.
- Basic workflow examples:
- Create a new table with specific columns and data types.
- Define constraints (NULL/NOT NULL, DEFAULT) and keys (PRIMARY KEY, FOREIGN KEY).
- Drop a table if needed (use cautiously; drops all data).
- Import data from external sources (e.g., CSV) using tools like Table Data Import Wizard.
- Core SQL concepts introduced in this course:
- Simple single-table queries, multi-table queries, and nested/derived queries.
- Data types, keys, constraints, and basic data integrity concepts.
- Basic query structure and the logical order of query execution.
SQL: What it is and how it’s used
- SQL stands for structure for querying data in a relational database.
- It’s used to perform CRUD operations on tables and to retrieve information through queries.
- Even though syntax varies slightly across MySQL, SQL retains the same core ideas and structure.
Data Definition Language (DDL) in SQL
- DDL operations change the structure of the tables, not the actual data.
- Create a table: syntax overview
- Start with:
CREATE TABLE <table_name> (
<column_name> <data_type> [constraints],
...
[PRIMARY KEY (<col1, col2, ...>)],
[FOREIGN KEY (<col>) REFERENCES <other_table>(<other_table_pk>)]
); - Key elements needed for a table:
- Table name
- Column names
- Data types for each column
- Constraints (optional):
NULL or NOT NULL (mandatory for primary keys to be non-null)DEFAULT values for automatic filling when inserting- Column definitions are separated by commas
- Keys:
PRIMARY KEY defines the unique identifier for rowsFOREIGN KEY defines a reference to another table’s key (use REFERENCES to specify the target table and column)- End the statement with a semicolon
;.
- Drop a table:
DROP TABLE <table_name>;- Dropping a table deletes the table structure and all its data; use with care.
- Modifying existing tables (ALTER): common operations
- Add a column:
ALTER TABLE <table> ADD <column_name> <data_type> [constraints]; - Drop a column:
ALTER TABLE <table> DROP COLUMN <column_name>; - Change a column:
ALTER TABLE <table> MODIFY COLUMN <column_name> <new_data_type> [constraints]; - Rename a column:
ALTER TABLE <table> CHANGE <old_name> <new_name> <data_type>; - Change primary keys: drop the old primary key, then add a new one if needed.
- Auto increment (surrogate keys):
- Common for primary keys requiring auto-generated values.
- MySQL example:
INT NOT NULL AUTO_INCREMENT, typically with PRIMARY KEY. - Result: inserting a new row assigns the next integer value automatically.
- Data types (common examples):
- Numeric:
INT, DECIMAL(p,s) (high precision; use for financial data; examples below) - Floating:
DOUBLE, FLOAT (less precise than DECIMAL for some uses) - Text:
VARCHAR(n), CHAR(n), TEXT - Date/time:
DATE, TIME, DATETIME (or TIMESTAMP)
- Important notes on types and precision:
DECIMAL(p,s) provides fixed precision and scale, helpful for financial calculations.- For primary keys containing both letters and numbers, character types (e.g.,
VARCHAR) are common.
- Example schemas from the transcript:
- Entity tables:
branch with primary key B_NAME, and customer with primary key C_NAME. - Interests and relationships: a many-to-many relationship between customers and branches is captured via an intersection table named
deposit. - Intersection table example (deposit):
- Columns:
C_NAME, B_NAME, BALANCE, D_ACCOUNT_NUMBER. C_NAME and B_NAME are foreign keys referencing customer(C_NAME) and branch(B_NAME) respectively.BALANCE is a DECIMAL with a default of 0.D_ACCOUNT_NUMBER is an INT UNSIGNED NOT NULL and serves as the primary key of the intersection table to uniquely identify each transaction.- If you used a composite primary key (
(C_NAME, B_NAME)), you could not track multiple deposits for the same customer in the same branch.
- Other example tables (simple):
customer table: C_ID as an INT NOT NULL PRIMARY KEY, other fields as VARCHAR or TEXT.order table: ORDER_NO as INT NOT NULL PRIMARY KEY, ORDER_DATE as DATETIME with default NULL, and CUSTOMER_ID as a foreign key referencing customer(C_ID).product table: PRODUCT_ID as INT NOT NULL PRIMARY KEY, PRODUCT_NAME as VARCHAR, PRICE as DECIMAL(p,s).
- Using a database name in DDL:
- Example:
CREATE TABLE M1_OrderDB.customer ( ... ); to specify the target database explicitly.
Importing data from CSV (Workbench example)
- Realistic workflow described for loading a CSV into MySQL Workbench:
- Right-click the target table, choose “Table Data Import Wizard.”
- Browse to the CSV file path.
- Choose to create a new table (or use an existing one) and opt to drop the table if it exists to avoid conflicts.
- The wizard infers field types and table structure; you can adjust field types later.
- After import, refresh and optionally edit to set primary keys and data types.
- Practical notes:
- Importing is convenient for bringing in non-SQL-source data; ensure the data types align with table definitions.
- If you already have an existing schema, you can drop and recreate the table as needed.
- In class demonstrations, Workbench and local databases are used since server permissions may restrict live changes.
SQL execution environment and best practices
- Keywords are case-insensitive in MySQL (e.g.,
SELECT, select, InSeRt all work). - Every SQL command ends with a semicolon
; to denote the end of the statement. - You can break long statements across multiple lines and use indentation for readability; line breaks do not affect the statement as long as the semicolon is present.
- Comments:
-- comment (single-line)/* comment */ (multi-line)
- Readability considerations:
- Use line breaks and indentation to improve readability, especially for complex statements.
- Use comments to explain non-obvious parts of the query.
- Aliases (nicknames):
- Column alias:
SELECT salary * 0.05 AS tax (gives the derived column a readable name) - Table alias:
SELECT e.name FROM employee AS e (shortens references in complex queries) - Aliases are especially useful with nested queries or derived tables.
Basic SQL queries: structure and flow
- Core structure of a simple query:
- Basic form:
SELECT <attribute_list> FROM <table_list> WHERE <condition> ORDER BY <attribute_list> LIMIT <n>; - Output mapping:
SELECT specifies the columns to display in the result.FROM specifies the table(s) to read from.WHERE filters rows (subsets) based on a boolean condition.ORDER BY sorts the output (ascending by default; use DESC for descending).LIMIT restricts the number of rows returned.
- Important concept: execution order vs syntax order
- Syntax order (as written): SELECT -> FROM -> WHERE -> ORDER BY -> LIMIT
- Logical execution order (how the DB engine processes): FROM -> WHERE -> SELECT -> ORDER BY -> LIMIT
- Note: ORDER BY and LIMIT affect display, not the data produced by FROM/WHERE/SELECT.
- Simple example:
- Display an employee’s first name, last name, and salary:
SELECT first_name, last_name, salary FROM employee;
- Distinct and duplicates:
- By default, results may contain duplicate rows if multiple records match the query criteria.
SELECT DISTINCT <columns> FROM <table>; removes duplicate rows from the output based on the specified columns.- Example:
SELECT DISTINCT department_number FROM employee; lists unique departments. - Distinct applies to the combination of the selected columns only, not to the underlying table data.
- The star operator:
SELECT * FROM employee; returns all columns for all rows in the table.- If you select a subset of columns, duplicates can still appear in the output for non-key columns; use
DISTINCT to remove duplicates in the output if desired.
- Between and IN operators in WHERE clauses:
- Range condition:
salary BETWEEN 10000 AND 20000 (inclusive) is a logical expression in WHERE. - Set membership:
last_name IN ('Smith', 'Jones', 'Brown') checks if the last name is in the specified set.
- Logical operators and precedence:
- Conditions can be combined with
AND and OR. AND means all conditions must be true; OR means at least one condition must be true.- If both appear,
AND has higher precedence unless parentheses are used to enforce order: - Example with parentheses:
(salary > 10000 OR middle_initial = 'M') AND last_name = 'Pigment'.
- Nested queries and derived tables (briefly mentioned):
- Aliases help manage readability when dealing with derived tables or nested queries.
Practical examples and explanations from the transcript
- Simple entity example recap:
- Branch table:
B_NAME as primary key, with columns like street, city, assets. - Customer table:
C_NAME as primary key, with street, city.
- Intersection table for a many-to-many relationship (deposit example):
- Purpose: record customer deposits across branches and track deposits per customer-branch pair.
- Columns in the deposit table:
C_NAME, B_NAME, BALANCE, D_ACCOUNT_NUMBER. - Keys and constraints:
C_NAME is a foreign key referencing customer(C_NAME).B_NAME is a foreign key referencing branch(B_NAME).BALANCE is DECIMAL(p,s) with a default of 0.D_ACCOUNT_NUMBER is an INT UNSIGNED NOT NULL and serves as the primary key to uniquely identify each deposit transaction.- Rationale for not using a composite primary key: a customer can make multiple deposits in the same branch, so a composite key on
(C_NAME, B_NAME) would not be unique; a surrogate key (D_ACCOUNT_NUMBER) solves this.
- More straightforward table examples:
customer table: C_ID as INT NOT NULL PRIMARY KEY, other fields VARCHAR/text as needed; only C_ID is required for insertion if others are optional.order table: ORDER_NO as INT NOT NULL PRIMARY KEY, ORDER_DATE as DATETIME, CUSTOMER_ID as a foreign key referencing customer(C_ID).product table: PRODUCT_ID as INT NOT NULL PRIMARY KEY, PRODUCT_NAME as VARCHAR, PRICE as DECIMAL(p,s).
- Aliases and readability in derived calculations:
- Example: calculate tax as 5% of salary and name the derived column:
SELECT salary * 0.05 AS tax FROM employee; - Aliases improve readability for results and for complex expressions.
Practical SQL usage notes and tips
- Case sensitivity:
- Keywords are not case sensitive in MySQL (e.g.,
SELECT, select, Select).
- End-of-statement delimiter:
- Always end statements with a semicolon
; to indicate completion.
- Readability and formatting:
- Break long statements into multiple lines; whitespace and line breaks do not affect execution as long as the semicolon terminates the statement.
- Comments:
- Use
-- or /* ... */ to annotate your SQL code for readability.
- Permissions and environment:
- Class servers may restrict DDL actions; practice often occurs on local environments.
- Workbench’s import wizard can simplify loading CSV data into new tables, with automatic type inference.
- Create table example skeleton:
CREATE TABLE <table_name> (
<column1> <datatype1> [constraints],
<column2> <datatype2> [constraints],
...,
[PRIMARY KEY (<cols>)],
[FOREIGN KEY (<col>) REFERENCES <other_table>(<other_col>)]
);- Data types: extINT, extVARCHAR(n), extDECIMAL(p,s), extDATE, extDATETIME, etc.
- Primary key and foreign key examples:
- Primary key: extPRIMARYKEY(<columnlist>)
- Foreign key: extFOREIGNKEY(<col>)extREFERENCES<othertable>(<othercol>)
- Data type precision example:
- For monetary values: extDECIMAL(10,2)
- Derived column example (tax):
SELECT salary * 0.05 AS tax FROM employee;- If you want to show the derived column name as an alias:
AS tax.
- Distinct and set-based filtering:
SELECT DISTINCT department_number FROM employee; to remove duplicates in the output for the selected column(s).
- Range and set membership in WHERE:
- Numeric range:
salary BETWEEN 10000 AND 20000 - Set membership:
last_name IN ('Smith','Jones','Brown').
- Conditional logic and precedence:
AND vs OR precedence and the use of parentheses to enforce order, e.g., (A OR B) AND C.
- Query structure reminder:
- Syntax order:
SELECT ... FROM ... WHERE ... ORDER BY ... LIMIT ...; - Logical execution order:
FROM -> WHERE -> SELECT -> ORDER BY -> LIMIT.
Final reminders from the lecture
- Always plan your schema with clear keys and relationships before writing queries.
- Use surrogate keys (like
D_ACCOUNT_NUMBER) for intersection/association tables when necessary. - Expect to use foreign keys to enforce referential integrity between related tables.
- Practice with a local database or coursework environment when class permissions limit live changes.
- Use the Table Data Import Wizard for CSV imports and verify data types after import.
- Remember to make queries readable with proper indentation, comments, and aliases when needed.
- Distinguish between what the query outputs (result set) and what exists in the underlying tables (data).