Showing the similarities between SQL and Prolog

SQL is a very common programming language, which sometimes is compared to the relatively more obscure Prolog language. Both are examples of declarative languages, where you define some facts, then you can ask questions about those facts, and the system answers the questions without you writing an explicit program.

However, I could not find a good example of their similarities. This text presents the most typical Prolog example, and translates it to SQL.

A typical Prolog example

"[x]" reads Prolog facts from file "x". We can use the special file "user" to read facts from the REPL, ending the facts with ctrl+d:

You should read "father(X,Y)" as "X is the father of Y". So Jim is the father of Julian, and so on.

We can ask Prolog questions:

Is Julian the father of Jim? There is no known fact about this, so no. But Julian *is* the father of Joe:

More interestingly, you can ask who are Julian's children:

(You press ; to get further answers.)

A simple translation to SQL

You can do pretty much the same with SQL, first define the facts as values in tables:

Then you can get the same answers:

The next step in Prolog

The typical example continues with some logic:

X is the grandfather of Y if X is the father of Z and Z is the father of Y. Then you can ask questions, and Prolog knows the answers:

Can we do the same in SQL?

You might not guess the answer on the first try, but the answer is not complex: you can do the same thing with SQL views:

And if you ask the same questions, SQLite gives the same answers: