tags:

views:

99

answers:

5

I want to represent the list "hi", "hello", "goodbye", "good day", "howdy" (with that order), in a SQL table:

pk | i | val
------------
1  | 0 | hi
0  | 2 | hello
2  | 3 | goodbye
3  | 4 | good day
5  | 6 | howdy

'pk' is the primary key column. Disregard its values.

'i' is the "index" that defines that order of the values in the 'val' column. It is only used to establish the order and the values are otherwise unimportant.

The problem I'm having is with inserting values into the list while maintaining the order. For example, if I want to insert "hey" and I want it to appear between "hello" and "goodbye", then I have to shift the 'i' values of "goodbye" and "good day" (but preferably not "howdy") to make room for the new entry.

So, is there a standard SQL pattern to do the shift operation, but only shift the elements that are necessary? (Note that a simple "UPDATE table SET i=i+1 WHERE i>=3" doesn't work, because it violates the uniqueness constraint on 'i', and also it updates the "howdy" row unnecessarily.)

Or, is there a better way to represent the ordered list? I suppose you could make 'i' a floating point value and choose values between, but then you have to have a separate rebalancing operation when no such value exists.

Or, is there some standard algorithm for generating string values between arbitrary other strings, if I were to make 'i' a varchar?

Or should I just represent it as a linked list? I was avoiding that because I'd like to also be able to do a SELECT .. ORDER BY to get all the elements in order.

A: 

Edit

If you have an Auxilliary Numbers table then quite a convoluted query to Update only as far as the first gap would be.

UPDATE [TESTING]
SET I= I + 1
WHERE I >3 AND 
(
NOT EXISTS 
    (SELECT * 
    FROM dbo.Numbers 
    WHERE Number > 3 AND NOT EXISTS 
                    (SELECT * FROM [TESTING] WHERE [TESTING].I = NUMBER))

OR  I < (SELECT MIN(Number) 
         FROM dbo.Numbers WHERE Number > 3 
         AND NOT EXISTS 
                 (SELECT * FROM [TESTING] WHERE [TESTING].I = NUMBER))
)
Martin Smith
He wants to maintain a certain order, not order by the `val` field
Michael Mrozek
+3  A: 

As i read your post, I kept thinking 'linked list' and at the end, I still think that's the way to go.

If you are using Oracle, and the linked list is a separate table (or even the same table with a self referencing id - which i would avoid) then you can use a CONNECT BY query and the pseudo-column LEVEL to determine sort order.

Randy
btw - this reminds me of the good old days when you needed to renumber your BASIC programs... that was usually done as a seperate command/effort whenever you ran out of numbers in between (you would count by 10's basically in the beginning just in case...)
Randy
As long as you can use your application to figure out the sort order, a simple NextNode column that is either NULL or points to the next entry will get you what you want. You won't be able to take advantage of ORDER BY but the data is there. INSERTS are as simple as modifying the NextNode column of the row that used to point to the one you want to be after your new entry.
colithium
A: 

So, is there a standard SQL pattern to do the shift operation, but only shift the elements that are necessary? (Note that a simple "UPDATE table SET i=i+1 WHERE i>=3" doesn't work, because it violates the uniqueness constraint on 'i', and also it updates the "howdy" row unnecessarily.)

There isn't a standard pattern that I'm aware of, much less a DB vendor that has something close.

IME, this was one of the few things that the application handled. Order would either be implied (starting top down), or explicitly left to the user to define a number for the ordering. Previously existing entries would be deleted -- UPDATE statements were never made for sake of the custom ordering -- the order was only ever set in INSERT statements.

You could copy the rows to a temp table, and manipulate there but the more I consider it - the less likely this would result in a generic solution.

OMG Ponies
A: 

If you don't use numbers, but Strings, you may have a table:

pk | i | val
------------
1  | a0 | hi
0  | a2 | hello
2  | a3 | goodbye
3  | b  | good day
5  | b1 | howdy

You may insert a4 between a3 and b, a21 between a2 and a3, a1 between a0 and a2 and so on. You would need a clever function, to generate an i for new value v between p and n, and the index can become longer and longer, or you need a big rebalancing from time to time.

Another approach could be, to implement a (double-)linked-list in the table, where you don't save indexes, but links to previous and next, which would mean, that you normally have to update 1-2 elements:

pk | prev | val
------------
1  |   0  | hi
0  |   1  | hello
2  |   0  | goodbye
3  |   2  | good day
5  |   3  | howdy

hey between heloo & goodbye:

hey get's pk 6,

pk | prev | val
------------
1  |   0  | hi
0  |   1  | hello 
6  |   0  | hi <- ins
2  |   6  | goodbye <- upd
3  |   2  | good day
5  |   3  | howdy

the preivous element would be hello with pk=0, and goodbye, which linked to hello by now has to link to hey in future.

But I don't know, if it is possible to find a 'order by' mechanism for many db-implementations.

user unknown
+3  A: 

You can easily achieve this by using a cascading trigger that updates any 'index' entry equal to the new one on the insert/update operation to the index value +1. This will cascade through all rows until the first gap stops the cascade - see the second example in this blog entry for a PostgreSQL implementation.

This approach should work independent of the RDBMS used, provided it offers support for triggers to fire before an update/insert. It basically does what you'd do if you implemented your desired behavior in code (increase all following index values until you encounter a gap), but in a simpler and more effective way.

Alternatively, if you can live with a restriction to SQL Server, check the hierarchyid type. While mainly geared at defining nested hierarchies, you can use it for flat ordering as well. It somewhat resembles your approach using floats, as it allows insertion between two positions by assigning fractional values, thus avoiding the need to update other entries.

Henrik Opel
I'm using SQLite, which apparently doesn't support cascading/recursive triggers (although it does support 'before' triggers).
Travis
@Travis: It seems like they added support for recursive triggers starting with version 3.6.18, but you have to explicitly turn it on: http://www.sqlite.org/pragma.html#pragma_recursive_triggers - I'm not sure though if the 'cascade' in your case counts as recursive, as it should never affect the inserted/updated row itself, but always a different row, so it might be worth a try anyway.
Henrik Opel
Thanks, didn't see that. However, there's a compiled-in upper limit on the recursion depth (1000 by default), and I don't know whether it can handle very high values, which could be a problem for me. What I finally decided to do was remove the uniqueness constraint on 'i' and for now just use the "i=i+1 WHERE i>=new_i" approach. I'll revisit this if updating the extra i values unnecessarily actually becomes a performance problem.
Travis