Exploring SELECT Statements

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.

Understanding 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.
Basic SELECT Statement

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.

Selecting Specific Columns

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 specifies movie_name and release_date explicitly, meaning only these columns will be retrieved.
  • The FROM clause still indicates the movies table as the source.
Using Aliases in SELECT Statements

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, the movie_name column will be called "Name".
  • release_date AS "Date": In the output, the release_date column will be named "Date".

The output of the query is:

Notice how the column names have changed in the output.

Summary

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal