Tables, rows and columns
A database table looks like a spreadsheet: each column has a name and type, and each row is one record.
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
grade INTEGER
);
INSERT INTO students (name, grade) VALUES
('Arta', 8), ('Besa', 7), ('Dren', 8), ('Ema', 9);
PRIMARY KEY gives every row a unique id, and NOT NULL means the name cannot be left empty.
SELECT and WHERE
SELECT name, grade FROM students;
SELECT name FROM students WHERE grade = 8;
SELECT name FROM students WHERE grade >= 8 AND name LIKE 'D%';
SELECT chooses columns, FROM chooses the table and WHERE filters rows. In LIKE, % matches any number of characters, so 'D%' means "starts with D".
Sorting and counting
SELECT name, grade FROM students ORDER BY grade DESC, name;
SELECT grade, COUNT(*) AS how_many
FROM students
GROUP BY grade;
ORDER BY ... DESC sorts from highest to lowest. GROUP BY puts rows with the same grade together so COUNT(*) can count each group. AS gives the result column a readable name.
Combining tables with JOIN
Data is usually split across tables. A second table stores test results and refers to students by id:
CREATE TABLE results (
student_id INTEGER REFERENCES students(id),
subject TEXT,
score INTEGER
);
INSERT INTO results VALUES (1, 'Math', 92), (2, 'Math', 67), (1, 'Science', 88), (3, 'Math', 75);
SELECT students.name, results.subject, results.score
FROM results
JOIN students ON students.id = results.student_id
ORDER BY results.score DESC;
JOIN ... ON matches each result to the student with the same id, so you can show names instead of numbers. Students without results (Ema) do not appear; use LEFT JOIN from students to include them.
Changing data safely
UPDATE students SET grade = 9 WHERE id = 3;
DELETE FROM results WHERE score < 50;
Always write the WHERE clause first: UPDATE or DELETE without it changes every row. In real programs, never build SQL by gluing user input into the text; use the parameter placeholders your language provides, which prevents SQL injection.
Try it yourself
In Unays Code, choose SQL and run the examples. Then write a query that shows each student's average score, highest first.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].