Wk4 - SQL Basics and Simple Queries
Wk4 - SQL Basics and Simple Queries
2
Week 4 Database Management II
Access Control
Statement Description
GRANT Grants users access privileges
REVOKE Removes users access privileges
3
Week 4 Database Management II
Data Definition Language
Statement Description
CREATE TABLE Adds a new table to the database
DROP TABLE Removes a table from the database
ALTER TABLE Changes the structure of the existing table
CREATE VIEW Adds a new view to the database
DROP VIEW Removes a view from the database
CREATE INDEX Builds an index for a column
DROP INDEX Removes the index for a column
CREATE SCHEMA Adds a new schema to the database
DROP SCHEMA Removes a schema from the database
CREATE DOMAIN Adds a new data value domain
ALTER DOMAIN Changes a domain definition
DROP DOMAIN Removes a domain from the database
4
Week 4 Database Management II
Data Manipulation Language
Statement Description
INSERT Adds new rows of data or tuples to the database
DELETE Removes rows of data or tuples from the
database
UPDATE Modifies existing database data
5
Week 4 Database Management II
Data Querying/Retrieval
Statement Description
SELECT Retrieves data from the database
6
Week 4 Database Management II
Anatomy of a SQL statement
10
Week 4 Database Management II
Column Names
11
Week 4 Database Management II
Data Types
Integers: INT (len), INTEGER (len)
Decimal numbers: NUMERIC (precision, scale), DECIMAL (precision,
scale), DEC (precision, scale)
Floating Point numbers: FLOAT (precision)
Fixed-length character strings: CHAR (len), CHARACTER (len)
Variable-length character strings: VARCHAR (len), CHAR VARYING (len)
Money amounts: MONEY, CURRENCY
Dates and times: DATE, TIME (precision), TIMESTAMP (precision)
Boolean data
Long text
Unstructured byte streams
12
Week 4 Database Management II
Constants (String, Date and Time, and Symbolic)
Character data are enclosed in single quotes (‘….’) as specified by
the ANSI/ISO standard, e.g. ‘Minna’ ‘Micheal, Mary J.’ etc.
Constant data values for dates, times, and time intervals are also
specified as string constants in SQL products that support date/time
data. However, the format of these constants varies from one DBMS
to the next.
The SQL language also includes special symbolic constants that
return data values maintained in the DBMS. For example, the
symbolic constant CURRENT_DATE returns the value of the
current date and can be used in queries.
Constant date values are also used in expressions.
14
Week 4 Database Management II
Expressions
16
Week 4 Database Management II
Simple Queries
Simple queries are queries that retrieve data from a single table
in the database.
The SELECT statement is used to express SQL queries which could
be simple or complex.
18
Week 4 Database Management II
The SELECT Statement
19
Week 4 Database Management II
The full form SELECT Statement
20
Week 4 Database Management II
DRIVER
NAME DOB
22
Week 4 Database Management II
CAR
23
Week 4 Database Management II
select-item
24
Week 4 Database Management II
Simple SELECT cont.
REGNO
F611 AAA
J111 BBB
A155 BDE
K555 GHT
SC04 BFE
26
Week 4 Database Management II
Simple SELECT cont.
27
Week 4 Database Management II
Duplicate Rows (DISTINCT)
28
Week 4 Database Management II
Duplicate Rows
Find all the colours used in cars.
29
Week 4 Database Management II
DISTINCT Example
COLOUR
RED
BLUE
GREEN
30
Week 4 Database Management II
Formatting
SPACES do not matter
NEWLINES do not matter
Good practice to put ; at the end of the query.
CASE (except between single quotes) does not matter.
These are all valid:
31
Week 4 Database Management II
Comments
To give you the ability to make notes in queries you are allowed to
have comments.
Comments are not executed
A comment starts with -- and ends with a newline
They are only permitted within a query.
32
Week 4 Database Management II
Row Selection (WHERE Clauses)
33
Week 4 Database Management II
Simple Rule
35
Week 4 Database Management II
Note
Things between quotes is CASE SENSITIVE.
‘RED’ is not the same as ‘Red’ or ‘red’
REGNO COLOUR
SELECT regno from CAR
F611 AAA RED
WHERE colour = 'RED'
36
Week 4 Database Management II
Search Conditions
37
Week 4 Database Management II
The Comparison Test (=, <>, <, <=, >, >=)
39
Week 4 Database Management II
DATE Comparison
Date comparisons can be tricky
You can use all the normal comparators with dates.
40
Week 4 Database Management II
DATE Comparison cont.
The tricky part with dates is remembering that dates get bigger as
you move into the future.
DATE1>DATE2 indicates DATE1 is in the future after DATE2.
NAME DOB
Bob Smith 23 Mar 1981
Bob Jones 3 Dec 1986
41
Week 4 Database Management II
DATE Syntax
It must be in quotes
Each DBMS handles dates in a slightly different way
Dates like ‘1 Jan 2003’ does not work quite well with some
implementations.
Oracle permits dates like ‘1-Jan-2003’ and ‘1-Jan-03’
MySQL permits dates like '1980-01-11’
You must always specify a day and a month. If you do not the
DBMS will report an error.
42
Week 4 Database Management II
The Range Test (BETWEEN)
43
Week 4 Database Management II
The Range Test Example
Find all drivers born between 1995 and 1999
SELECT name,dob from driver
WHERE DOB between ‘1 Jan 1985’ and ’31 Dec 1999’
44
Week 4 Database Management II
The Set Membership Test (IN)
45
Week 4 Database Management II
IN - Example
When you have a list of OR, all on the same attribute, then IN
could be a simpler way:
Rather Than:
SELECT regno,make FROM car
WHERE make = ‘SKODA’ or make = ‘SMART’
Have
SELECT regno,make FROM car
WHERE make in (‘SKODA’,’SMART’);
46
Week 4 Database Management II
The Pattern Matching Test (LIKE)
Checks to see whether the data value in a column matches a
specified pattern.
The pattern is a string that could include one or more wildcard
characters including the percent sign (%), the underscore (_).
The percent sign (%) wildcard matches any sequence of zero or
more characters while the underscore (_) wildcard matches a single
character.
Strings that do not match a pattern can also be located using the
(NOT LIKE) form of the pattern matching test. The syntax is as
follows:
column-name [NOT] LIKE pattern
47
Week 4 Database Management II
Pattern Matching Test Examples
Name LIKE ‘Jim Smith’ e.g. Jim Smith
Name LIKE ‘_im Smith’ e.g. Tim Smith
Name LIKE ‘___ Smith’ e.g. Bob Smith
Name LIKE ‘% Smith’ e.g. Frank Smith
Name LIKE ‘% S%’ e.g. Brian Smart
Name LIKE ‘Bob %’ e.g. Bob Martin
Name LIKE ‘%’ i.e. match anyone
48
Week 4 Database Management II
The NULL Value Test (IS NULL)
NULL indicates that something has no value
It is not a value, and you cannot use normal comparison operators.
Wrong: SELECT regno from car where owner = NULL
Wrong: SELECT regno from car where owner = ‘NULL’
49
Week 4 Database Management II
Null Test Example
REGNO
SELECT regno from car F611 AAA
J111 BBB
WHERE OWNER is not null
A155 BDE
K555 GHT
SC04 BFE
50
Week 4 Database Management II
Query Results
The result of a SQL query is always a table of data, just like the
tables in the database.
The number of columns in the query result corresponds to the
number of items in the SELECT clause, while the number of rows
depends on the number of rows that meet the search criteria
(WHERE clause).
Query results can be a single value in some cases. These results
are still a table consisting of one column and one row.
It is also possible for a query to produce zero rows of query
results. The query result is still a table although an empty table.
51
Week 4 Database Management II
Query Results (NULL)
52
Week 4 Database Management II
Logical Operators
53
Week 4 Database Management II
AND, OR and NOT Operators
54
Week 4 Database Management II
Multiple AND rules - Example
SELECT regno
FROM car
WHERE colour = ‘BLUE’
AND regno like ‘%5%’
AND owner like ‘Bob %’
;
55
Week 4 Database Management II
OR - Example
OR is like ‘either’. So long as one of the rules is true then the filter is
true.
Looks for cars which are EITHER red or blue…
REGNO COLOUR
F611 AAA RED
J111 BBB BLUE
A155 BDE BLUE
SC04 BFE BLUE
56
Week 4 Database Management II
NOT
57
Week 4 Database Management II
Precedence
Precedence is the order in which the rules are evaluated and
combined together.
It is NOT in the order they are written.
Rules are combined together firstly at AND, then OR, and finally at
NOT.
Consider : Find a car that has a 5 in reg and is either red or blue.
59
Week 4 Database Management II
Sorting Query Results (ORDER BY Clause)
60
Week 4 Database Management II
ASCending order
Sort by alphabetical or numeric order: ASC
ORDER BY … ASC is the default.
MAKE
SMART
SKODA
MERCEDES
FIAT
FORD
63
Week 4 Database Management II
Multi Column Sort
ORDER BY can take multiple columns.
MAKE COLOUR
SKODA BLUE
SMART BLUE
MERCEDES BLUE
FIAT GREEN
FORD RED
64
Week 4 Database Management II
Rules for Single-Table Query Processing
65
Week 4 Database Management II
Rules for Single-Table Query Processing
Start with the table named in the FROM clause
If there is a WHERE clause, apply its search condition to each row of the
table, retaining only those rows for which the search condition is TRUE,
and discarding those rows for which the search condition is FALSE or
NULL.
For each remaining row, calculate the value of each item in the select list
to produce a single row of query results. For each column reference, use
the value of the column in the current row.
If SELECT DISTINCT is specified, eliminate any duplicate rows of the
query results that were produced.
If there is an ORDER BY clause, sort the query as specified.
The rows generated by these steps comprise the query results.
66
Week 4 Database Management II
SELECT - Order of Evaluation
SELECT [DISTINCT] column_name 5,6 eliminate unwanted data
FROM label_list 1 Cartesian Product
[WHERE condition ] 2 eliminate unwanted rows
[GROUP BY column_list 3 group rows
[HAVING condition ]] 4 eliminate unwanted groups
[ORDER BY column_list[DESC]] 7 sort rows
67
Week 4 Database Management II