SQL is the language for talking to a database. A database is a collection of tables that store data. A table is a list of rows and columns, like a spreadsheet. This tutorial uses MySQL/MariaDB. It covers only the basics: creating a table, adding data, reading data, changing data, and deleting data.

Setup

This tutorial uses MySQL or MariaDB that is already installed. The full install guide is in the tutorial “Instal Apache, MySQL, PHP dan phpMyAdmin di ArchLinux”. On Arch Linux, MySQL is replaced by MariaDB, but the SQL commands are the same.

Enter MySQL from the terminal with this command:

mysql -u root -p

Type your MySQL password when asked. The prompt changes to mysql>. That means you are in. Type every command in this tutorial at that prompt.

Note: end each SQL command with a semicolon (;). Without a semicolon, MySQL waits and the command does not run. Press Ctrl+C to cancel a command that has not been sent yet.

Databases and tables

A database is a container for tables. One database can hold many tables. Create a new database named perpustakaan with this command:

CREATE DATABASE perpustakaan;

Then select that database, so the next commands go there:

USE perpustakaan;

A table is where data is stored. One table holds one kind of data, for example a book list. A table has columns (the kinds of fields) and rows (one record each). The id column is a unique number for each row. The judul column holds text, so its type is VARCHAR(100) (text, up to 100 characters). The tahun column holds numbers, so its type is INT (a whole number).

Book table: columns id, judul, penulis, tahun and three rows of data

CREATE TABLE

CREATE TABLE creates a new table. Write the table name, then the list of columns inside brackets. Write each column with its name and type, separated by commas.

CREATE TABLE buku (
  id INT AUTO_INCREMENT PRIMARY KEY,
  judul VARCHAR(100),
  penulis VARCHAR(100),
  tahun INT
);

INT AUTO_INCREMENT PRIMARY KEY means: the id column holds numbers, rises on its own with each new row, and is the primary key (the unique marker of each row). You do not need to fill in id yourself when adding data.

Note: a table or column name with a space in it must use backticks, for example judul buku. Safer: use names without spaces, like judul or judul_buku.

INSERT

INSERT adds a new row to a table. Write the table name, the column names, then the values. Write text between single quotes. Write numbers without quotes.

INSERT INTO buku (judul, penulis, tahun)
VALUES ('Laskar Pelangi', 'Andrea Hirata', 2005);

The id column is not written, because it fills itself. One command can add several rows at once, with each row separated by a comma:

INSERT INTO buku (judul, penulis, tahun) VALUES
  ('Bumi Manusia', 'Pramoedya Ananta Toer', 1980),
  ('Harry Potter dan Batu Bertuah', 'J.K. Rowling', 1997),
  ('Dune', 'Frank Herbert', 1965);

SELECT

SELECT reads data from a table. The star (*) means all columns. This command shows every row in the buku table:

SELECT * FROM buku;

The result looks about like this:

+----+-------------------------------+----------------------+-------+
| id | judul                         | penulis              | tahun |
+----+-------------------------------+----------------------+-------+
|  1 | Laskar Pelangi                | Andrea Hirata        |  2005 |
|  2 | Bumi Manusia                  | Pramoedya Ananta Toer|  1980 |
|  3 | Harry Potter dan Batu Bertuah | J.K. Rowling         |  1997 |
|  4 | Dune                          | Frank Herbert        |  1965 |
+----+-------------------------------+----------------------+-------+

If you only need some columns, write their names. This command shows only title and year:

SELECT judul, tahun FROM buku;

WHERE

WHERE is a row filter. Only rows that match the condition are shown. Without WHERE, all rows are shown. This command shows only books from the year 2005:

SELECT * FROM buku WHERE tahun = 2005;

SELECT with WHERE filters rows: from 4 rows only 2 remain

Operators often used in WHERE:

  • = equals.
  • != does not equal.
  • > greater than, < less than.
  • >= and <= for greater than or equal to, and the reverse.
  • LIKE for text patterns, with % standing in for any letters. Example: WHERE judul LIKE ‘Harry%’ matches titles that start with “Harry”.

Several conditions can be joined. AND means both conditions must match. OR means one condition is enough.

SELECT * FROM buku WHERE tahun > 1990 AND penulis = 'Andrea Hirata';

UPDATE

UPDATE changes the contents of rows that already exist. SET sets the new column and value. WHERE picks which rows change.

UPDATE buku SET tahun = 1998 WHERE id = 3;

The four CRUD operations and their SQL commands: INSERT, SELECT, UPDATE, DELETE

Warning: UPDATE without WHERE changes EVERY row in the table. Always check the WHERE first before pressing Enter. The safe way: run a SELECT with the same WHERE first, and make sure the rows shown are the ones you want to change.

DELETE

DELETE removes rows from a table. WHERE picks which rows are deleted.

DELETE FROM buku WHERE id = 2;

Warning: DELETE without WHERE deletes EVERY row in the table. Deleted data cannot be brought back. Always check the WHERE first, just like with UPDATE. If unsure, run a SELECT with the same WHERE first.

Common mistakes

  • Forgetting the semicolon at the end of a command, so MySQL waits and the command does not run.
  • UPDATE or DELETE without WHERE, so all rows change or are deleted.
  • Writing text without single quotes, for example VALUES (Laskar Pelangi).
  • Writing numbers between quotes, for example tahun = ‘2005’. MySQL still accepts it, but comparisons can go wrong.
  • Mistyping a column name, so MySQL shows an “Unknown column” error.
  • Forgetting USE perpustakaan;, so the table is made in the wrong database.

If you get stuck, ask Muse (yue) to explain the error message. Paste the error from the terminal so the answer is exact.

Complete example: book list

This example joins all the commands above. One small database named perpustakaan with one table named buku. Copy the whole script below, paste it at the MySQL prompt, then press Enter per line. All commands use the same database and table, so the results connect.

CREATE DATABASE perpustakaan;
USE perpustakaan;

CREATE TABLE buku (
  id INT AUTO_INCREMENT PRIMARY KEY,
  judul VARCHAR(100),
  penulis VARCHAR(100),
  tahun INT
);

INSERT INTO buku (judul, penulis, tahun) VALUES
  ('Laskar Pelangi', 'Andrea Hirata', 2005),
  ('Bumi Manusia', 'Pramoedya Ananta Toer', 1980),
  ('Harry Potter dan Batu Bertuah', 'J.K. Rowling', 1997),
  ('Dune', 'Frank Herbert', 1965);

SELECT * FROM buku;

SELECT * FROM buku WHERE tahun = 2005;

UPDATE buku SET tahun = 1998 WHERE id = 3;

DELETE FROM buku WHERE id = 2;

SELECT * FROM buku;

The final result, after the UPDATE and DELETE, is a table with 3 rows:

+----+-------------------------------+---------------+-------+
| id | judul                         | penulis       | tahun |
+----+-------------------------------+---------------+-------+
|  1 | Laskar Pelangi                | Andrea Hirata |  2005 |
|  3 | Harry Potter dan Batu Bertuah | J.K. Rowling  |  1998 |
|  4 | Dune                          | Frank Herbert |  1965 |
+----+-------------------------------+---------------+-------+

Note: this script uses INT AUTO_INCREMENT PRIMARY KEY, which is MySQL syntax. To test it with SQLite, change that line to INTEGER PRIMARY KEY AUTOINCREMENT, and drop the first two lines (CREATE DATABASE and USE), because SQLite does not use those commands. The other commands are exactly the same.