Navigating the SQL SELECT Statement

Navigating the SQL SELECT Statement

Greetings, and welcome to our second unit in the "Learning SQL with Leo Messi" 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 a Messi 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 Clubs table. We'll use the asterisk (*) symbol to do this.

SELECT * FROM Clubs;

This statement fetches all columns, along with their data, from the table Clubs. You would see club_id, club_name, club_country, and more, all displaying data from the Lionel Messi's clubs table.

SELECT for Specific Columns

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

SELECT club_name, club_country FROM Clubs;

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

Alias in SQL: Using AS Keyword

Can we rename column names in the output for better understanding? Yes, we can! Thanks to SQL aliasing features. The AS keyword is used to rename a column or table with an alias.

SELECT club_name AS Name, club_country AS "Club Country" FROM Clubs;

In this statement, AS is used to rename club_name to Name and club_country to Club Country in our output. Notice that we use double quotes around Club Country because the new name contains spaces. This way, our result set has more comprehensible column names.

The output of this query would be:

NameClub Country
FC BarcelonaSpain
Paris Saint-GermainFrance
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