Sub topic 1
Your first query: SELECT and FROM
Prerequisites
This chapter assumes you already know the following:
- A relational table stores data in rows (one record each) and columns (one named attribute each).
- You have access to a SQL database or client where you can run statements. PostgreSQL, MySQL, and SQLite all work. The examples use only syntax they share.
- You can create a table and insert rows, or you have a sample table to practice on.
The examples use an employees table. If you need one, this script works in PostgreSQL, MySQL, and SQLite:
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary INTEGER,
hire_date DATE,
manager_id INTEGER
);
INSERT INTO employees VALUES (1, 'Ada', 'Lovelace', 'Engineering', 90000, '2019-03-01', NULL);
INSERT INTO employees VALUES (2, 'Grace', 'Hopper', 'Engineering', 95000, '2020-06-15', 1);
INSERT INTO employees VALUES (3, 'Maria', 'McBride', 'Sales', 52000, '2021-02-10', 1);
INSERT INTO employees VALUES (4, 'Tom', 'Nguyen', 'Sales', 48000, '2022-09-05', 3);
INSERT INTO employees VALUES (5, 'Priya', 'Shah', 'Marketing', 61000, '2020-11-20', 1);What a query is
A query is a request for data. In SQL, the statement that makes this request is SELECT. It reads data and returns it as a result set. A result set is a temporary table with its own columns and rows. A SELECT does not change the stored data. You can run it as often as you like without risk.
The smallest useful query has two parts, called clauses:
SELECTnames what you want back.FROMnames the table to read it from.
SELECT first_name, last_name, salary
FROM employees;This returns three columns for every row of employees. With the sample data, the result looks like this:
| first_name | last_name | salary |
|---|---|---|
| Ada | Lovelace | 90000 |
| Grace | Hopper | 95000 |
| Maria | McBride | 52000 |
| Tom | Nguyen | 48000 |
| Priya | Shah | 61000 |
The semicolon ends the statement. Most clients accept a statement without it when you run one at a time. Include it anyway, because scripts with several statements need it.
Reading the statement
SQL is declarative. You describe the result you want, not the steps to produce it. The database decides how to find the rows, for example whether to scan the whole table or use an index.
Three habits make queries easier to read:
- Put each clause on its own line.
- Write keywords such as
SELECTandFROMin uppercase. SQL does not require this, but it separates keywords from names. - Put each column on its own line when the list gets long.
Keywords are case-insensitive, so select and SELECT behave the same. Table and column names depend on the database. PostgreSQL folds unquoted names to lowercase. MySQL treats table names as case-sensitive on Linux and case-insensitive on Windows and macOS by default. Using lowercase names with underscores avoids these differences.
The order of the clauses
You write SELECT before FROM, but you can read it as "from this table, get these columns." The clause order in the text is fixed. FROM must come after SELECT, and later chapters add WHERE and ORDER BY after FROM.
The diagram below shows the shape of a query and what each part contributes.
Selecting every column with *
The asterisk * is shorthand for "all columns":
SELECT *
FROM employees;This is useful for a first look at an unfamiliar table. Columns come back in the order they were defined in the table. Avoid * in application code and saved queries for these reasons:
- The result changes when someone adds, drops, or reorders columns. Code that reads columns by position can break silently.
- It returns data you do not need. This wastes network bandwidth and memory, and it can expose sensitive columns.
- It can prevent the database from answering the query from an index alone.
Naming the columns documents your intent and keeps the result stable. The next chapter covers choosing columns in more detail.
Row order and the number of rows
A plain SELECT ... FROM returns one result row for each row in the table. It may return them in any order. The order often looks stable, such as insertion order, but SQL does not guarantee it. It can change after updates, after a table is reorganized, or when the database picks a different plan. If order matters, you must ask for it with ORDER BY, which a later chapter covers.
SELECT without FROM
FROM is not always needed. You can select an expression that does not depend on any table:
SELECT 1 + 1;PostgreSQL, MySQL, and SQLite all accept this. Oracle requires a table, so it uses FROM dual. This form is handy for testing an expression or a function before you use it in a larger query.
Common errors
Read the error message first. It usually names the problem. These are the mistakes you are most likely to meet.
| Mistake | Typical cause | Fix |
|---|---|---|
| `column "name" does not exist` | The column name is misspelled or belongs to a different table. | Check the table definition with your client's describe command, or select `*` once. |
| `relation "employee" does not exist` (PostgreSQL) or `no such table` (SQLite) | The table name is misspelled, or you are connected to the wrong database or schema. | Confirm the name and the current database. |
| Syntax error near `FROM` | A comma after the last column in the list, for example `SELECT first_name, FROM employees`. | Remove the trailing comma. |
| Missing comma between columns | `SELECT first_name last_name FROM employees` | Separate columns with commas. See the callout below. |
| Clauses in the wrong order | `FROM employees SELECT first_name` | Write `SELECT` first, then `FROM`. |
Quoting names and strings
SQL uses two kinds of quotes, and they mean different things.
- Single quotes wrap text values, such as
'Sales'. - Double quotes wrap identifiers, which are names of tables and columns. This is standard SQL, and PostgreSQL and SQLite follow it. MySQL uses backticks for identifiers by default.
You rarely need quoted identifiers if you use plain lowercase names. If a table was created with a name like "Order Details", you must quote it every time.
Running a query safely
Because SELECT only reads, it is the safest statement to experiment with. For a large table, add a row limit while you explore, so you do not pull millions of rows into your client. A later chapter covers LIMIT and FETCH FIRST in detail. Here is a preview:
SELECT *
FROM employees
LIMIT 3;LIMIT works in PostgreSQL, MySQL, and SQLite. Other databases use the standard FETCH FIRST 3 ROWS ONLY.
Summary of the key points
SELECTlists the columns to return.FROMnames the table to read.- A basic query returns one result row per table row, in no guaranteed order.
SELECT *returns every column. Use it to explore, and name columns in code you keep.- Keywords are case-insensitive. Identifier case rules vary by database.
- Single quotes are for text values. Double quotes are for identifiers.
Exercise
A teammate writes SELECT first_name last_name FROM employees; and says the query "only returns last names." What does it actually return, and how do you fix it so it returns two columns?
Show answer
The database treats last_name as an alias for first_name, so the query returns one column that holds first names but is labeled last_name. Add a comma: SELECT first_name, last_name FROM employees;.
Exercise
Write a query that returns the department and salary columns of employees. Then explain why you cannot rely on the order of the rows it returns.
Show answer
SELECT department, salary FROM employees;. SQL does not guarantee row order unless the query includes ORDER BY. The order can change with updates, storage changes, or a different execution plan.