Writing Queries

A file of SQL can hold many statements, and each of them ends with a semicolon. A query is one kind of statement; later, you'll meet statements that add, change and delete data. The database runs them one after another, from the top, and the results come in the same order.

Spaces and new lines don't matter in SQL. These three queries are the same:

SELECT title, genre, price FROM games;

SELECT title, genre, price
FROM games;

SELECT title,
       genre,
       price
FROM games;

Short queries fit on one line. In longer ones, programmers put each part on a line of its own: SELECT with the columns on the first one, FROM with the table on the next. You'll soon add more parts, and each will get its own line too, which makes queries much easier to read.

SQL doesn't mind whether you write its keywords, such as SELECT and FROM, in capitals or in lowercase: select title from games; works too. Still, programmers usually write keywords in capitals and the names of tables and columns in lowercase, so that it's clear at first sight which word is which. This course does it that way too.

Typical mistake: a missing semicolon between two queries. The database then reads them as one query, which doesn't make sense:

SELECT title FROM games
SELECT name FROM customers;
Error on line 1: near "SELECT": syntax error

You'll learn to read such messages in a moment. This one says that the database didn't expect the word SELECT where it found it, because the first query didn't end.

Instructions

The query in the editor works, but it's hard to read. Rewrite it the usual way: keywords in capitals, SELECT with the columns first, and FROM games; on a line of its own.

Below it, add a query that shows the ID, the date and the status of every order (the columns id, ordered_at and status of the table orders). Write it in two lines too.

idordered_atstatus
12024-01-20paid
22024-02-14paid
………

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/7