Lesson 5

SELECT statement

Understanding SQL SELECT Statements

The SELECT statement is at the heart of retrieving data from a SQL database. It specifies which columns and tables to return data from.

SELECT Syntax

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.

Query a Single Table

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.

Return All Columns

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.

Query Multiple Tables

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.

Summary

In summary, SELECT is used to specify:

  • Which columns to return
  • Which tables to query
  • Whether to return all or specific columns

Mastering the basics of writing SELECT statements is foundational to retrieving and analyzing data in SQL.

Column Aliases

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:

  • Giving columns more descriptive names
  • Shortening long column names
  • Renaming columns from different tables that have the same name

To alias a column, add the alias after the name separated by a space or AS keyword. The AS is optional.

Takeaways:

  • Aliases rename columns in the result set
  • Improve readability and disambiguate columns
  • Added after the column name separated by a space or AS

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.

Select all data from authors
Select all data from reviews
List the first and last names of all customers
Display the title and ISBN of every book in the books table.
Display the 'first_name' column as 'FirstName' from the authors table
Tables used in this quizz:
No Data

©2024 SQLZap - Learn SQL Interactively

Twitter