<p>What's the best way to store a linked list in a MySQL database so that inserts are simple (i.e. you don't have to re-index a bunch of stuff every time) and such that the list can easily be pulled out in order?</p>

[{'answer_id': 65229, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': -1, 'selected': False, 'text': '<p>A list can be stored by having a column contain the offset (list index position) -- an insert in the middle is then incrementing all above the new parent and then doing an insert.</p>\n'}, {'answer_id': 65238, 'author': 'Adrian Dunston', 'author_id': 8344, 'author_profile': 'https://Stackoverflow.com/users/8344', 'pm_score': 5, 'selected': True, 'text': '<p>Store an integer column in your table called \'position\'.  Record a 0 for the first item in your list, a 1 for the second item, etc.  Index that column in your database, and when you want to pull your values out, sort by that column.</p>\n\n<pre><code> alter table linked_list add column position integer not null default 0;\n alter table linked_list add index position_index (position);\n select * from linked_list order by position;\n</code></pre>\n\n<p>To insert a value at index 3, modify the positions of rows 3 and above, and then insert:</p>\n\n<pre><code> update linked_list set position = position + 1 where position &gt;= 3;\n insert into linked_list (my_value, position) values ("new value", 3); \n</code></pre>\n'}, {'answer_id': 65276, 'author': 'cfeduke', 'author_id': 5645, 'author_profile': 'https://Stackoverflow.com/users/5645', 'pm_score': 4, 'selected': False, 'text': "<p>Using Adrian's solution, but instead of incrementing by 1, increment by 10 or even 100.  Then insertions can be calculated at half of the difference of what you're inserting between without having to update everything below the insertion.  Pick a number large enough to handle your average number of insertions - if its too small then you'll have to fall back to updating all rows with a higher position during an insertion.</p>\n"}, {'answer_id': 65283, 'author': 'user9252', 'author_id': 9252, 'author_profile': 'https://Stackoverflow.com/users/9252', 'pm_score': 2, 'selected': False, 'text': '<p>A linked list can be stored using recursive pointers in the table. This is very much the same hierarchies are stored in Sql and this is using the recursive association pattern.</p>\n\n<p>You can learn more about it <a href="https://web.archive.org/web/20180729174436/http://www.tomjewett.com/dbdesign/dbdesign.php?page=recursive.php" rel="nofollow noreferrer">here</a> (Wayback Machine link).</p>\n\n<p>I hope this helps.</p>\n'}, {'answer_id': 65295, 'author': 'B0fh', 'author_id': 9159, 'author_profile': 'https://Stackoverflow.com/users/9159', 'pm_score': 4, 'selected': False, 'text': '<p>create a table with two self referencing columns PreviousID and NextID. If the item is the first thing in the list PreviousID will be null, if it is the last, NextID will be null. The SQL will look something like this:</p>\n\n<pre><code>create table tblDummy\n{\n     PKColumn     int     not null, \n     PreviousID     int     null, \n     DataColumn1     varchar(50)     not null, \n     DataColumn2     varchar(50)     not null,  \n     DataColumn3     varchar(50)     not null, \n     DataColumn4     varchar(50)     not null, \n     DataColumn5     varchar(50)     not null, \n     DataColumn6     varchar(50)     not null, \n     DataColumn7     varchar(50)     not null, \n     NextID     int     null\n}\n</code></pre>\n'}, {'answer_id': 65330, 'author': 'Rory', 'author_id': 8479, 'author_profile': 'https://Stackoverflow.com/users/8479', 'pm_score': 2, 'selected': False, 'text': '<p>The simplest option would be creating a table with a row per list item, a column for the item position, and columns for other data in the item. Then you can use ORDER BY on the position column to retrieve in the desired order. </p>\n\n<pre><code>create table linked_list\n(   list_id   integer not null\n,   position  integer not null \n,   data      varchar(100) not null\n);\nalter table linked_list add primary key ( list_id, position );\n</code></pre>\n\n<p>To manipulate the list just update the position and then insert/delete records as needed. So to insert an item into list 1 at index 3:</p>\n\n<pre><code>begin transaction;\n\nupdate linked_list set position = position + 1 where position &gt;= 3 and list_id = 1;\n\ninsert into linked_list (list_id, position, data)\nvalues (1, 3, "some data");\n\ncommit;\n</code></pre>\n\n<p>Since operations on the list can require multiple commands (eg an insert will require an INSERT and an UPDATE), ensure you always perform the commands within a transaction.</p>\n\n<p>A variation of this simple option is to have position incrementing by some factor for each item, say 100, so that when you perform an INSERT you don\'t always need to renumber the position of the following elements. However, this requires a little more effort to work out when to increment the following elements, so you lose simplicity but gain performance if you will have many inserts.</p>\n\n<p>Depending on your requirements other options might appeal, such as:</p>\n\n<ul>\n<li><p>If you want to perform lots of manipulations on the list and not many retrievals you may prefer to have an ID column pointing to the next item in the list, instead of using a position column. Then you need to iterative logic in the retrieval of the list in order to get the items in order. This can be relatively easily implemented in a stored proc.</p></li>\n<li><p>If you have many lists, a quick way to serialise and deserialise your list to text/binary, and you only ever want to store and retrieve the entire list, then store the entire list as a single value in a single column. Probably not what you\'re asking for here though.</p></li>\n</ul>\n'}, {'answer_id': 65428, 'author': 'Mike Monette', 'author_id': 6166, 'author_profile': 'https://Stackoverflow.com/users/6166', 'pm_score': 2, 'selected': False, 'text': '<p>There are a few approaches I can think of right off, each with differing levels of complexity and flexibility.  I\'m assuming your goal is to preserve an order in retrieval, rather than requiring storage as an actual linked list.</p>\n\n<p>The simplest method would be to assign an ordinal value to each record in the table (e.g. 1, 2, 3, ...).  Then, when you retrieve the records, specify an order-by on the ordinal column to get them back in order. </p>\n\n<p>This approach also allows you to retrieve the records without regard to membership in a list, but allows for membership in only one list, and may require an additional "list id" column to indicate to which list the record belongs.</p>\n\n<p>An slightly more elaborate, but also more flexible approach would be to store information about membership in a list or lists in a separate table.  The table would need 3 columns:  The list id, the ordinal value, and a foreign key pointer to the data record.  Under this approach, the underlying data knows nothing about its membership in lists, and can easily be included in multiple lists.</p>\n'}, {'answer_id': 7025913, 'author': 'Poncho', 'author_id': 889912, 'author_profile': 'https://Stackoverflow.com/users/889912', 'pm_score': 0, 'selected': False, 'text': '<p>I think its much simpler adding a created column of <code>Datetime</code> type and a position column of <code>int</code>, so now you can have duplicate positions, at the select statement use the <code>order by</code> position, created desc option and your list will be fetched in order.</p>\n'}, {'answer_id': 21038546, 'author': 'FlyTigert', 'author_id': 657921, 'author_profile': 'https://Stackoverflow.com/users/657921', 'pm_score': 2, 'selected': False, 'text': '<p>This post is old but still going to give my .02$.  Updating every record in a table or record set sounds crazy to solve ordering. the amount of indexing also crazy, but it sounds like most have accepted it.  </p>\n\n<p>Crazy solution i came up with to reduce updates and indexing is to create two tables (and in most use cases you don\'s sort all records in just one table anyway).  Table A to hold the records of the list being sorted and table B to group and hold a record of the order as a string.  the order string represents an array that can be used to order the selected records either on the web server or browser layer of a webpage application.  </p>\n\n<pre><code>Create Table A{\nId int primary key identity(1,1),\nData varchar(10) not null\nB_Id int\n}\n\nCreate Table B{\nId int primary key Identity(1,1),\nGroupName varchat(10) not null,\nOrder varchar(max) null\n}\n</code></pre>\n\n<p>The format of the order sting should be id, position and some separator to split() your string by.  in the case of jQuery UI the .sortable(\'serialize\') function outputs an order string for you that is POST friendly that includes the id and position of each record in the list. </p>\n\n<p>The real magic is the way you choose to reorder the selected list using the saved ordering string.  this will depend on the application you are building.  here is an example again from jQuery to reorder the list of items: <a href="http://ovisdevelopment.com/oramincite/?p=155" rel="nofollow">http://ovisdevelopment.com/oramincite/?p=155</a> </p>\n'}, {'answer_id': 25908592, 'author': 'Vadzim', 'author_id': 603516, 'author_profile': 'https://Stackoverflow.com/users/603516', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://dba.stackexchange.com/questions/46238/linked-list-in-sql-and-trees">https://dba.stackexchange.com/questions/46238/linked-list-in-sql-and-trees</a> suggests a trick of using floating-point position column for fast inserts and ordering.</p>\n\n<p>It also mentions specialized SQL Server 2014 <a href="http://technet.microsoft.com/en-us/library/bb677173.aspx" rel="nofollow noreferrer">hierarchyid</a> feature.</p>\n'}, {'answer_id': 29475498, 'author': 'HumbleWebDev', 'author_id': 3496058, 'author_profile': 'https://Stackoverflow.com/users/3496058', 'pm_score': 2, 'selected': False, 'text': '<p>This is something I\'ve been trying to figure out for a while myself. The best way I\'ve found so far is to create a single table for the linked list using the following format (this is pseudo code):</p>\n\n<p>LinkedList(</p>\n\n<ul>\n<li>key1, </li>\n<li>information, </li>\n<li>key2</li>\n</ul>\n\n<p>)</p>\n\n<p>key1 is the starting point. Key2 is a foreign key linking to itself in the next column. So your columns will link something link something like this</p>\n\n<p><strong>col1</strong>                    </p>\n\n<ul>\n<li>key1 = 0,</li>\n<li>information= \'hello\'</li>\n<li>key2 = 1</li>\n</ul>\n\n<p><em>Key1 is primary key of col1. key2 is a foreign key leading to the key1 of col2</em></p>\n\n<p><strong>col2</strong></p>\n\n<ul>\n<li>key1 = 1,</li>\n<li>information= \'wassup\'</li>\n<li>key2 = null</li>\n</ul>\n\n<p><em>key2 from col2 is set to null because it doesn\'t point to anything</em></p>\n\n<p>When you first enter a column in for the table, you\'ll need to make sure key2 is set to null or you\'ll get an error. After you enter the second column, you can go back and set key2 of the first column to the primary key of the second column.</p>\n\n<p>This makes the best method to enter many entries at a time, then go back and set the foreign keys accordingly (or build a GUI that just does that for you)</p>\n\n<p>Here\'s some actual code I\'ve prepared (all actual code worked on MSSQL. You may want to do some research for the version of SQL you are using!):</p>\n\n<p><em>createtable.sql</em></p>\n\n<pre><code>create table linkedlist00 (\n\nkey1 int primary key not null identity(1,1),\n\ninfo varchar(10),\n\nkey2 int\n\n)\n</code></pre>\n\n<p><em>register_foreign_key.sql</em></p>\n\n<pre><code>alter table dbo.linkedlist00\n\nadd foreign key (key2) references dbo.linkedlist00(key1)\n</code></pre>\n\n<p>*I put them into two seperate files, because it has to be done in two steps. MSSQL won\'t let you do it in one step, because the table doesn\'t exist yet for the foreign key to reference.</p>\n\n<p>Linked List is especially powerful in <em>one-to-many</em> relationships. So if you\'ve ever wanted to make an array of foreign keys? Well this is one way to do it! You can make a primary table that points to the first column in the linked-list table, and then instead of the "information" field, you can use a foreign key to the desired information table.</p>\n\n<p>Example:</p>\n\n<p>Let\'s say you have a Bureaucracy that keeps forms.</p>\n\n<p>Let\'s say they have a table called <em>file cabinet</em> </p>\n\n<p>FileCabinet(</p>\n\n<ul>\n<li>Cabinet ID (pk)</li>\n<li>Files ID (fk)\n)</li>\n</ul>\n\n<p><em>each column contains a primary key for the cabinet and a foreign key for the files. These files could be tax forms, health insurance papers, field trip permissions slips etc</em></p>\n\n<p>Files(</p>\n\n<ul>\n<li><p>Files ID (pk)</p></li>\n<li><p>File ID (fk)</p></li>\n<li><p>Next File ID (fk)</p></li>\n</ul>\n\n<p>)</p>\n\n<p><em>this serves as a container for the Files</em></p>\n\n<p>File(</p>\n\n<ul>\n<li><p>File ID (pk)</p></li>\n<li><p>Information on the file</p></li>\n</ul>\n\n<p>)</p>\n\n<p><em>this is the specific file</em></p>\n\n<p>There may be better ways to do this and there are, depending on your specific needs. The example just illustrates possible usage.</p>\n'}, {'answer_id': 34668848, 'author': 'Stephen', 'author_id': 593238, 'author_profile': 'https://Stackoverflow.com/users/593238', 'pm_score': 0, 'selected': False, 'text': "<p>Increment the SERIAL 'index' by 100, but manually add intermediate values with an 'index' equal to Prev+Next / 2.  If you ever saturate the 100 rows, reorder the index back to 100s.</p>\n\n<p>This should maintain sequence with primary index.</p>\n"}, {'answer_id': 63198185, 'author': 'Cal', 'author_id': 5785894, 'author_profile': 'https://Stackoverflow.com/users/5785894', 'pm_score': -1, 'selected': False, 'text': '<p>You could implement it like a double ended queue (deque) to support fast push/pop/delete(if oridnal is known) and retrieval you would have two data structures. One with the actual data and another with the number of elements added over the history of the key. Tradeoff: This method would be slower for any insert into the middle of the linked list O(n).</p>\n<pre><code>create table queue (\n    primary_key,\n    queue_key\n    ordinal,\n    data\n)\n</code></pre>\n<p>You would have an index on queue_key+ordinal</p>\n<p>You would also have another table which stores the number of rows EVER added to the queue...</p>\n<pre><code>create table queue_addcount (\n    primary_key,\n    add_count\n)\n</code></pre>\n<p>When pushing a new item to either end of the queue (left or right) you would always increment the add_count.</p>\n<p>If you push to the back you could set the ordinal...</p>\n<pre><code>ordinal = add_count + 1\n</code></pre>\n<p>If you push to the front you could set the ordinal...</p>\n<pre><code>ordinal = -(add_count + 1)\n</code></pre>\n<p>update</p>\n<pre><code>add_count = add_count + 1\n</code></pre>\n<p>This way you can delete anywhere in the queue/list and it would still return in order and you could also continue to push new items maintaining the order.</p>\n<p>You could optionally rewrite the ordinal to avoid overflow if a lot of deletes have occurred.</p>\n<p>You could also have an index on the ordinal to support fast ordered retrieval of the list.</p>\n<p>If you want to support inserts into the middle you would need to find the ordinal which it needs to be insert at then insert with that ordinal. Then increment every ordinal by one following that insertion point. Also, increment the add_count as usual. If the ordinal is negative you could decrement all of the earlier ordinals to do fewer updates. This would be O(n)</p>\n'}]
['https://Stackoverflow.com/questions/65205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']