Sub topic 1
Your first query: SELECT and FROM
A SQL query asks a database for information. This chapter assumes you know that a table contains rows and columns. You will use SELECT to choose which columns to return and FROM to name the table that contains them.
Prerequisites
You should understand these ideas:
- A table stores related data.
- A row is one record in a table.
- A column stores one kind of value, such as a name or salary.
- You have access to a SQL database or client containing an
employeestable.
A simple employees table might contain columns such as first_name, last_name, department, and salary.
The basic shape of a query
The smallest useful query has two clauses:
SELECT column_name
FROM table_name;A clause is a part of a SQL statement that performs one job. SELECT identifies the columns you want to see. FROM identifies the table from which the database reads those columns.
For example:
SELECT first_name, last_name, salary
FROM employees;This query returns the first name, last name, and salary for every row in employees. The result is a new table-shaped result, but it does not change the stored table.
The semicolon marks the end of the statement. Many SQL tools can run a query without it, but using semicolons makes statement boundaries clear.
Choosing columns with SELECT
Separate multiple column names with commas. The order in the SELECT list controls the order of columns in the result:
SELECT salary, first_name, department
FROM employees;The database returns salary first, then first_name, then department. The order of rows is not guaranteed unless you add an ORDER BY clause, which you will learn later.
You can use an asterisk (*) to request every column:
SELECT *
FROM employees;This is useful when exploring an unfamiliar table. It is usually better to name columns in application queries. Explicit columns make the result easier to understand and prevent unexpected extra columns when the table structure changes.
How the database reads the query
Although SQL writes SELECT before FROM, the database first needs a data source. You can think of the basic operation like this:
The database reads the employees table, takes the named columns from each row, and returns those values. At this stage, every row is included.
Common mistakes
- Misspelling a table or column name causes an error.
- Forgetting a comma between column names causes a syntax error.
- Putting column names after
FROMreverses the roles of the clauses. - Assuming rows are sorted can produce unreliable results. Add
ORDER BYwhen order matters. - Using
SELECT *can expose columns you did not intend to return.
Exercise
Write a query that returns the employee_id and department columns from the employees table.
Show answer
SELECT employee_id, department FROM employees;