Describing data using the SQL language.
Ensuring data integrity in SQL. Creating data tables. Working with subqueries. Creating database objects. Data definition language (DDL) commands.
Describing Data using SQL
Recap: Relational Model and Tables
Recap: SQL Basics
Data Definition Language (DDL)
DDL vs. DML
Importance of DDL
DDL: The Blueprint of Your Database
Creating Tables: The CREATE TABLE Statement
CREATE TABLE Syntax - Basic Structure
CREATE TABLE Syntax - Components
Inside the parentheses, we define each column:
CREATE TABLE - Simple Example
CREATE TABLE Employees (
employee_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
Data Types in SQL: Overview
Data Types: Integer (INT)
Data Types: Variable-Length String (VARCHAR)
Data Types: Fixed-Length String (CHAR)
Data Types: Date and Time
Data Types: Decimal (DECIMAL / NUMERIC)
Data Types: Other Types
SQL supports other data types, including:
The specific data types available and their syntax may vary slightly depending on the database system (MySQL, PostgreSQL, SQL Server, Oracle, etc.). Refer to the documentation for your specific database system for details.
Data Types: Summary
Column Constraints: Enforcing Data Integrity
Constraint: NOT NULL
CREATE TABLE Students (
student_id INT NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
Constraint: UNIQUE
CREATE TABLE Students (
student_id INT,
email VARCHAR(255) UNIQUE,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
Constraint: PRIMARY KEY
CREATE TABLE Students (
student_id INT PRIMARY KEY,
email VARCHAR(255),
first_name VARCHAR(50),
last_name VARCHAR(50)
);
Constraint: FOREIGN KEY
CREATE TABLE Courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(100)
);
CREATE TABLE Enrollments (
enrollment_id INT PRIMARY KEY,
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES Students(student_id),
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);
Constraint: CHECK
CREATE TABLE Students (
student_id INT PRIMARY KEY,
age INT,
CHECK (age >= 18)
);
CREATE TABLE Example: Students Table
Ensuring Data Integrity
Why is Data Integrity Important?
Data Integrity: Real-World Examples
SQL Constraints and Data Integrity
NOT NULL and Data Integrity
UNIQUE and Data Integrity
PRIMARY KEY and Data Integrity (Entity Integrity)
FOREIGN KEY and Data Integrity (Referential Integrity)
CHECK and Data Integrity (Domain Integrity)
Data Integrity: Quick Quiz
Introduction to Subqueries
Purpose of Subqueries
Subquery Syntax: SELECT in WHERE Clause
SELECT column1, column2
FROM table_name
WHERE column_name IN (SELECT column_name FROM another_table WHERE condition);
Subquery Execution Order
Subquery Example: Students and Instructors
Subquery: Complete example
SELECT student_name
FROM Students
WHERE course_id IN (
SELECT course_id
FROM Courses
WHERE instructor_id IN (
SELECT instructor_id
FROM Instructors
WHERE department = 'Computer Science'
)
);
Subqueries: Beyond the Basics
Database Objects: Tables
Summary