Adventure 6: Build a Knowledge Base
Welcome to the world of databases! Today, you'll discover how to organize and track your learning journey using powerful data tools. Get ready to become a data architect!

Adventure 1

Hook
The Mystery Question
Imagine you've been studying all year. You have notes everywhere—notebooks, sticky notes, text files on your computer. Now someone asks you: "How many hours did you study math this semester?"
Could you answer this in less than 5 minutes? Probably not! But what if you could answer it in 5 seconds? That's the power of databases.

Adventure 1

The Chaos of Text Files
Your Current System
You create a new file for each day:
monday.txt: Math: 1 hour English: 30 minutes tuesday.txt: Math: 45 minutes Coding: 1 hour wednesday.txt: English: 20 minutes History: 40 minutes
The Problem
  • 100+ files after a few months
  • Can't search across all files easily
  • Hard to calculate totals
  • No way to sort or filter
  • Takes forever to find patterns

Adventure 1

Discussion Time: Your Data Problems
Partner Share
Turn to a partner and discuss: What kinds of information do you track? How do you currently organize it? What's frustrating about your system?
Group Question
Has anyone ever lost important information because they couldn't remember where they saved it? Share your story!

Adventure 1

Enter: The Database Solution
A database is like a super-smart filing cabinet that organizes your data in tables (like spreadsheets). But unlike regular files, databases let you ask questions about your data using special commands.
Want to know your math total? One command. Want to find all study sessions over 1 hour? One command. Want to see which subject you study most? You guessed it—one command!

Adventure 1

What is SQLite?
Super Lightweight
No complicated setup. Your entire database is just one file on your computer. Easy to backup and share!
Blazing Fast
Can handle millions of records and still answer your questions in milliseconds. Way faster than searching through files.
Perfect for Learning
SQLite is used by apps you use every day—like your phone's messaging app. It's industry-standard and easy to learn.

Adventure 1

Database vs. Spreadsheet
Excel/Google Sheets
  • Great for humans to read
  • Click and drag interface
  • Good for small amounts of data
  • Can be slow with lots of data
  • One person at a time (usually)
SQLite Database
  • Optimized for programs
  • Command-based queries
  • Handles massive datasets
  • Lightning-fast searches
  • Multiple apps can use it
Think of spreadsheets as notebooks and databases as libraries. Both store information, but libraries are built for fast searching and large collections.

Adventure 1

Hands-On
Activity 1: Install SQLite
01
Open your terminal
Find and launch your terminal application.
02
Install SQLite
Type this command and press Enter:
03
Create your first database
Type this to create a database file:
sudo apt install sqlite3 -y sqlite3 ~/learning.db
You should see a sqlite> prompt. Congratulations! You're inside your database.

Adventure 1

Understanding Tables
In databases, we organize data into tables. A table is like a spreadsheet with columns (fields) and rows (records). Each column has a specific type of data.
Columns
The categories of information (like "Date", "Subject", "Duration")
Rows
Individual records (like one study session)
Data Types
What kind of data each column holds (text, numbers, dates)

Adventure 1

Creating Your Learning Log Table
Let's create a table to track your study sessions. We'll define exactly what information we want to store:
CREATE TABLE learning_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, subject TEXT NOT NULL, duration_min INTEGER NOT NULL, notes TEXT );
1
id: A unique number for each record (auto-generated)
2
date: When you studied (required)
3
subject: What you studied (required)
4
duration_min: How long in minutes (required)
5
notes: Any extra info (optional)

Adventure 1

Checkpoint: Understanding the Structure
Why do we need an ID column?
The ID gives each record a unique identifier, so even if two sessions are identical, we can tell them apart.
What does NOT NULL mean?
It means that field is required—you can't leave it empty. We need date, subject, and duration for every record.
Why is notes optional?
Sometimes you don't have extra details to add. Making it optional keeps data entry quick and easy.

Adventure 1

CRUD Operations
The Four Basic Database Actions
Create
Add new records (INSERT)
Read
Get information (SELECT)
Update
Change existing records (UPDATE)
Delete
Remove records (DELETE)
Every database operation falls into one of these categories. Master these four, and you can do anything!

Adventure 1

Adding Data: INSERT Command
Let's add your first study session! The INSERT command adds a new row to your table:
INSERT INTO learning_log (date, subject, duration_min, notes) VALUES ('2025-02-08', 'Math', 60, 'Learned fractions');
Let's add a few more sessions:
INSERT INTO learning_log (date, subject, duration_min, notes) VALUES ('2025-02-08', 'English', 30, 'Vocabulary practice'); INSERT INTO learning_log (date, subject, duration_min, notes) VALUES ('2025-02-09', 'Math', 45, 'Word problems'); INSERT INTO learning_log (date, subject, duration_min, notes) VALUES ('2025-02-09', 'Coding', 90, 'Built a calculator');

Adventure 1

Reading Data: SELECT Command
Now the fun part—asking questions! The SELECT command retrieves data from your table.
See Everything
SELECT * FROM learning_log;
The asterisk (*) means "all columns"
Filter by Subject
SELECT * FROM learning_log WHERE subject='Math';
WHERE lets you filter results
Sort by Duration
SELECT * FROM learning_log ORDER BY duration_min DESC;
DESC = descending (highest first)
Calculate Total Time
SELECT SUM(duration_min) FROM learning_log WHERE subject='Math';
SUM adds up all the values

Adventure 1

Practice
Activity 2: Build Your Database
1
Add 5 Study Sessions
Insert at least 5 records with different subjects, dates, and durations. Make them realistic!
2
View Your Data
Use SELECT * to see all your records. Check that everything looks correct.
3
Try Filtering
Use WHERE to show only one subject. Then try sorting by duration.
Time limit: 10 minutes. Raise your hand if you get stuck!

Adventure 1

SQL Magic Spells: Advanced Queries
Now let's learn some powerful SQL "spells" that give you incredible insights into your data!
Counting Records
SELECT COUNT(*) FROM learning_log;
How many total study sessions?
Average Duration
SELECT AVG(duration_min) FROM learning_log;
What's your average session length?
Longest Session
SELECT MAX(duration_min), subject FROM learning_log;
Your personal best study session!

Adventure 1

Grouping Data: The GROUP BY Clause
Want to see totals for each subject? Use GROUP BY to organize results into categories:
SELECT subject, SUM(duration_min) as total_minutes FROM learning_log GROUP BY subject;
This shows the total study time for each subject separately. It's like creating a summary report automatically!
SELECT subject, COUNT(*) as sessions, SUM(duration_min) as total_min, AVG(duration_min) as avg_min FROM learning_log GROUP BY subject ORDER BY total_min DESC;
Now you can see which subject you've studied most, how many sessions, and your average time per session!

Adventure 1

Discussion: Data Patterns
Partner Discussion
Look at your grouped data. Which subject have you studied the most? The least? Are you surprised by the results?
Reflection Question
If you could see this data for a whole semester, what patterns might you discover about your study habits?
Goal Setting
Based on your data, is there a subject you should spend more time on? How would tracking this help you improve?

Adventure 1

Updating Records: The UPDATE Command
Made a mistake? No problem! The UPDATE command lets you change existing records:
UPDATE learning_log SET notes = 'Mastered fractions!' WHERE id = 1;

Warning! Always use WHERE with UPDATE! If you forget it, you'll change every record in the table. The id column helps you target exactly the right record.
You can update multiple fields at once:
UPDATE learning_log SET duration_min = 65, notes = 'Extended study session' WHERE id = 1;

Adventure 1

Deleting Records: The DELETE Command
Need to remove a record? Use DELETE carefully:
DELETE FROM learning_log WHERE id = 5;

Super Important! Just like UPDATE, always use WHERE with DELETE! Without it, you'll delete everything in your table. There's no undo button!
To delete all records from a specific date:
DELETE FROM learning_log WHERE date = '2025-02-08';
To delete all records (use with extreme caution!):
DELETE FROM learning_log;

Adventure 1

Challenge
SQL Challenge Race!
Time to test your skills! Try to complete these challenges. Work with a partner if you'd like:
1
Find Your Best Day
Write a query to find which date you studied the most total minutes.
2
Average by Subject
Calculate the average study duration for each subject.
3
Long Sessions Only
Show all study sessions that were 45 minutes or longer.
4
Update a Note
Pick one of your records and update its notes field with new information.
Bonus Challenge: Find the subject with the highest average study duration!

Adventure 1

Challenge Solutions
Best Day
SELECT date, SUM(duration_min) FROM learning_log GROUP BY date ORDER BY SUM(duration_min) DESC LIMIT 1;
Average by Subject
SELECT subject, AVG(duration_min) FROM learning_log GROUP BY subject;
Long Sessions
SELECT * FROM learning_log WHERE duration_min >= 45;
Update Note
UPDATE learning_log SET notes = 'Your new note' WHERE id = 3;

Adventure 1

AI Integration
Teaching AI to Manage Your Database
Here's where it gets really cool: we can teach an AI assistant to interact with your database using natural language. Instead of typing SQL commands, you'll just talk to your AI!
Imagine saying: "Record that I studied math for 45 minutes today" and your AI automatically adds it to the database. Or asking: "How much did I study this week?" and getting an instant answer.
Let's set this up using a skill system!

Adventure 1

Creating a Database Skill
First, we'll create a folder and file to teach our AI about our database:
mkdir ~/clawd/skills/database vim ~/clawd/skills/database/SKILL.md
This creates a special instruction file that tells the AI:
  • When to use the database (trigger words)
  • Where the database is located
  • What operations it can perform
  • The exact SQL commands to use
Think of this as writing a training manual for your AI assistant!

Adventure 1

The Skill File Contents
# Learning Record Database Skill ## Trigger Words User mentions "record study", "learning stats", "studied today", "how much studied" ## Database Location ~/learning.db ## Operations ### Record Study Session sqlite3 ~/learning.db "INSERT INTO learning_log (date, subject, duration_min, notes) VALUES ('date', 'subject', minutes, 'notes');" ### View Statistics sqlite3 ~/learning.db "SELECT subject, SUM(duration_min) as total FROM learning_log GROUP BY subject;" ### Weekly Summary sqlite3 ~/learning.db "SELECT SUM(duration_min) FROM learning_log WHERE date >= date('now', '-7 days');"

Adventure 1

Testing Your AI Database Assistant
Now restart your AI system and try it out:
openclaw restart openclaw agent --message "Record that I studied Math for 45 minutes today"
The AI should understand your request and add it to the database! Try more commands:
  • "How many hours did I study this week?"
  • "Show me my study statistics"
  • "I just finished 30 minutes of English vocabulary"
  • "What subject have I studied the most?"
Your AI becomes your personal study tracker!

Adventure 1

Discussion: AI and Automation
Group Discussion
Share with your table: What other things could you track with a database? Fitness? Reading? Hobbies? What would be useful for you personally?
Think about: What tasks do you do repeatedly that could be automated with AI and a database?
Ethics Question
If an AI is tracking everything you do (study time, websites visited, apps used), is that helpful or concerning? Where should we draw the line?
Discuss the balance between convenience and privacy.

Adventure 1

Visualization
Making Your Data Visual
Numbers in a database are great, but humans understand pictures better! Let's create visualizations of your study data using Python and matplotlib.
We'll generate:
Bar Chart
Total study time per subject
Pie Chart
Percentage breakdown of subjects
Trend Line
Study time over days/weeks

Adventure 1

Installing Visualization Tools
First, install the Python library for creating charts:
pip3 install matplotlib
Then create a Python script:
vim ~/visualize-learning.py
This script will:
  1. Connect to your SQLite database
  1. Query your study data
  1. Create beautiful charts
  1. Save them as image files
You'll be able to see your progress at a glance!

Adventure 1

Python Visualization Script
import sqlite3 import matplotlib.pyplot as plt # Connect to database conn = sqlite3.connect('/home/user/learning.db') cursor = conn.cursor() # Get data cursor.execute(""" SELECT subject, SUM(duration_min) FROM learning_log GROUP BY subject """) results = cursor.fetchall() # Separate into subjects and durations subjects = [row[0] for row in results] durations = [row[1] for row in results] # Create bar chart plt.figure(figsize=(10, 6)) plt.bar(subjects, durations, color='skyblue') plt.xlabel('Subject') plt.ylabel('Total Minutes') plt.title('Study Time by Subject') plt.savefig('study-chart.png') print("Chart saved!")

Adventure 1

Running Your Visualization
Execute your Python script:
python3 ~/visualize-learning.py
This creates a file called study-chart.png in your home directory. Open it to see your beautiful chart!

Tip: You can modify the script to create different types of charts. Try changing plt.bar() to plt.pie() for a pie chart, or add plt.plot() for a line graph showing trends over time.
Now you can share these visualizations with teachers, parents, or just admire your own progress!

Adventure 1

Teaching AI to Generate Charts
Let's add chart generation to your AI's database skill file:
### Generate Study Chart python3 ~/visualize-learning.py ### Response "I've created a chart of your study statistics. Check study-chart.png to see your progress!"
Now you can simply tell your AI: "Show me a chart of my study time" and it will automatically generate and save the visualization for you!

Adventure 1

Common Mistakes
Common Database Mistakes & Fixes
Forgetting WHERE Clause
Problem: UPDATE or DELETE without WHERE changes/removes ALL records!
Fix: Always double-check you have a WHERE clause. Test with SELECT first.
Mismatched Data Types
Problem: Putting text in a number field or vice versa causes errors.
Fix: Check your column types. Use quotes for TEXT, no quotes for INTEGER.
Typos in Column Names
Problem: Writing "duraton" instead of "duration" gives a "no such column" error.
Fix: Use tab completion or check your CREATE TABLE statement.
Missing Quotes Around Text
Problem: WHERE subject=Math instead of WHERE subject='Math' causes errors.
Fix: TEXT values always need single quotes. Numbers don't.

Adventure 1

More Common Mistakes
SQL Injection in User Input
Problem: Building SQL with user input like: "SELECT * FROM table WHERE user='" + input + "'" is dangerous!
Fix: Use parameterized queries or prepared statements to prevent SQL injection attacks.
Not Closing Database Connection
Problem: Leaving connections open can lock the database file.
Fix: Always close connections: conn.close() in Python or .exit in sqlite3 terminal.
Forgetting Semicolon
Problem: SQL commands need a semicolon at the end, or they won't execute.
Fix: Always end SQL statements with ;

Adventure 1

Quick Quiz
Knowledge Check Quiz
Time to test what you've learned! Answer these 5 questions. Write your answers down, then we'll review together.
  1. What are the four basic database operations (CRUD)?
  1. What SQL command do you use to add a new record?
  1. Why is it dangerous to use UPDATE or DELETE without a WHERE clause?
  1. What does the GROUP BY clause do?
  1. What's the difference between a database and a spreadsheet?
Bonus question: What does the asterisk (*) mean in SELECT * FROM table?

Adventure 1

Quiz Answers
1
CRUD Operations
Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE)
2
Adding Records
INSERT INTO table_name (columns) VALUES (values);
3
WHERE Clause Importance
Without WHERE, UPDATE changes ALL records and DELETE removes ALL records—there's no undo!
4
GROUP BY Function
It organizes results into categories and lets you calculate aggregates (SUM, AVG, COUNT) for each group.
5
Database vs Spreadsheet
Spreadsheets are human-friendly for small data. Databases are optimized for programs, fast queries, and large datasets.
Bonus: The asterisk means "all columns"—select everything!

Adventure 1

Achievement
Congratulations, Database Architect!
100%
Adventure Complete
You've mastered database basics!
Badges Unlocked
Database Architect
Created and managed your own database
Data Visualization Master
Generated charts from your data
SQL Query Wizard
Mastered SELECT, INSERT, UPDATE, DELETE
Progress Tracker
Built a system to monitor your learning

Adventure 1

Homework
Your Mission This Week
1
Daily Tracking
Record all your study sessions for one full week. Try to log at least 3 subjects. Be consistent!
2
Enhance Visualizations
Modify the Python script to create both a bar chart AND a pie chart. Add a trend line showing daily total study time.
3
Export & Share
Research how to export your database to CSV format. Write a short reflection on what you learned from your study patterns.

Adventure 1

Reflection & Exit Ticket
Personal Reflection
Take 3 minutes to write down:
  • One thing that surprised you about databases
  • One challenge you faced and how you overcame it
  • One way you'll use this skill in the future
Exit Ticket Questions
  1. On a scale of 1-5, how confident are you with SQL commands?
  1. What's one question you still have?
  1. What would you track in a database if you could track anything?
Submit your exit ticket before leaving class. Your responses help me understand what we need to review!

Adventure 1

Next Adventure Preview
Adventure 7: AI Superpowers!
Get ready for the next level! In Adventure 7, you'll learn about tool calling and MCP plugins—teaching AI to use external tools and services.
Tool Integration
Connect your AI to web APIs, calculators, and other services
MCP Plugins
Build modular capabilities your AI can activate on demand
Supercharged AI
Create an AI assistant that can truly DO things, not just talk
See you in the next adventure! 🚀

Adventure 1