Coding

SQL for Beginners: The 6 Statements You Need, With Examples

SQL for beginners comes down to six statements: CREATE TABLE to define a table, INSERT to add rows, SELECT to read them, UPDATE to change them and DELETE to remove them, plus WHERE to say which rows. You can run every example below in SQLite, which needs no server.

SQL (Structured Query Language) is how you talk to a relational database, which stores data in tables of rows and columns. The quickest way to start is to open a SQLite shell and type along. If you have the sqlite3 command-line tool installed, run sqlite3 practice.db. Python's built-in sqlite3 module works too. Every statement ends with a semicolon.

Create a table

A table has named columns, each with a type. This one stores books:

CREATE TABLE books (
  id     INTEGER PRIMARY KEY,
  title  TEXT,
  author TEXT,
  year   INTEGER,
  price  REAL
);

The PRIMARY KEY column identifies each row uniquely. In SQLite, a column declared exactly as INTEGER PRIMARY KEY fills itself in with a new number if you insert NULL or leave it out. Declaring it as INT PRIMARY KEY does not do that, so keep the full word INTEGER. Also note that SQLite treats column types loosely: the declared type decides how a value is converted, but it does not strictly reject the wrong kind of value (the INTEGER PRIMARY KEY column is the main exception). Other databases such as PostgreSQL are stricter.

Add rows with INSERT

INSERT INTO books (title, author, year, price) VALUES
  ('Dune',             'Herbert', 1965,  9.99),
  ('Emma',             'Austen',  1815,  5.50),
  ('Persuasion',       'Austen',  1817,  6.00),
  ('Neuromancer',      'Gibson',  1984,  8.25),
  ('Children of Dune', 'Herbert', 1976, 10.50);

One INSERT can add several rows by separating the value lists with commas. Text goes in single quotes. Because id is not in the column list, SQLite assigns 1 to 5 in order. Any column you leave out gets its default value, or NULL if it has none.

Read data with SELECT

SELECT * FROM books;

A SELECT has a list of columns to return and a table to read from. The * means all columns. The PostgreSQL tutorial points out that SELECT * is fine for quick, ad hoc queries but is widely considered bad style in production code, because adding a column to the table changes what the query returns. Name the columns you want instead:

SELECT title, price FROM books;

You can also compute a value and rename it with AS:

SELECT title, price * 0.9 AS sale_price FROM books;

A SELECT never changes the data. It only reads.

Filter rows with WHERE

SELECT title, price FROM books WHERE price < 9;

WHERE takes a condition, and only rows where it is true are returned. Combine conditions with AND, OR and NOT:

SELECT title FROM books WHERE author = 'Herbert' AND year > 1970;

Example output:

Children of Dune

Use a single = to compare, and single quotes around text. Double quotes are for column and table names, so "Herbert" may be read as a column name rather than a value.

Sort results with ORDER BY

SELECT title, price FROM books WHERE price < 9 ORDER BY price;

Example output:

Emma|5.5
Persuasion|6.0
Neuromancer|8.25

Add DESC after a column for highest first. Without ORDER BY, the order of the rows is not guaranteed, so never rely on it. You can sort by two columns, such as ORDER BY author, year, and the second one breaks ties in the first. To remove duplicate rows from a result, use SELECT DISTINCT author FROM books;, and add ORDER BY if the order matters.

To return only the first few rows in SQLite, add LIMIT, for example ORDER BY price DESC LIMIT 2 for the two most expensive books.

Count and summarise with GROUP BY

Aggregate functions such as COUNT, SUM, AVG, MIN and MAX turn many rows into one value. GROUP BY computes them once per group:

SELECT author, COUNT(*) AS book_count, MAX(price) AS top_price
FROM books
GROUP BY author
ORDER BY author;

Example output:

Austen|2|6.0
Gibson|1|8.25
Herbert|2|10.5

To keep only some groups, use HAVING. The PostgreSQL tutorial states the difference: WHERE selects input rows before groups and aggregates are computed, whereas HAVING selects group rows after. So WHERE cannot contain an aggregate such as COUNT(*), and HAVING usually does:

SELECT author, COUNT(*) AS book_count
FROM books
GROUP BY author
HAVING COUNT(*) > 1;

Example output: Austen|2 and Herbert|2, in no guaranteed order. Put conditions that do not need an aggregate in WHERE, so that excluded rows never reach the grouping step.

Change rows with UPDATE

UPDATE books SET price = 7.00 WHERE id = 3;

SET lists the new values, and WHERE picks the rows. The SQLite documentation is explicit: if an UPDATE has no WHERE clause, all rows in the table are modified. UPDATE books SET price = 0; sets every price to 0.

Remove rows with DELETE

DELETE FROM books WHERE id = 5;

The same warning applies, from the SQLite documentation: if there is no WHERE clause, all records in the table are deleted. DELETE FROM books; empties the table.

A habit that prevents data loss

Before running an UPDATE or DELETE, run a SELECT with the identical WHERE clause and read the rows it returns:

SELECT * FROM books WHERE id = 5;

If those are the rows you mean to change, replace SELECT * with DELETE and run it again. While you practise, keep a copy of the practice.db file, or just rerun the CREATE TABLE and INSERT statements from the top after dropping the table with DROP TABLE books;.

Common beginner errors

  • Double quotes around text. Use single quotes for values, as in WHERE author = 'Austen'.
  • Aggregate in WHERE. WHERE COUNT(*) > 1 is rejected. Move it to HAVING after a GROUP BY.
  • Re-running the INSERT. It adds the same rows again with new ids, so the table ends up with duplicates.

What to learn next

Once these statements feel familiar, the next topic is working with more than one table, using joins to match rows by a shared key. The other thing to learn early is how to keep user input out of your SQL text. Building a statement by pasting strings together is how SQL injection happens, and the fix is parameterised queries in whatever language calls the database.

Frequently asked questions

How long does it take to learn SQL?
The statements in this article (CREATE TABLE, INSERT, SELECT with WHERE, ORDER BY and GROUP BY, UPDATE, DELETE) are a small set, and you can type and run all of them in one sitting. Joins, subqueries and database design take more practice. There is no official figure for learning time, so the useful measure is whether you can answer your own questions from a table.
Which database should a beginner start with?
SQLite is the lowest-friction choice: it is a single file with no server to install, and the examples here run in it. PostgreSQL is a good next step because its documentation includes a full tutorial. The basic statements in this article work in both, though the less common features differ between systems.
Are SQL keywords case sensitive?
No for the keywords themselves: SELECT and select are the same statement in SQLite and PostgreSQL. Writing keywords in capitals is a convention that makes queries easier to read. String values such as 'Dune' are data, and comparing them can be case sensitive depending on the database and column settings.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before any grouping happens. HAVING filters the groups after the aggregates such as COUNT have been computed. So a condition on a count belongs in HAVING, and a condition on a plain column belongs in WHERE.

Sources