❖ Queries |
A query is a declarative program that retrieves data from a database.
declarative = say what we want, not method to get it
Queries are used in two ways in RDBMSs:
psql
SQL is based on the relational algebra, which we discuss elsewhere
❖ SQL Query Language |
An SQL query consists of a sequence of clauses:
SELECT projectionList FROM relations/joins WHERE condition GROUP BY groupingAttributes HAVING groupCondition
FROM
WHERE
GROUP BY
HAVING
Result of query: a relation, typically displayed as a table.
Result could be just one tuple with one attribute (i.e. one value) or even empty
❖ SQL Query Language (cont) |
Functionality provided by SQL ...
Filtering: extract attributes from tuples, extract tuples frm tables
SELECT b,c FROM R(a,b,c,d) WHERE a > 5
Combining: merging related tuples from different tables
... FROM R(x,y,z) JOIN S(a,b,c) ON R.y = S.a
Summarising: aggregating values in a single column
SELECT avg(mark) FROM ...
Set operations: union, intersection, difference
❖ SQL Query Language (cont) |
More functionality provided by SQL ...
Grouping: forming subsets of tuples sharing some property
... GROUP BY R.a
(forms groups of tuples from R
a
Group Filtering: selecting only groups satisfying a condition
... GROUP BY R.a HAVING max(R.a) < 75
Renaming: assign a name to a component of a query
SELECT a as name FROM Employee(a,b,c) e WHERE e.b > 50000
❖ SQL Query Language (cont) |
Schema:
Example SQL query on this schema:
SELECT s.id, s.name, avg(e.mark) as avgMark
FROM Students s
JOIN Enrolments e on (s.id = e.student)
GROUP BY s.id, s.name
-- or --
SELECT s.id, s.name, avg(e.mark) as avgMark
FROM Students s, Enrolments e
WHERE s.id = e.student
GROUP BY s.id, s.name
❖ SQL Query Language (cont) |
How the example query is computed:
❖ Problem-solving in SQL |
Starts with an information request:
Pre-req: know your schema
Look for keywords in request to identify required data :
❖ Problem-solving in SQL (cont) |
Developing SQL queries ...
FROM
JOIN
WHERE
GROUP BY
SELECT
❖ Problem-solving in SQL (cont) |
Example: just the beers that John likes
Likes(drinker,beers)
WHERE
SELECT beer
select beer from Likes where drinker='John';
❖ Views |
A view associates a name with a query:
CREATE VIEW
(
)
AS
FROM
Views are useful for "packaging" a complex query to use in other queries.
cf. writing functions to package computations in programs
❖ Exercise: Queries on Beer Database (cont) |
Answer these queries on the Beer database:
Produced: 28 Sep 2020