
Python
Learn how to design tables that organize data effectively.
A table is like a spreadsheet with rows (records) and columns (fields):
ID | Name | Age | Email
---|-------|-----|------------------
1 | Alice | 30 | alice@example.com
2 | Bob | 25 | bob@example.com
3 | Carol | 28 | carol@example.comEach column has a data type that defines what kind of data it can hold.
| Type | Description | Example |
|---|---|---|
| INTEGER | Whole numbers | 25, -100, 0 |
| REAL | Decimal numbers | 3.14, 99.99 |
| TEXT | Text/strings | "Alice", "New York" |
| BLOB | Binary data | Images, files |
| NULL | No value | (empty) |
import sqlite3
conn = sqlite3.connect("app.db")
cursor = conn.cursor()
# CREATE TABLE statement
cursor.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
email TEXT
)
""")
conn.commit()Constraints enforce rules about what data can be stored:
# Each ID must be unique (no duplicates)
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT
)# Name is required (can't be empty)
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)# Email must be unique (no two users same email)
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT UNIQUE
)# If no age provided, default to 0
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER DEFAULT 0,
created_date TEXT DEFAULT CURRENT_TIMESTAMP
)# Age must be positive
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER CHECK(age > 0)
)import sqlite3
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
# Create students table
cursor.execute("""
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
grade INTEGER CHECK(grade >= 1 AND grade <= 12),
email TEXT UNIQUE,
enrollment_date TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
# Create courses table
cursor.execute("""
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
teacher TEXT NOT NULL,
credits INTEGER DEFAULT 3
)
""")
conn.commit()
print("Tables created successfully!")# Add a new column to existing table
cursor.execute("ALTER TABLE users ADD COLUMN phone TEXT")
# Rename a table
cursor.execute("ALTER TABLE users RENAME TO profiles")
# Check if table exists
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name='users'
""")
table_exists = cursor.fetchone() is not None# Delete entire table (be careful!)
cursor.execute("DROP TABLE users")
conn.commit()
# Drop only if it exists
cursor.execute("DROP TABLE IF EXISTS users")
conn.commit()Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward