SELECT, WHERE and ORDER BY

Choose columns, filter rows with WHERE, sort with ORDER BY and limit with LIMIT.

Runs in Zerethon IDE · SQLite 3 Official SQL documentation ↗
main.sql
SELECT name, year
FROM students
WHERE year >= 2 AND name LIKE '%a%'
ORDER BY year DESC, name
LIMIT 3;
setup/schema.sql
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, year INTEGER);
CREATE TABLE courses (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE enrollments (
    student_id INTEGER REFERENCES students (id),
    course_id INTEGER REFERENCES courses (id),
    grade REAL
);

INSERT INTO students VALUES (1, 'Ada', 2), (2, 'Alan', 3), (3, 'Grace', 2), (4, 'Linus', 1);
INSERT INTO courses VALUES (1, 'Algorithms'), (2, 'Databases'), (3, 'Networks');
INSERT INTO enrollments VALUES (1, 1, 9.5), (1, 2, 8.0), (2, 1, 7.5), (3, 2, 9.0), (3, 3, NULL);

Result

nameyear
Alan3
Ada2
Grace2
Uses the school database in setup/schema.sql (shown below the query): students, courses and enrollments.
  • Filters: =, <>, <, >=, IN (1, 2), BETWEEN 1 AND 3, LIKE 'A%' (% any text, _ one character), IS NULL.
  • = NULL is never true — use IS NULL / IS NOT NULL.
  • ORDER BY sorts ascending; add DESC per column. Without ORDER BY the row order is not guaranteed.
  • LIMIT 10 OFFSET 20 returns rows 21–30. SELECT DISTINCT removes duplicate rows.