Navigating the SQL SELECT Statement

Navigating the SQL SELECT Statement

Greetings, and welcome to our second unit in the "Getting Started with SQL for Online Shopping" course!

You have already journeyed through what databases are, explored the world of SQL, and understood the usage of MySQL. Remember how we wrote our first SHOW TABLES SQL command to list all the tables in our Online Shop database? That was your first step into SQL syntax!

SQL, unlike many programming languages, doesn't deal with logic or flow control; instead, it understands, manipulates, and retrieves data stored in databases in a structured manner.

Getting to Know SELECT Syntax

In this lesson, we will cover the SELECT keyword. The syntax is straightforward.

General Syntax:

SELECT column1, column2, ..., columnN FROM table_name

In this syntax, you mention the column names that you want to retrieve, separated by commas. If you want to retrieve all columns, replace the column names with an asterisk (*).

Let's see how it works!

Querying the Database: Select All

Let's pull all the data from the Products table. We'll use the asterisk (*) symbol to do this.

SELECT * FROM Products;

This statement fetches all columns, along with their data, from the table Products. You would see product_id, product_name, product_price, category_id, and more, all displaying data related to the products available in the Online Shop.

Note: When using SELECT *, the database fetches every column and every row from the specified table. While this is useful for exploring the table’s structure or inspecting all data at once, it can be inefficient, especially for large tables. For instance, if the Products table has thousands of rows and includes columns like product_id, product_name, product_price, and category_id, SELECT * retrieves everything — which might include data you don’t need.

Best Practice: Use SELECT * sparingly. For precise and efficient queries, always specify the required columns.

SELECT for Specific Columns

Now, what if we want only specific information, such as the product name and product price? It's simple. We replace the asterisk with the required column names. Here's how:

SELECT product_name, product_price FROM Products;

In this example, we have fetched only the product_name and product_price columns from our Products table. Isn't fine-tuning our query results exciting?

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