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 version table using a field to track order:

id, owner_id, order, version
5, 1, 1, 1.1
6, 1, 4, 1.2
7, 1, 7, 1.2.1
8, 1, 10, 1.3

I want to ALTER TABLE version ADD COLUMN parent_id and have each record reference their parent and then drop the order column. The parent_id is the next lowest in order (which may not be sequential) resulting in:

id, owner_id, parent_id, version
5, 1, NULL, 1.1
6, 1, 5, 1.2
7, 1, 6, 1.2.1
8, 1, 7, 1.3

Can I write a query that will update the parent_id for me? Or must it be done programmatically?

share|improve this question
up vote 2 down vote accepted
    SELECT * 
    FROM version;

UPDATE version v1 
SET parent_id = (
    SELECT id 
    FROM v2 
    WHERE v2.order < v1.order 
    ORDER BY v2.order DESC LIMIT 1
share|improve this answer
(Putting this here for other's reference) (stupid enter key) To avoid the error about not being able to select from the table you're updating, create a temp table first, do to the select from, like this: CREATE TEMP TABLE v2 SELECT * FROM version – Utoxin Sep 6 '11 at 21:48

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.