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:
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.
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:
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.
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:
| Name | Club Country |
|---|---|
| FC Barcelona | Spain |
| Paris Saint-Germain | France |
