Java tutorialLesson 15 of 18 · tap to see all lessons
Java tutorial · Beginner
Essential SQL for Java Applications: CREATE, INSERT, SELECT, UPDATE, and DELETE
Write the SQL every database application needs: create a database and tables, insert rows, query them with WHERE and ORDER BY, and safely update and delete data.
- Qyubie Learn Editorial Team
- Published
- 15 min read
Includes 4 exercises and 2 quick checks you can do right here.
Almost everything an application does with its data comes down to four actions: Create, Read, Update, and Delete, or CRUD. Adding a student, listing the class, changing a grade, removing a dropped subject: each is one SQL statement. In lesson 19 your Java code will send these same statements to MySQL, so it's worth learning them well now.
By the end of this lesson you will be able to:
- create a database and a table,
- add rows with
INSERT, - read rows with
SELECT, filter them withWHERE, and sort them withORDER BY, and - change and remove rows safely with
UPDATEandDELETE.
Every example runs in your browser. Edit them and press Run as often as you like; each run starts from an empty database.
| CRUD | SQL | Example |
|---|---|---|
| Create | INSERT | enroll a new student |
| Read | SELECT | show the class list |
| Update | UPDATE | change a student's course |
| Delete | DELETE | remove a cancelled enrollment |
Creating a database and a table
In MySQL, a server holds many databases, one per application. Create one and switch to it with USE:
CREATE DATABASE school_db;
USE school_db;Then create tables inside it. Each column gets a name, a type, and optional rules:
Try it · SQL
DESCRIBE lists a table's columns, so you can check what you made. DEFAULT 1 fills in year_level when an INSERT leaves it out. (In the browser, DESCRIBE shows SQLite's names for the types; MySQL shows the types as you wrote them.)
Two more statements you'll use while practicing:
SHOW TABLES; -- list the tables in the current database
DROP TABLE IF EXISTS students; -- delete a table and ALL its rowsSQL keywords aren't case-sensitive, but writing them in CAPITALS makes queries easier to read. End each statement with a semicolon.
INSERT: adding rows
List the columns, then the values in the same order. Text and dates go in single quotes; numbers don't.
Try it · SQL
idis never inserted:AUTO_INCREMENTfills it in.- Always name the columns.
INSERT INTO students VALUES (...)without them depends on the exact column order and breaks when a column is added. - An apostrophe inside text is written twice:
'Ma''am Santos'.
SELECT: reading rows
SELECT picks the columns, FROM names the table, and WHERE keeps only the rows that match a condition:
Try it · SQL
Change the last query and run it again. Try these one at a time:
SELECT * FROM students WHERE year_level >= 2;
SELECT name FROM students WHERE course = 'BSIT' AND gwa <= 2.00;
SELECT name FROM students WHERE year_level = 1 OR year_level = 3;
SELECT name FROM students WHERE year_level IN (1, 3); -- same as the line above
SELECT name FROM students WHERE gwa BETWEEN 1.50 AND 2.00; -- includes both ends
SELECT name FROM students WHERE name LIKE 'C%'; -- starts with C
SELECT name FROM students WHERE gwa IS NULL; -- no GWA recordedThe comparison operators are =, <> (not equal; != also works), <, >, <=, and >=. Note that SQL uses a single = for comparing, unlike Java's ==.
In LIKE, % matches any number of characters and _ matches exactly one: '%son' ends with "son", and '_en' matches "Ben" and "Ken".
Exercise · SQL
Third-year students
Show the name and course of students in year 3.
Hint
SELECT name, course FROM students WHERE ... ; the condition compares year_level with 3.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
SELECT name, course FROM students WHERE year_level = 3;
ORDER BY and LIMIT
Without ORDER BY, the database may return rows in any order. Add ORDER BY at the end; ASC (smallest first) is the default and DESC reverses it. LIMIT n keeps only the first n rows.
Try it · SQL
You can sort by more than one column: ORDER BY course ASC, name ASC sorts by course, and by name within each course.
The clauses always go in this order:
SELECT columns
FROM table
WHERE condition
ORDER BY column
LIMIT n;Exercise · SQL
BSIT class list
List the name and year_level of BSIT students, sorted by year_level from highest to lowest.
Hint
Add WHERE course = 'BSIT', then ORDER BY year_level DESC. WHERE comes before ORDER BY.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
SELECT name, year_level FROM students WHERE course = 'BSIT' ORDER BY year_level DESC;
Quick check
UPDATE: changing rows
UPDATE sets new values with SET, and WHERE chooses which rows to change:
Try it · SQL
You can set several columns at once: SET course = 'BSCS', year_level = 2.
Always check the WHERE before you run an UPDATE. Without it, every row changes. UPDATE students SET course = 'BSCS'; makes the whole school BSCS, and there's no undo. A safe habit:
- First run a
SELECTwith the sameWHERE, and check it returns only the rows you mean. - Then turn it into the
UPDATE. - Update by the primary key (
WHERE id = 2) when you mean one row. Names can repeat; IDs can't.
MySQL Workbench has a "safe updates" setting, on by default, that refuses an UPDATE or DELETE without a key in its WHERE for exactly this reason.
Exercise · SQL
Record a new GWA
Cara Lim (id 3) has a new GWA of 1.25. Write an UPDATE for her row only, then a SELECT that shows name and gwa of all students, sorted by id.
Hint
UPDATE students SET gwa = 1.25 WHERE id = 3; then keep the SELECT.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
UPDATE students SET gwa = 1.25 WHERE id = 3; SELECT name, gwa FROM students ORDER BY id;
DELETE: removing rows
DELETE FROM removes whole rows, and like UPDATE, the WHERE chooses which:
Try it · SQL
DELETE FROM enrollments; without a WHERE empties the table. The same rule applies: test the WHERE with a SELECT first.
DELETE removes rows but keeps the table. DROP TABLE removes the table itself, structure and all.
Exercise · SQL
Remove cancelled enrollments
The subject PE 2 was cancelled. Delete every enrollment in PE 2, then show the remaining student and subject_code, sorted by id.
Hint
DELETE FROM enrollments WHERE subject_code = 'PE 2'; then the SELECT.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
DELETE FROM enrollments WHERE subject_code = 'PE 2'; SELECT student, subject_code FROM enrollments ORDER BY id;
Quick check
Counting and averages (a preview)
SQL can also compute over many rows. These aggregate functions return one row:
Try it · SQL
AS gives a result column a readable name. COUNT, SUM, AVG, MIN, and MAX are handy for reports. In the next lesson you'll use them with GROUP BY to get one result per group, such as "how many students per course". For more practice on SELECT and WHERE, try your first SQL queries.
Common mistakes
UPDATEorDELETEwithoutWHERE: every row is changed or removed.- Double quotes for text. Standard SQL uses single quotes:
'BSCS'. WHERE gwa = NULL. Nothing is ever equal toNULL; writeWHERE gwa IS NULL.- Clauses in the wrong order, such as
ORDER BYbeforeWHERE. - Inserting values in a different order than the column list.
- Expecting a fixed row order without
ORDER BY.
Summary
CREATE DATABASE,USE, andCREATE TABLEset up where data lives;DESCRIBEandSHOW TABLESlet you check.INSERT INTO table (columns) VALUES (...)adds rows.SELECT columns FROM table WHERE ... ORDER BY ... LIMIT nreads them.UPDATE table SET ... WHERE ...changes rows, andDELETE FROM table WHERE ...removes them. Check theWHEREfirst.
Next lesson: designing the project database: putting these statements to work on the Student Information Program.