9.2 Queries


We saw earlier that the way to interact with the Prolog system is to write queries and get a response. On this page, we look at queries in a little more detail.

Example program

Again, consider the by now familiar example program:

student(Lisa, 5).
student(Martin, 3).
student(John, 3).
student(Edward, 7).

An example query

If we ask the following question of the Prolog+CG system:

?- student(Lisa,5).

we get the following response:


This requires some explanation.



sequence of symbols means "here starts a query." Prolog+CG prints it for you automatically in the query-area, and you don't need to write it. However, in these notes we will always write it in front of queries to show that we are dealing with a query.


sequence of symbols means "yes". The question we asked:

?- student(Lisa, 5).

could be paraphrased as "Does there exist a student named Lisa who is in the fifth semester?", and since there was a fact in the database to match this query, the answer was "yes" or "{}".

A Query is terminated with a period

It will be noticed that the query, like a fact, is terminated with a period. You must always terminate your queries (as well as your facts) with a period.

When a query fails

If we asked the following question:

?- student(Abraham, 3).

the response would be:


The reason is that there is no fact in the program database saying that there is a student named Abraham in the third semester. We say that the query fails.


Queries start with

, but you don't need to write this -- Prolog+CG writes it for you on the screen. If the answer to a question is "yes", the response will be
. If the answer to a question is "no", the response will be
. Queries must be terminated with a period.


Next, we look at goals and subgoals in queries. This is essential terminology when talking about Prolog queries and programs.

PrevLite: 9.1 Facts and the program database
NextLite: 9.3 Goals and subgoals

Prev: 9.1 Facts and the program database
Up: 9 A simple Prolog program
Next: 9.3 Goals and subgoals