Lesson 5
The SELECT statement is at the heart of retrieving data from a SQL database. It specifies which columns and tables to return data from.
The basic syntax is:
SELECT column1, column2, ...
FROM table_name;
This queries specific columns from a single table.
You can select as many columns as you want, or use SELECT *
to return all columns.
To query a single table, refer to it after FROM:
SELECT id, name
FROM customers;
This returns the id and name for all rows in the customers table.
Use the *
wildcard to return all columns:
SELECT *
FROM products;
This can be useful for quickly inspecting the full contents of a table during development.
You can query multiple tables by separating them with commas:
SELECT *
FROM customers, orders;
This will produce a cross join and return all combinations of rows between the two tables.
In summary, SELECT is used to specify:
Mastering the basics of writing SELECT statements is foundational to retrieving and analyzing data in SQL.
You can alias column names in the SELECT clause to return them with more readable or descriptive names:
SELECT id AS customer_id,
name AS customer_name
FROM customers;
Now the id column is returned as customer_id and name as customer_name.
Aliases are helpful for:
To alias a column, add the alias after the name separated by a space or AS keyword. The AS is optional.
Leveraging SQL features like column aliases allows you to shape and customize the data returned from queries. Mastering the finer details of SELECT can make you a better SQL developer.