Mysql LQB 7
Mysql LQB 7
7. SELECT STATEMENT
After completing this chapter, you will be able to do the following:
• Identify keywords and clauses in a SELECT statement
• Select and view one column and all columns of a table
• Display multiple columns of a table
• Use a column alias to clarify the contents of a particular column
• Perform basic arithmetic operations in the SELECT clause
• Remove duplicate lists by using the DISTINCT.
• Use concatenation to combine fields, literals, and other data
• Use select statement with AND, OR, AND & OR, IN, LIKE, BETWEEN, NOT, and IS NOT
NULL operators.
• Use select statement with WHERE, ORDER BY, GROUP BY and HAVING clauses.
7.1. Select Statement
SELECT statement is used to query the database and retrieve selected data that follow the conditions
we want. The select statement is most common and used to retrieve data from a table in the database.
Syntax: SELECT expressions FROM tables WHERE conditions;
There are some optional clauses in SELECT statement:
• WHERE Clause: It specifies which rows to retrieve.
• GROUP BY Clause: Groups rows that share a property so that the aggregate function can
be applied to each group.
• HAVING Clause: It selects among the groups defined by the GROUP BY clause.
• ORDER BY Clause: It specifies an order in which to return the rows.
7.2. Selecting All Data in a Table
To have the SELECT statement return all data from a specific table, type an asterisk (*) after SELECT.
This statement retrieves all data stored in the table. The asterisk (*) is a symbol that instructs to include
all columns in the table. Asterisk (*) can be used only in the SELECT clause of a SELECT statement.
Example: to select all data from student table: select * from Student;
STUDENT
StudentID FirstName LastName CITY
1
By: Worku Muluye
1 Abebe Dawit Addis Ababa
2 Ermias Yonas Adama
3 Sara Abraham Bahir Dar
7.3. Selecting One Column from a Table
Choosing specific columns in a SELECT statement is called projection. You can select one column
or as many as all columns contained in the table. Example: to select one column its name is CITY
from student table:
SELECT CITY from Student;
CITY
Addis Ababa
Adama
Bahir Dar
7.4. Selecting Multiple Columns from a Table
When specifying more than one column in the SELECT clause, commas should separate the columns
listed. Although a space has been entered after the comma, it’s not part of the SELECT statement’s
required syntax. The space simply improves the statement’s readability. Select columns its name is
StudentID, first name and city from student table:
Example: select StudentID, FirstName, CITY from Student;
StudentID FirstName CITY
1 Abebe Addis Ababa
2 Ermias Adama
3 Sara Bahir Dar
7.5. Concatenation
Combining the contents of two or more columns is known as concatenation. To concatenate the output
of a query, use two vertical bars, or pipes (| |), between the fields you’re combining. On a keyboard,
this symbol is located above the backslash (\). For example, for a list of student names, you might
prefer to have them combined so that they appear as a single column rather than separate first name
and last name columns. Example: select FirstName | | LastName from Student;
FirstName||LastName
AbebeDawit
ErmiasYonas
SaraAbraham
To have insert a blank space, you must concatenate the FirstName and LastName fields with a string
literal. A string literal instructs to interpret the characters you have entered “literally,” not to consider
2
By: Worku Muluye
them a keyword or command. A string literal must be enclosed in single quotation marks (‘ ‘). For
example, you need a Student listing in the following format: StudentID: FirstName, LastName.
select StudentID ||’ : ’||FirstName ||‘ , ’|| LastName “Student Information” from Student;
Student Information
1: Abebe, Dawit
2: Ermias, Yonas
3: Sara, Abraham
7.6. Select Distinct
The SQL DISTINCT command is used with SELECT key word to retrieve only distinct or unique
data.
Syntax: SELECT DISTINCT column-name, column-name FROM table-name;
Here is a table of student from where we want to retrieve distinct city information.
Example: SELECT DISTNICT City FROM Student;
CITY
Addis Ababa
Adama
Bahir Dar
DISTINCT Clause with single expression If you use a single expression, then the MySQL
DISTINCT clause will return a single field with unique records (no duplicate record).
Example: SELECT DISTINCT address FROM Student;
DISTINCT with multiple expressions: If you use multiple expressions with DISTINCT Clause then
MySQL DISTINCT clause will remove duplicates from more than one field in your SELECT
statement.
Example: SELECT DISTINCT FirstName, address FROM Student
3
By: Worku Muluye
Example: SELECT TOP 2 * FROM Student;
It will return the following table:
StudentID FirstName LastName CITY
1 Abebe Dawit Addis Ababa
2 Ermias Yonas Adama
7.8. Select AS
SQL AS is used to assign temporarily a new name to a table column. It makes easy presentation of
query results and allows the developer to label results more accurately without permanently renaming
table columns. The optional keyword of AS has been included to distinguish between the column name
and the column alias. If the column alias contains spaces or special symbols, or if you don’t want it to
appear in all uppercase letters, you must enclose it in quotation marks (" ").
Syntax: SELECT Old-ColName1 AS "NewColName1", OldColMame2 AS "NewColName2”, …,
FROM Table-Name;
E.g. SELECT StudentID AS "ID" FirstName As "FirstName", LastName, City, FROM Student;
Let us take a table named Student, it contains:
ID FirstName LastName CITY
1 Abebe Dawit Addis Ababa
2 Ermias Yonas Adama
3 Sara Abraham Bahir Dar
4 Ermias Elias Adama
7.9. Select Date
SQL SELECT DATE is used to retrieve a date from a database. If you want to find a particular date
from a database, you can use this statement.
For example: let's see the query to get all the records after '2013-12-12'.
SELECT * FROM table-name WHERE your date-column >= '2013-12-12'
Let's see the another query to get all the records after '2013-12-12' and before '2013-12-13' date.
SELECT* FROM table-name where datecolumn<'2013-12-13' and datecolumn>='2013-12-12';
If you want to compare the dates within the query, you should use BETWEEN operator to compare
the dates.
SELECT * FROM table-name WHERE datecolumn BETWEEN ‘2012-12-12’ and ‘2013-12-12’;
Or if you are looking for one date in particular you can use. You should change the date parameter
into the acceptable form.
4
By: Worku Muluye
SELECT* FROM table-name WHERE cast (datediff (day, 0, date) as datetime)=‘2012-12-12’;
5
By: Worku Muluye
Example: SELECT * FROM Student WHERE ID BETWEEN 1 AND 3;
BETWEEN condition with date facilitates you to retrieve records according to date.
Example: SELECT * FROM employee WHERE working_date BETWEEN CAST ('2015-01-24' AS
DATE) AND CAST ('2015-01-25' AS DATE);
7.10.5. IN
SQL IN is an operator used to reduce the need to use multiple SQL "OR" conditions. It is used in
SELECT, INSERT, UPDATE or DELETE statement. Advantage of IN is to minimize the use of
multiple OR operator. Syntax: Expression IN (value 1, value 2 ... value n);
Expression: It specifies a value to test.
value1, value2, ... or value_n: These are the values to test against expression. If any of these values
matches expression, then the IN condition will evaluate to true.
Example: SELECT * FROM student WHERE FirstName IN (Abebe, Nathan, Sara)
StudentID FirstName LastName CITY
1 Abebe Dawit Addis Ababa
3 Sara Abraham Bahir Dar
Let’s take another example with numeric values.
SELECT * FROM Student WHERE StudentID IN (1, 4, 7, 20);
StudentID FirstName LastName CITY
1 Abebe Dawit Addis Ababa
4 Ermias Elias Adama
7.10.6. NOT
NOT operator is opposite of IN condition. NOT operator is used to negate a condition in a SELECT,
INSERT, UPDATE or DELETE statement.
NOT Operator with IN condition:
Example: SELECT * FROM Student WHERE firstname NOT IN ('Abebe', 'Dawit', 'Daniel');
NOT Operator with IS NULL condition:
Example: SELECT * FROM Student WHERE firstname IS NOT NULL;
NOT Operator with LIKE condition:
Example: SELECT * FROM Student WHERE firstname NOT LIKE 'A%';
NOT Operator with BETWEEN condition:
Example: SELECT * FROM Student WHERE ID NOT BETWEEN 3 AND 5;
6
By: Worku Muluye
7.10.7. IS Null
Null values are used to represent missing unknown data. This means that field has null value. We
should not compare null value with 0. IS NULL condition is used to check if there is a NULL value
in the expression. It is used with SELECT, INSERT, UPDATE and DELETE statement.
Syntax: SELECT Col, Col2, Col3 FROM Table-Name WHERE Colname IS NULL;
Example: SELECT * FROM Student WHERE firstname IS NULL;
Note: Here, you are getting the empty result because there is no NULL value in firstname column.
STUDENT
StudentID FirstName LastName CITY
1 Abebe Dawit Addis Ababa
2 Ermias Yonas Adama
3 Sara Abraham Bahir Dar
4 Ermias Elias Adama
5 Alemu Daniel Null
Let's see the query to get all the records where City is NULL from Student table:
SELECT * FROM Student WHERE City IS NULL;
StudentID FirstName LastName CITY
5 Alemu Daniel Null
Note: You can insert data a column which has null value by using Update statement. Example to
change null value into Wolkite under a city column in student table.
Example: UPDATE Student SET city =‘Wolkite’ WHERE city IS NULL;
STUDENT
StudentID FirstName LastName CITY
5 Alemu Daniel Wolkite
7.10.8. IS NOT NULL
MySQL IS NOT NULL condition is used to check the NOT NULL value in the expression. It is used
with SELECT, INSERT, UPDATE and DELETE statements.
Syntax: expression IS NOT NULL
expression: It specifies a value to test if it is not NULL value.
Example: SELECT * FROM Student WHERE firstname IS NOT NULL;
Let's see the query to get all the records where City is NOT NULL
SELECT * FROM Student WHERE City IS NOT NULL;
StudentID FirstName LastName CITY
1 Abebe Dawit Addis Ababa
2 Ermias Yonas Adama
3 Sara Abraham Bahir Dar
7
By: Worku Muluye
4 Ermias Elias Adama
7.10.9. LIKE
LIKE condition is used to perform pattern matching to find the correct result. It is used in SELECT,
INSERT, UPDATE and DELETE statement with the combination of WHERE clause.
Syntax: expression LIKE pattern [ ESCAPE 'escape_character' ]
expression: It specifies a column or field.
pattern: It is a character expression that contains pattern matching.
escape_character: It is optional. It allows you to test for literal instances of a wildcard character such
as % or _. If you do not provide the escape_character, MySQL assumes that "\" is the escape_character.
Using % (percent) Wildcard: SELECT firstname FROM Student WHERE address LIKE 'Abel%';
Using _ (Underscore) Wildcard: We are using the same table "Student" in this example too.
Example: SELECT Firstname FROM Student WHERE address LIKE 'Abe_aw';
Using NOT Operator: You can also use NOT operator with MySQL LIKE condition. This example
shows the use of % wildcard with the NOT Operator.
SELECT Firstname FROM Student WHERE address NOT LIKE 'Abel%';
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_%' Finds any values that start with "a" and are at least 3
characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
8
By: Worku Muluye
Functions are classified based on the type of data on which they perform the operation. The following
are the different types of functions:
• Arithmetic Functions: perform take numeric data; date functions take date type data and string
functions take strings.
• Date and Time functions
• String functions
• Conversion functions: are used to convert the given value from one type to another.
• Miscellaneous functions: perform operations on any type of data.
• Aggregate (Group) functions:
7.11.1. Aggregate (Group) Function
Aggregate (Group) functions are used to perform operations on the groups created by GROUP BY
clause. Group or aggregate functions perform their operation on a group (a collection of rows). All the
remaining functions are called as single-row functions as they return a result for each row.
Syntax: SELECT Aggregate/GroupFunction (aggregate_expression) FROM table_name [WHERE
conditions];
Aggregate/GroupFunction: Can be one of the group function such as Count, Sum, Max, Min …etc.
aggregate_expression: It specifies the column (expression) who’s not null values will be counted.
table_name: It specifies the tables, from where you want to retrieve records. There must be at least
one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the records to
be selected.
7.11.1.1. Count () Function
The count() function is used to return the count of an expression. It is used when you need to count
some records of your table.
Syntax: SELECT COUNT (aggregate_expression) FROM table_name [WHERE conditions];
Example: SELECT COUNT(FirstName) FROM Student;
Here, you can see that that the COUNT function calculates the total number of students in the table.
Example2: SELECT COUNT (*) FROM Employee;
7.11.1.2. Min () Function
The MIN () function is used to return the minimum value of an expression.
Syntax: SELECT MIN(aggregate-expression) FROM tables [WHERE conditions];
9
By: Worku Muluye
Example: Select "Employee" table and fetch the minimum salary of the table.
SELECT MIN(salary) AS "Lowest Salary" FROM Employee;
7.11.1.3. Max () Function
MAX () function is used to return the maximum value of an expression.
Syntax: SELECT MAX(aggregate-expression) FROM tables [WHERE conditions];
Example: Select "Employee" table and fetch the maximum salary of the table.
SELECT MAX(salary) AS "Highest Salary" FROM Employee;
7.11.1.4. Sum () Function
The SUM () function is used to return the sum of an expression in a SELECT statement.
Syntax: SELECT SUM(aggregate-expression) FROM tables [WHERE conditions];
Example1: SELECT SUM(salary) AS "Sum Salary" FROM Employee;
Example2: SELECT SUM (working_hours) AS "Total working hours" FROM employee WHERE
working_hours > 5;
EMPLOYEE
Emp-Name Address Salary
Abebe Addis Ababa 15000
Dawit Adama 18000
Tomas Bahir Dar 20000
Daniel Hawassa 25000
If you want to know how the combined total salary of all employee whose salary is above 20000 per
month.
SELECT SUM (salary) AS "Total Salary" FROM Employee WHERE salary >=20000;
After using this SQL SELECT SUM example, it will produce the result containing the sum of the
salary greater than 20000. Total Salary: 45,000. We can find the sum of all salaries without using
where clause.
SELECT SUM (salary) AS "Total Salary" FROM Employee;
The result is: Total Salary: 78,000
7.11.1.5. AVG () Function
AVG () function is used to return the average value of an expression.
Syntax: SELECT AVG(aggregate-expression) FROM tables [WHERE conditions];
Example: Select "Employee" table and fetch the average salary of the table.
SELECT AVG(salary) AS "Average Salary" FROM Employee;
10
By: Worku Muluye
7.11.1.6. First function
The MySQL first function is used to return the first value of the selected column. Here, we use limit
clause to select first record or more.
Syntax: SELECT column_name FROM table_name LIMIT 1;
Example, to SELECT FIRST element: SELECT FirstName FROM Student LIMIT 1;
To SELECT FIRST two records: SELECT FirstName FROM Student LIMIT 2;
7.11.1.7. Last Function
MySQL last function is used to return the last value of the selected column.
Syntax: SELECT column_name FROM table_name ORDER BY column_name DESC LIMIT 1;
Example: SELECT FirstName FROM Student ORDER BY StudentID DESC LIMIT 1;
Return the last FirstName ordering by FirstName:
SELECT FirstName FROM Student ORDER BY FirstName DESC LIMIT 1;
7.12. Select Random
The SQL SELECT RANDOM() function returns the random row. It can be used in online exam to
display the random questions. There are a lot of ways to select a random record or row from a
database table. Each database server needs different SQL syntax.
In MySQL Syntax: SELECT column FROM table ORDER BY RAND ( ) LIMIT 1;
Summary
A basic query includes the SELECT and FROM clauses, the only mandatory clauses in a SELECT
statement. To view all columns in a table, use an asterisk (*) or list all the column names in the
SELECT clause. To display a specific column or set of columns, list the column names in the SELECT
clause (in the order in which you want them to appear). When listing column names in the SELECT
clause, a comma must separate column names. A column alias can be used to clarify the contents of a
particular column. If the alias contains spaces or special symbols, or if you want to display the column
with any lowercase letters, you must enclose the column alias in quotation marks (" "). To specify
which table contains the columns you want, you must list the table name after the keyword FROM.
Basic arithmetic operations can be performed in the SELECT clause. NULL values indicate an absence
of a value and might have an undesirable effect on arithmetic operations.
To remove duplicate listings, include the DISTINCT. A string literal is a set of characters enclosed in
single quotation marks (''); it’s interpreted as is, not treated as a keyword or command. Use vertical
bars (| |) to combine, or concatenate, fields, literals, and other data.
11
By: Worku Muluye
Review Questions
1. What are the two required clauses for a SELECT statement?
2. What is the purpose of the SELECT statement?
3. What does an asterisk (*) in the SELECT clause of a SELECT statement represent?
4. What is the purpose of a column alias?
5. How do you indicate that a column alias should be used?
6. When is it appropriate to use a column alias?
7. What are the guidelines to keep in mind when using a column alias?
8. How can you concatenate columns in a query?
9. What is a NULL value?
10. Discuss about logical operators?
11. What is the difference between IN, OR, AND, BETWEEN and LIKE operators?
12. How to use IN, OR, AND, BETWEEN and LIKE operators with INSERT, SELECT, UPDATE
and DELETE statements?
12
By: Worku Muluye