Welcome back! In the previous lesson, you learned the basics of databases and SQL, focusing on using PostgreSQL. You also wrote some initial SQL queries to get familiar with listing tables and retrieving data. In this lesson, you will learn how to retrieve specific data using the SELECT
statement.
The SELECT
statement is one of the fundamental building blocks of SQL. Its primary purpose is to retrieve data from a database table. Here's a breakdown of a basic SELECT
statement:
SELECT
: This keyword initiates the retrieval operation.column1, column2, ...
: These are the columns you want to retrieve from the table.FROM
: This keyword specifies the table from which to retrieve the data.table_name
: The name of the table to retrieve data from.
In the last lesson, we learned how to use *
to select all columns from a table. The asterisk (*
) is a wildcard character that tells SQL to select all columns from the movies
table. To review:
This code outputs:
Notice that the output contains all 4 column names.
Now, let's say we only want to retrieve the movie_name
and release_date
columns from the movies
table. Here's how you can do it:
- The
SELECT
statement now specifiesmovie_name
andrelease_date
explicitly, meaning only these columns will be retrieved. - The
FROM
clause still indicates themovies
table as the source.
Using aliases can make your output more readable and meaningful. Aliases are temporary names assigned to columns or tables for the duration of the query. You achieve this with the AS
keyword.
movie_name AS "Name"
: In the output, themovie_name
column will be called "Name".release_date AS "Date"
: In the output, therelease_date
column will be named "Date".
The output of the query is:
Notice how the column names have changed in the output.
In this lesson, you learned how to write SQL queries using the SELECT
statement to retrieve data from a database. We covered:
- The structure of a basic
SELECT
statement. - Selecting all columns from a table.
- Selecting specific columns.
- Using aliases to rename columns in the output.
Remember, practice is key to mastering SQL. In the next section, you'll find exercises to reinforce what you've learned. Take your time to work through them, and feel free to refer back to this lesson for guidance.
Good luck, and happy querying!
