❖ Query Translation (cont) |
Translation step: SQL text → RA expression
Example:
SQL: select name from Students where id=7654321;
-- is translated to
RA: Proj[name](Sel[id=7654321]Students)
Processes: lexer/parser, mapping rules, rewriting rules.
Mapping from SQL to RA may include some optimisations, e.g.
select * from Students where id = 54321 and age > 50; -- is translated to Sel[age>50](Sel[id=54321]Students) -- rather than ... because of index on id Sel[id=54321&age>50](Students)
❖ Parsing SQL |
Parsing task is similar to that for programming languages.
Language elements:
create
select
from
where
Students
name
id
CourseCode
+
-
=
<
>
AND
OR
NOT
IN
'abc'
123
3.1
'01-jan-1970'
PostgreSQL parser ...
src/backend/parser
src/backend/catalog
❖ Expression Rewriting Rules |
Since RA is a well-defined formal system
❖ Relational Algebra Laws |
Commutative and Associative Laws:
❖ Relational Algebra Laws (cont) |
Selection pushing ( σc(R ∪ S) and σc(R ∪ S) ):
❖ Relational Algebra Laws (cont) |
Rewrite rules for projection ...
All but last projection can be ignored:
Projections can be pushed into joins:
❖ Query Rewriting |
Subqueries ⇒ convert to a join
Example:
select c.code, count(*) from Courses c where c.id in (select cid from Enrolments) group by c.code
becomes
select c.code, count(*) from Courses c join Enrolments e on c.id = e.cid group by c.code
❖ Query Rewriting (cont) |
But not all subqueries can be converted to join, e.g.
select e.sid as student_id, e.cid as course_id from Enrolments e where e.sid = (select max(id) from Students)
has to be evaluated as
Val = max[id]Students
Res = π(sid,cid)(σsid=ValEnrolments)
❖ Query Rewriting (cont) |
In PostgreSQL, views are implemented via rewrite rules
create view COMP9315studes as
select stu,mark from Enrolments where course='COMP9315';
-- students who passed
select stu from COMP9315studes where mark >= 50;
is represented in RA by
COMP9315studes = Proj[stu,mark](Sel[course=COMP9315](Enrolments)) -- with query ... Proj[stu](Sel[mark>=50](COMP9315studes)) -- becomes ... Proj[stu](Sel[mark>=50]( Proj[stu,mark](Sel[course=COMP9315](Enrolments)))) -- which could be rewritten as ... Proj[stu](Sel[mark>=50 & course=COMP9315]Enrolments)
Produced: 5 Apr 2021