SELECT statement in sql

What is a SELECT query in MySQL?
SELECT QUERY is used to retrieve data from a MySQL database. Databases store data for later retrieval. The purpose of MySQL Select is to return one or more rows from database tables that match given criteria. The select query can be used in a scripting language such as PHP, Ruby, or you can execute it from the command line.
SQL SELECT statement syntax
This is the most commonly used SQL command and has the following general syntax
SELECT [DISTINCT|ALL ] { * | [fieldExpression [AS newName]} FROM tableName [alias] [WHERE condition][GROUP BY fieldName(s)] [HAVING condition] ORDER BY fieldName(s)
HERE
- SELECT is an SQL keyword that lets the database know that you want to retrieve data.
- [DISTINCT | ALL] are optional keywords that can be used to fine-tune the results returned by the SQL SELECT statement. If nothing is specified, the default is ALL.
- {* | [fieldExpression [AS newName]} must have at least one part specified, "*" selects all fields from the specified table name, fieldExpression performs some calculation on the specified fields, such as adding numbers or concatenating two string fields into one.
- FROM tableName is required and must contain at least one table, multiple tables must be separated by commas or joined using the JOIN keyword.
- If a condition is optional, it can be used to specify criteria in the result set returned by the query.
- GROUP BY is used to combine records that have the same field values.
- The HAVING clause is used to specify criteria when working with the GROUP BY keyword.
- ORDER BY is used to specify the sort order of the result set.
*
The star symbol is used to select all columns in a table. An example of a simple SELECT statement looks like the one below.
SELECT * FROM `members`;
The above statement selects all fields from the members table. A semicolon completes this statement. This is not required, but it is considered good practice to end your statements this way.
Practical examples
Click to download the myflix database used for practical examples.
You can learn how to import a .sql file into MySQL WorkBench.
Examples run in the following two tables
Table 1: table of participants
membership number | full names | Floor | Date of Birth | Physical adress | mailing address | contract number | |
---|---|---|---|---|---|---|---|
one | Janet Jones | female | 21-07-1980 | First Street Plot No. 4 | Private bag | 0759 253 542 | janetjones@yagoo.cm |
2 | Janet Smith Jones | female | 23-06-1980 | Melrose 123 | NULL | NULL | jj@fstreet.com |
3 | Robert Phil | the male | 12-07-1989 | 3rd Street, 34 | NULL | 12345 | rm@tstreet.com |
4 | Gloria Williams | female | 14-02-1984 | 2nd street, 23 | NULL | NULL | NULL |
Table 2: movie table
movie_id | title | director | year_released | category_id |
---|---|---|---|---|
one | Pirates of the Caribbean 4 | Rob Marshall | 2011 | one |
2 | Forget Sarah Marshal | Nicholas Stoller | 2008 | 2 |
3 | X-Men | NULL | 2008 | NULL |
4 | Codename black | Edgar Jimz | 2010 | NULL |
5 | daddies little girls | NULL | 2007 | eight |
6 | Angels and Demons | NULL | 2007 | 6 |
7 | The Da Vinci Code | NULL | 2007 | 6 |
9 | honey moons | John Schultz | 2005 | eight |
sixteen | 67% guilty | NULL | 2012 | NULL |
Getting a list of participants
Let's assume that we want to get a list of all registered members of a library from our database, we will use the script shown below to do this.
SELECT * FROM `members`;
Running the above script in MySQL Workbench gives the following results.
membership number | full names | Floor | Date of Birth | Physical adress | mailing address | contract number | |
---|---|---|---|---|---|---|---|
one | Janet Jones | female | 21-07-1980 | First Street Plot No. 4 | Private bag | 0759 253 542 | janetjones@yagoo.cm |
2 | Janet Smith Jones | female | 23-06-1980 | Melrose 123 | NULL | NULL | jj@fstreet.com |
Our query above returned all rows and columns from the members table.
Let's say we're only interested in getting full names, gender, physical address, and email address only. The following script will help us achieve this.
SELECT `full_names`,`gender`,`physical_address`, `email` FROM `members`;
Running the above script in MySQL Workbench gives the following results.
full names | Floor | Physical adress | |
---|---|---|---|
Janet Jones | female | First Street Plot No. 4 | janetjones@yagoo.cm |
Janet Smith Jones | female | Melrose 123 | jj@fstreet.com |
Robert Phil | the male | 3rd Street, 34 | rm@tstreet.com |
Gloria Williams | female | 2nd street, 23 | NULL |
Getting a list of movies
Remember in our discussion above that we are referring to expressions used in SELECT statements. Let's say we want to get a list of movies from our database. We want the movie title and director's name to be in the same field. The director's name should be in brackets. We also want to know the year the movie was released. The following script helps us with this.
SELECT Concat(`title`, ' (', `director`, ')') , `year_released` FROM `movies`;
HERE
- The MySQL Concat() function is used to concatenate column values.
- The line "Concat (` title`, '(', Director ", ')') gets the title, adds an opening parenthesis followed by the director's name, then adds a closing parenthesis.
String parts are separated by commas in the concat() function.
Running the above script in MySQL Workbench results in the following set of results.
Concat (`title`, '(', Director`, ')') | year_released |
---|---|
Pirates of the Caribbean 4 (Rob Marshall) | 2011 |
Forget Sarah Marshal (Nicholas Stoller) | 2008 |
NULL | 2008 |
Codename Black (Edgar Jimz) | 2010 |
NULL | 2007 |
NULL | 2007 |
NULL | 2007 |
Honeymoons (John Schultz) | 2005 |
NULL | 2012 |
Alias ​​field names
The example above returned the concatenation code as the field name for our results. Let's say we want to use a more descriptive field name in our result set. We would use a column alias to achieve this. Following is the basic syntax for a column alias.
SELECT `column_name|value|expression` [AS] `alias_name`;
HERE
- "SELECT` column_name | value | expression `" is a regular SELECT statement, which can be a column name, value, or expression.
- "[AS]" is an optional keyword before the alias name denoting an expression, value, or field name to be returned as.
- "alias_name" is the alias we want to return in our result set as the field name.
The above query with a more meaningful column name
SELECT Concat(`title`, ' (', `director`, ')') AS 'Concat', `year_released` FROM `movies`;
We get the following result
Concat | year_released |
---|---|
Pirates of the Caribbean 4 (Rob Marshall) | 2011 |
Forget Sarah Marshal (Nicholas Stoller) | 2008 |
NULL | 2008 |
Codename Black (Edgar Jimz) | 2010 |
NULL | 2007 |
NULL | 2007 |
NULL | 2007 |
Honeymoons (John Schultz) | 2005 |
NULL | 2012 |
Getting a list of participants with their year of birth
Suppose we want to get a list of all members with their member number, full names, and year of birth, we can use the LEFT string function to extract the year of birth from the date of birth field. The script shown below helps us to do this.
SELECT `membership_number`,`full_names`,LEFT(`date_of_birth`,4) AS `year_of_birth` FROM members;
HERE
- The "LEFT(` date_of_birth`, 4)" string function LEFT takes a date of birth as a parameter and returns only 4 characters from the left.
- "AS` year_of_birth`" is the column alias that will be returned in our results. Note that the AS keyword is optional , you can leave it out and the query will still work.
Running the above query in MySQL Workbench against myflixdb gives us the results shown below.
membership number | full names | year of birth |
---|---|---|
one | Janet Jones | 1980 |
2 | Janet Smith Jones | 1980 |
3 | Robert Phil | 1989 |
4 | Gloria Williams | 1984 |
SQL using MySQL Workbench
We will now use MySQL Workbench to generate a script that will display all the field names from our category table.
1. Right-click the category table. Click "Select Rows - Limit 1000"
2. MySQL Workbench will automatically generate the SQL query and paste it into the editor.
3. Query results will be shown
Note that we didn't write the SELECT statement ourselves. MySQL workbench generated this for us.
Why use SELECT SQL command when we have MySQL Workbench?
Now you might be thinking why learn the SQL SELECT command to query data from a database when you can just use a tool like the MySQL workbench to get the same results without knowing the SQL language. Of course it's possible, but learning how to use the SELECT command gives you more flexibility and control over SQL SELECT statements .
MySQL Workbench belongs to the " Query by Example " category of QBE tools . It is designed to help generate SQL statements faster to improve user productivity.
Learning the SQL SELECT command can allow you to create complex queries that cannot be easily generated with Query by Example utilities such as MySQL Workbench.
To improve performance, you can generate the code using MySQL and then customize it to your needs . This can only happen if you understand how SQL statements work!
Summary
- The SQL SELECT keyword is used to query data from a database and is the most commonly used command.
- The simplest form has the syntax "SELECT * FROM tableName;"
- Expressions can also be used in a select statement. Example "SELECT Quantity + Price FROM SALES"
- The SQL SELECT command can also have other optional parameters such as WHERE, GROUP BY, HAVING, ORDER BY. They will be discussed later.
- MySQL Workbench can help you develop SQL statements, execute them, and display the result in the same window.