Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a database of small documents which users can view and annotate. Their annotations are not public. I'm looking to optimise a single query to read the document and annotations for the current user.

Originally I tried this:

SELECT content,select_start,select_end,select_colour
FROM documents
LEFT OUTER JOIN annotations
USING (document_id)
WHERE document_id=<some_document_id_here> AND (user_id=<some_user_id_here> or user_id IS NULL)

But it failed to return a document if another user had added annotations. So I'm now using this:

SELECT content,select_start,select_end,select_colour
FROM documents A
    SELECT document_id,select_start,select_end,select_colour
    FROM annotations
    WHERE user_id=<some_user_id_here>
) B
ON A.document_id = B.document_id
WHERE A.document_id=<some_document_id_here>

which works, but the inner select statement could create quite a sizeable temporary table. I'd like to know if there's a better way to achieve this.

share|improve this question
up vote 1 down vote accepted

The best I've been able to come up with is to limit the size of the temporary table as much as possible by changing the inner WHERE to:

WHERE user_id=<some_user_id_here> AND document_id=<some_document_id_here>

It means the document ID has to be repeated in the statement, but at least means that the inner table is small, and pretty much guaranteed to be in-memory.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.