Tuesday, March 7, 2017

MySQL SELECT Statement with Examples

Databases store data for later retrieval. Ever wondered how that is achieved? It's the SELECT SQL command that does the job. 

That's what it's all about, retrieving data from the database tables. It's part of the data manipulation language that is responsible for query the data from the database

SQL SELECT statement syntax

It is the most frequently 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 the 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 from the SQL SELECT statement. If nothing is specified then ALL is assumed as the default.
  • {*| [fieldExpression [AS newName]} at least one part must be specified, "*" selected all the fields from the specified table name, fieldExpression performs some computations on the specified fields such as adding numbers or putting together two string fields into one.
  • FROM tableName is mandatory and must contain at least one table, multiple tables must be separated using commas or joined using the JOIN keyword.
  • WHERE condition is optional, it can be used to specify criteria in the result set returned from the query.
  • GROUP BY is used to put together records that have the same field values.
  • HAVING condition is used to specify criteria when working using 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 the columns in table. An example of a simple SELECT statement looks like the one shown below.
SELECT * FROM `members`;
The above statement selects all the fields from the members table. The semi-colon is a statement terminate. It's not mandatory but is considered a good practice to end your statements like that.

Practical examples

Click to download the myflix DB used for practical examples.
You can learn to import the .sql file into MySQL WorkBench
The Examples are performed on the following two tables Table 1: members table 
membership_ numberfull_namesgenderdate_ of_ birthphysical_ addresspostal_ addresscontct_ numberemail
1Janet JonesFemale21-07-1980First Street Plot No 4Private Bag0759 253 542janetjones@yagoo.cm
2Janet Smith JonesFemale23-06-1980Melrose 123NULLNULLjj@fstreet.com
3Robert PhilMale12-07-19893rd Street 34NULL12345rm@tstreet.com
4Gloria WilliamsFemale14-02-19842nd Street 23NULLNULLNULL
Table 2: movies table
movie_idtitledirectoryear_releasedcategory_id
1Pirates of the Caribean 4Rob Marshall20111
2Forgetting Sarah MarshalNicholas Stoller20082
3X-MenNULL2008NULL
4Code Name BlackEdgar Jimz2010NULL
5Daddy's Little GirlsNULL20078
6Angels and DemonsNULL20076
7Davinci CodeNULL20076
9Honey moonersJohn Schultz20058
1667% GuiltyNULL2012NULL
Getting members listing
Let's suppose that we want to get a list of all the registered library members from our database, we would use the script shown below to do that.
SELECT * FROM `members`;
Executing the above script in MySQL workbench produces the following results.
membership_numberfull_namesgenderdate_of_birthphysical_addresspostal_addresscontct_numberemail
1Janet JonesFemale21-07-1980First Street Plot No 4Private Bag0759 253 542janetjones@yagoo.cm
2Janet Smith JonesFemale23-06-1980Melrose 123NULLNULLjj@fstreet.com
3Robert PhilMale12-07-19893rd Street 34NULL12345rm@tstreet.com
4Gloria WilliamsFemale14-02-19842nd Street 23NULLNULLNULL

Our above query has returned all the rows and columns from the members table.
Let's say we are only interested in getting only the full_names, gender, physical_address and email fields only. The following script would help us to achieve this.
SELECT `full_names`,`gender`,`physical_address`, `email` FROM `members`;
Executing the above script in MySQL workbench produces the following results.
full_namesgenderphysical_addressemail
Janet JonesFemaleFirst Street Plot No 4janetjones@yagoo.cm
Janet Smith JonesFemaleMelrose 123jj@fstreet.com
Robert PhilMale3rd Street 34rm@tstreet.com
Gloria WilliamsFemale2nd Street 23NULL
Getting movies listing
Remember in our above discussion that we mention expressions been used in SELECT statements. Let's say we want to get a list of movie from our database. We want to have the movie title and the name of the movie director in one field. The name of the movie director should be in brackets. We also want to get the year that the movie was released. The following script helps us do that.
SELECT Concat(`title`, ' (', `director`, ')') , `year_released` FROM `movies`;
HERE
  • The Concat () MySQL function is used join the columns values together.
  • The line "Concat (`title`, ' (', `director`, ')')  gets the title, adds an opening bracket followed by the name of the director then adds the closing bracket.
String portions are separated using commas in the Concat () function.
Executing the above script in MySQL workbench produces the following result set.
Concat(`title`, ' (', `director`, ')')year_released
Pirates of the Caribean 4 ( Rob Marshall)2011
Forgetting Sarah Marshal (Nicholas Stoller)2008
NULL2008
Code Name Black (Edgar Jimz)2010
NULL2007
NULL2007
NULL2007
Honey mooners (John Schultz)2005
NULL2012
 Alias field names
The above example returned the Concatenation code as the field name for our results. Suppose we want  to use a more descriptive field name in our result set. We would use the column alias name to achieve that. The following is the basic syntax for the column alias name
SELECT `column_name|value|expression` [AS] `alias_name`;
HERE
  • "SELECT ` column_name|value|expression `" is the regular SELECT statement which can be a column name, value or expression.
  • "[AS]" is the optional keyword before the alias name that denotes the expression, value or field name will be returned as.
  • "`alias_name`" is the alias name that 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
Concatyear_released
Pirates of the Caribean 4 ( Rob Marshall)2011
Forgetting Sarah Marshal (Nicholas Stoller)2008
NULL2008
Code Name Black (Edgar Jimz)2010
NULL2007
NULL2007
NULL2007
Honey mooners (John Schultz)2005
NULL2012
Getting members listing showing the year of birth
Suppose we want to get a list of all the members showing the membership 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 that.
SELECT `membership_number`,`full_names`,LEFT(`date_of_birth`,4) AS `year_of_birth` FROM members;
HERE
  • "LEFT(`date_of_birth`,4)" the LEFT string function accepts the date of birth as the parameter and only returns 4 characters from the left.
  • "AS `year_of_birth`" is the column alias name that will be returned in our results. Note the AS keyword is optional, you can leave it out and the query will still work.
Executing the above query in MySQL workbench against the myflixdb gives us the results shown below.
membership_numberfull_namesyear_of_birth
1Janet Jones1980
2Janet Smith Jones1980
3Robert Phil1989
4Gloria Williams1984

SQL using MySQL Workbench

We are now going to use MySQL workbench to generate the script that will display all the field names from our categories table.
1.       Right Click on the Categories Table. Click on "Select Rows - Limit 1000"
2.       MySQL workbench will automatically create a SQL query and paste in the editor.
3.       Query Results will be show
MySQL SELECT Statement with Examples
Notice that we didn't write the SELECT statement ourselves. MySQL workbench generated it for us. 

Why use the SELECT SQL command when we have MySQL Workbench?

Now, you might be thinking why learn the SQL SELECT command to query data from the database when you can simply use a tool such as MySQL workbench's to get the same results without knowledge of the SQL language. Of course that is possible, but learning how to use the SELECT command gives you more flexibility and control over your SQL SELECT statements.
MySQL workbench falls in the category of "Query by Example" QBE tools. It's intended to help generate SQL statements faster to increase the user productivity.
Learning the SQL SELECT command can enable you to create complex queries that cannot be easily generated using Query by Example utilities such as MySQL workbench.
To improve productivity you can generate the code using MySQL workbench then customize it to meet your requirements. This can only happen if you understand how the SQL statements work!
MySQL SELECT Statement with Examples

Summary

  • The SQL SELECT keyword is used to query data from the database and it's the most commonly used command.
  • The simplest form has the syntax "SELECT * FROM tableName;"
  • Expressions can also be used in the 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 develop SQL statements, execute them and produce the output result in the same window.

0 comments:

Post a Comment