Datalog Query Language: Xi XJ
Datalog Query Language: Xi XJ
Datalog Query Language: Xi XJ
Datalog is a logical query language (Data Logic). See textbook (Ullman ch. 5.3, 5.4 and 10.2)
RS
Answer(x1, …, xn) R(x1, ..., xn) AND S(x1, ..., xn)
R–S
Answer(x1, …, xn) R(x1, ..., xn) AND NOT S(x1, ..., xn)
RS
Answer(x1, …, xn) R(x1, ..., xn)
Answer(x1, …, xn) S(x1, ..., xn)
Xi=Xj(R)
Answer(x1, …, xn) R(x1, ..., xn) AND Xi = Xj
X1,X2(R)
Answer(x1, x2) R(x1, x2, ..., xn)
RS
Answer(x1, …, xn, y1, …, ym) R(x1, x2, ..., xn) AND S(y1, ..., ym)
R⨝S
Answer(x1, …, xn, y1, …, ym, z1, …, zk) R(x1, ..., xn, z1, … zk) AND S(y1, ..., ym, z1, … zk)
List those names who doesn't like pear but like something else.
Answer(X) Likes(X, Y) AND NOT Likes(X, 'pear')
WITH
Min3(N) AS (
SELECT DISTINCT L1.name FROM Likes L1, Likes L2, Likes L3
WHERE L1.name=L2.name AND L2.name=L3.name
AND L1.fruits <> L2.fruits AND L2.fruits <> L3.fruits
AND L1.fruits <> L3.fruits)
SELECT name FROM Likes MINUS SELECT N FROM Min3;
WITH
Min2(N) AS (
SELECT DISTINCT L1.name FROM Likes L1, Likes L2
WHERE L1.name=L2.name AND L1.fruits <> L2.fruits),
Min3(N) AS (
SELECT DISTINCT L1.name FROM Likes L1, Likes L2, Likes L3
WHERE L1.name=L2.name AND L2.name=L3.name
AND L1.fruits <> L2.fruits AND L2.fruits <> L3.fruits
AND L1.fruits <> L3.fruits)
SELECT N FROM Min2 MINUS SELECT N FROM Min3;
WITH
NotLikes(N,F) AS (
SELECT L1.name, L2.fruits FROM Likes L1, Likes L2
MINUS
SELECT name, fruits FROM Likes)
SELECT name FROM Likes MINUS SELECT N FROM NotLikes;
Recursive Datalog
WITH
Sib(a,b) AS
(SELECT p1.c, p2.c FROM Par p1, Par p2
WHERE p1.p = p2.p AND p1.c <> p2.c),
Cousin(x,y) AS
(SELECT * FROM Sib
UNION ALL
SELECT p1.c, p2.c FROM Par p1, Par p2, Cousin
WHERE p1.p = Cousin.x AND p2.p = Cousin.y)
CYCLE x,y SET cycle_yes TO 'T' DEFAULT 'N'
SELECT DISTINCT * FROM Cousin WHERE x <= y ORDER BY 1,2;
The tuples are not the same as in TextBook. I inserted an extra tuple in order to be a cycle in the
graph of Flight table. --> orig = 'Chicago' and dest = 'Denver';
Most DBMS-s allow only linear recursion in recursive queries, which means:
no rule has more than one subgoal that is mutually recursive with the head.
(See mutual recursion in textbook, ch. 10.2)
In the previous datalog program the second rule violates this requirement.
SQL query
---------
WITH reaches(orig, dest) AS
(
SELECT orig, dest FROM flight
UNION ALL
SELECT flight.orig, reaches.dest FROM flight, reaches
WHERE flight.dest = reaches.orig AND flight.orig <> reaches.dest
)
CYCLE orig SET cycle_yes TO 'Y' DEFAULT 'N'
SELECT distinct orig, dest, cycle_yes FROM reaches order by 1;