SQL Basics
SELECT, WHERE, INSERT, JOIN, GROUP BY. Write 5 SQL statements into a .sql file. Schema is in the task.
Your first SQL queries
SQL basics: your first queries
SQL (Structured Query Language) is the language for querying and changing databases. Data lives in tables (rows = records, columns = fields). Almost every application stores its data in an SQL database.
Key commands
SELECT: query data ("show me …").WHERE: filters rows by a condition.INSERT: adds a new record.JOIN: connects two tables via a shared column.GROUP BY+AVG(): groups rows and computes e.g. averages.
You write the SQL into
.sqlfiles under/home/student/sql/(mkdir -p /home/student/sql). There are tablesschueler(name, klasse, …) andnoten(fach, note, …).
Your goal
You write five queries — from a simple selection to an analysis across multiple tables.
Exercises
1. Query all students
Concept:
SELECT.SELECT * FROM tablefetches all columns (*) of all rows of a table. Query all students.mkdir -p /home/student/sql echo "SELECT * FROM schueler;" > /home/student/sql/alle.sqlCheck:
alle.sqlcontainsSELECT * FROM schueler.2. Students of class 7a
Concept:
WHERE. WithWHEREyou filter rows by a condition. Fetch only the students of class7a.echo "SELECT * FROM schueler WHERE klasse = '7a';" > /home/student/sql/klasse-7a.sqlText values are in single quotes (
'7a').Check:
klasse-7a.sqlcontainsSELECT ... FROM schueler ... WHERE klasse = '7a'.3. Insert a new student
Concept:
INSERT.INSERT INTOadds a new record: first the columns, then the values. Add a new student.echo "INSERT INTO schueler (name, klasse) VALUES ('Lisa', '7b');" > /home/student/sql/neu.sqlCheck:
neu.sqlcontainsINSERT INTO schueler (... name ... klasse ...).4. Grades with student name
Concept:
JOIN. AJOINconnects two tables via a shared column (here the student ID), so you can show e.g. grades with the student's name.echo "SELECT schueler.name, noten.fach, noten.note FROM schueler JOIN noten ON schueler.id = noten.schueler_id;" > /home/student/sql/noten-mit-namen.sqlCheck:
noten-mit-namen.sqlcontainsSELECT ... FROM schueler ... JOIN noten.5. Average grade per subject
Concept: aggregation (
AVG+GROUP BY). Aggregate functions combine several rows into one value —AVG()computes the average.GROUP BY fachdoes it per subject.echo "SELECT fach, AVG(note) FROM noten GROUP BY fach;" > /home/student/sql/schnitt.sqlCheck:
schnitt.sqlcontainsSELECT ... AVG(note ... GROUP BY fach.
Related courses
Now practice it yourself
Reading is good – doing is better. Start this course on a real Linux VM, right in your browser. A free account is all it takes.
Start for freeLab content under CC BY 4.0 – free to use with attribution (© TechLogia).
