T3_L1_SELECTSIMPLE
T3_L1_SELECTSIMPLE
Topic 3
Lesson 1 – SQL SELECT on one table
Chapter 3 Murach’s MySQL
2
Extracting data from a single table
SELECT field_list
FROM table
WHERE condition_true
ORDER BY order_field_list
LIMIT num_tuples;
id name school credits_earned credits_req
1 Smith Khoury 32 120
3
AS keyword
4
Computed result and the AS keyword
Write a query that returns the ID, Name and the number
of credits left for the student to graduate
5
ORDER BY clause
You can specify multiple fields to order by as well as different
ordering directions. ASC – signifies ORDER BY with values
increasing. DESC – signified ORDER BY with values
decreasing.
Extended format:
ORDER BY expression [ASC|DESC][, expression
[ASC|DESC]]
6
Ordering by field position
Rather than specifying the name of the field in the output, you
can specify the field position in the output. This places a
dependency between the field list and the order_by list.
7
Limit clause
Limit the number of tuples that are returned as the result. The
default is to return the first n tuples in the result. But you can
also specify an offset to start returning from. The extended
syntax for the clause is:
LIMIT [offset,] row_count
EXAMPLE:
SELECT * FROM STUDENT LIMIT 2, 2;
8
WHERE clause
The format of the WHERE clause is:
expression1 operation expression2
The supported operations are: = equals, < less than, > greater
than, <= less than or equal, >= greater than or equal, <> not
equal , != not equal, LIKE (a limited regular expression) .
LIKE has 2 special characters The under score matches any
one character, % matches any collection of characters.
9
WHERE clause allows multiple conditions
10
IN Keyword
11
BETWEEN Keyword
12
LIKE Keyword
13
SQL Practice (1)
Write SQL statements to :
1. Extract all student names from the student table
2. Extract all Khoury college students from the student table
3. Extract all Khoury college students from the student table
ordering the results by the last name
4. Extract 5 Khoury college students from the student table
ordering the results by the last name
14
SQL Practice (2)
Write SQL statements to :
1. Extract all fields from the student table where the id is
either 1 or 3
2. Extract all Khoury college students and all D’Amore
McKim students
3. Extract all college students whose IDs are < 15 OR >20
4. Extract college students from the student table whose IDs
are greater than 15 and less than 20
id name school credits_earned credits_req
1 Smith Khoury 32 120
15
MySQL work
Let’s use the MySQL workbench to write SELECT statements
using the ap database
16
SQL Practice (3)
1. Extract all information on students, first order the output by
credits_earned in ascending order and then order by
name in ascending order
2. Extract all information on students, first order the output by
credits_earned in descending order and then order by
name in ascending order.
17
Summary
In this module you learned:
• SQL SELECT clauses: SELECT FROM, WHERE,
ORDER BY, LIMIT.