<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Noctilucent]]></title><description><![CDATA[Welcome to Noctilucent 🌙
A place for curious minds, wandering thoughts, and the occasional rabbit hole.
Here, I write about software development, programming, ]]></description><link>https://noctilucent.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b059220d321e1ecd0ac3a5d/79a57fb5-42c1-4c72-9513-9b714ae3a847.png</url><title>Noctilucent</title><link>https://noctilucent.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 00:59:51 GMT</lastBuildDate><atom:link href="https://noctilucent.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Everything Migrated, Except the Sequence]]></title><description><![CDATA[Migrated database records but forgot PostgreSQL sequences? Learn how to fix primary key conflicts using the setval() function.]]></description><link>https://noctilucent.hashnode.dev/everything-migrated-except-the-sequence</link><guid isPermaLink="true">https://noctilucent.hashnode.dev/everything-migrated-except-the-sequence</guid><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Django]]></category><category><![CDATA[database]]></category><category><![CDATA[Python]]></category><category><![CDATA[migration]]></category><dc:creator><![CDATA[Night Purr]]></dc:creator><pubDate>Wed, 25 Nov 2026 14:01:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b059220d321e1ecd0ac3a5d/0f739a51-d60c-4288-ad18-073411d0f402.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>Have you ever been tasked with migrating an existing database to a new one, where the schemas are slightly different, without losing a single piece of data?</p>
<p>If the schemas were identical, the process would probably be straightforward. You could migrate the data, verify that everything was transferred successfully, and call it a day. But what if the schemas differed, even just a little? Would everything still go smoothly? Or could those seemingly minor differences lead to unexpected errors and bugs?</p>
<p>In this article, I'll share my experience dealing with exactly this kind of situation. The project involved Django and PostgreSQL, and this wasn't just some experiment in a development environment. It happened while the application was already running in production, with real users and real data.</p>
<h1>The Story Behind the Migration</h1>
<p>Alright, I won't beat around the bush or waste any of your valuable time. It all started when I became involved in an existing application that had been developed within our team. At that point, the application already had an established database structure, which I hadn't been involved in designing. As I started examining it more closely, I noticed several aspects of the database that could be improved, including column data types, table structures, relationships, and so on.</p>
<p>Initially, I thought I could address these issues one at a time. I tried making adjustments to the backend and frontend code, as well as modifying parts of the database itself, such as changing certain column data types and tweaking some table structures. However, things didn't turn out quite as I expected. Every time I fixed one issue, another would surface. Then I'd fix that one, only to encounter yet another problem. It felt like an endless cycle! 😭</p>
<p>At some point, I realized that continuously addressing these issues individually wasn't going to be a sustainable solution. Some of these issues seemed to be interconnected, and addressing one area often required making additional adjustments elsewhere. Rather than continuing down that path, I decided it would be better to take a step back and rebuild the database with a more consistent structure.</p>
<p>Of course, that didn't mean throwing everything away and starting completely from scratch. I kept the parts of the original database that were still relevant and working as intended, changing only what needed to be changed. And, most importantly, I had to make sure that all the existing data would be migrated to the new database without losing anything.</p>
<h2>A Quick Look at the Application</h2>
<p>Before we go any further, let me give you a little context about the application.</p>
<p>It's a grocery store management application designed to make everyday store operations easier. Instead of manually calculating purchases, keeping track of product stock, or recording daily sales, the application takes care of these tasks for the store owner.</p>
<p>The process is pretty simple: the cashier selects the products a customer wants to purchase (or scans their barcodes), clicks a few buttons, and—ta-da!—a receipt is printed, inventory is updated, and the transaction is recorded.</p>
<p>In short, it's a straightforward application that helps grocery stores manage their daily operations without all the hassle of doing things manually.</p>
<h2>The Table We'll Be Focusing On</h2>
<p>Now, although the original database had several aspects that needed improvement, I'm not going to discuss every single one of them in this article. Instead, I'll narrow things down to just one table: <code>products</code>.</p>
<p>Why this table? Because it's where the interesting part of this story begins, and it's directly related to the problem that inspired me to write this article.</p>
<p>For the sake of simplicity, I won't go into the nitty-gritty details of its structure. Just think of it as a table that stores information about all the products available for sale in a shop.</p>
<h1>The Migration: Everything Seemed Fine</h1>
<p>Alright, we've finally reached the migration part!</p>
<p>As I mentioned earlier, the old and new databases had slightly different schemas. Because of that, simply dumping the old database and restoring it into the new one wasn't suitable for this particular migration. I needed to adapt the existing data to match the new schema, which meant transferring the data manually.</p>
<p>And yes, that included the IDs, or primary keys!</p>
<p>At the time, I didn't think much of it. I simply made sure that the existing records were transferred correctly, including their respective IDs. After all, the data was there, the relationships were preserved, and everything seemed to be working as expected.</p>
<p>Or so I thought.</p>
<p>After the migration was completed, the application was handed over to the client. Initially, everything seemed fine. The existing products were there, the application could retrieve them, and the client could continue using it as usual.</p>
<p>However, things started getting a little weird when the client tried to add new products.</p>
<p>They reported that sometimes they had to click the <code>Save</code> button multiple times before a new product was successfully added. Naturally, that was unexpected. Why would something as simple as adding a new product require multiple attempts?</p>
<p>At first, I didn't immediately realize what was going on. The existing data had been migrated successfully, and there didn't seem to be any missing records. So, what exactly was causing the problem?</p>
<p>Well, as it turned out, the problem wasn't with the existing records themselves. It had something to do with the way PostgreSQL generated new primary key values.</p>
<p>And that's where things get interesting.</p>
<h1>The Culprit: An Out-of-Sync Sequence</h1>
<p>To understand why this happened, we first need to talk about something called a sequence in PostgreSQL.</p>
<p>A sequence is a database object responsible for generating sequential numeric values. It's commonly used to generate values for auto-incrementing primary keys. In PostgreSQL, when you define a column using <code>SERIAL</code> or an identity column, PostgreSQL automatically creates and uses a sequence behind the scenes to generate its values.</p>
<p>Now, here's where things get interesting.</p>
<p>A sequence maintains its own state independently of the table it's associated with. In other words, it doesn't automatically inspect the table to figure out which IDs are already occupied. It simply generates values based on its current state.</p>
<p>Let me give you a simple example.</p>
<p>Suppose we have a products table in the old database containing five records:</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>Product</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Apple</td>
</tr>
<tr>
<td>2</td>
<td>Banana</td>
</tr>
<tr>
<td>3</td>
<td>Orange</td>
</tr>
<tr>
<td>4</td>
<td>Mango</td>
</tr>
<tr>
<td>5</td>
<td>Grape</td>
</tr>
</tbody></table>
<p>Now, let's say the client deletes the product with ID 3. The table would look like this:</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>Product</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Apple</td>
</tr>
<tr>
<td>2</td>
<td>Banana</td>
</tr>
<tr>
<td>4</td>
<td>Mango</td>
</tr>
<tr>
<td>5</td>
<td>Grape</td>
</tr>
</tbody></table>
<p>As you can see, we now have four records, but their IDs aren't necessarily consecutive. That's perfectly fine! Primary keys don't have to be consecutive numbers.</p>
<p>Next, we migrate these records into the new database. Since the schemas are different, we manually insert the existing records, including their IDs.</p>
<p>Here's the catch: manually inserting those IDs doesn't automatically synchronize the sequence associated with the id column.</p>
<p>So, even though our new <code>products</code> table already contains records with IDs <code>1</code>, <code>2</code>, <code>4</code>, and <code>5</code>, its associated sequence might still be at its initial state. In this example, let's assume the sequence hasn't generated any values yet and is still waiting to return its initial value, <code>1</code>.</p>
<p>What happens when we try to insert a new product?</p>
<p>PostgreSQL asks the sequence for the next value. Since the sequence hasn't been synchronized, it might generate <code>1</code> again. But wait! We already have a product with ID <code>1</code>, don't we?</p>
<p>As a result, PostgreSQL rejects the insertion because it violates the primary key constraint.</p>
<p>And here's another interesting detail: when PostgreSQL calls <code>nextval()</code> to generate a sequence value, that value is consumed even if the subsequent insertion fails. The sequence doesn't automatically roll back to its previous value.</p>
<p>So, if the next generated value is <code>2</code>, we'll encounter another primary key conflict. Then 3 comes along, and guess what? There's no product with ID <code>3</code> anymore!</p>
<p>Finally, the insertion succeeds.</p>
<p>And now the client's experience makes sense! They had to click the <code>Save</code> button multiple times because PostgreSQL kept generating IDs that were already occupied until it eventually reached an available one.</p>
<p>Well, who would've thought that something as seemingly insignificant as a database sequence could cause such a headache?</p>
<p>Now that we've identified the culprit, how do we fix it?</p>
<h1>The Fix: Synchronizing the Sequence</h1>
<p>Alright, now that we know what's causing the problem, let's fix it!</p>
<p>Fortunately, PostgreSQL provides a built-in function called <code>setval()</code> that allows us to manually set the current value of a sequence.</p>
<p>That's exactly what we need. We just have to synchronize the sequence with the existing IDs in our products table.</p>
<p>Here's the SQL query:</p>
<pre><code class="language-sql">SELECT setval(
    pg_get_serial_sequence('public.products', 'id'),
    COALESCE(MAX(id), 1),
    MAX(id) IS NOT NULL)
FROM public.products;
</code></pre>
<p>Let's break it down so we understand what's happening.</p>
<ol>
<li><code>pg_get_serial_sequence('public.products', 'id')</code></li>
</ol>
<p>This function retrieves the name of the sequence associated with the id column in the products table.</p>
<p>In other words, instead of having to remember or manually specify the sequence name, PostgreSQL can find it for us.</p>
<ol start="2">
<li><code>MAX(id)</code></li>
</ol>
<p>Pretty straightforward, right? This retrieves the highest ID currently available in the products table.</p>
<p>In our previous example, the highest ID is 5.</p>
<ol start="3">
<li><code>COALESCE(MAX(id), 1)</code></li>
</ol>
<p>This handles the possibility that the table is empty.</p>
<p>If <code>MAX(id)</code> returns <code>NULL</code>, <code>COALESCE()</code> uses 1 instead. This gives us a valid starting value for the sequence.</p>
<ol start="4">
<li><code>MAX(id) IS NOT NULL</code></li>
</ol>
<p>This is the third argument passed to <code>setval()</code>. It determines whether the value we've provided should be considered already used. Considering the function signature as follow:</p>
<pre><code class="language-sql">setval(sequence_name, value, is_called)
</code></pre>
<p>If the table contains records, this expression evaluates to <code>TRUE</code>. PostgreSQL will consider the provided value as already used, meaning the next call to <code>nextval()</code> will generate the following value.</p>
<p>If the table is empty, it evaluates to <code>FALSE</code>. This tells PostgreSQL that the provided value hasn't been used yet, so the next call to <code>nextval()</code> will return 1.</p>
<p>And that's it! 😄</p>
<p>In our example, since the highest existing ID is 5, the sequence will be synchronized to 5. The next time PostgreSQL generates a new ID, it will return 6.</p>
<p>No more primary key conflicts caused by an out-of-sync sequence!</p>
<p>Of course, make sure you execute this query after migrating the existing data. Also, replace public if your table belongs to a different schema.</p>
<p>After executing the query, you can verify the sequence's state by checking its current value and whether it has already been called:</p>
<pre><code class="language-sql">SELECT last_value, is_called 
FROM public.products_id_seq;
</code></pre>
<p>Just remember to replace <code>products_id_seq</code> with the actual sequence name if yours is different.</p>
<p>And that's how I fixed the problem! A couple of lines of SQL were all it took to resolve an issue that had been causing quite a headache.</p>
<h1>Conclusion</h1>
<p>And that's the story of how a seemingly successful database migration led to an unexpected issue with PostgreSQL sequences!</p>
<p>At first, everything appeared to have gone smoothly. All the existing data had been migrated, the application was running, and the client could continue using it. However, I overlooked one important detail: the sequence associated with the auto-incrementing primary key hadn't been synchronized with the existing records. Fortunately, PostgreSQL provides <code>setval()</code> to help us fix exactly this kind of issue.</p>
<p>But beyond the technical solution, there's another lesson I'd like to share, especially with junior developers who are just starting to design databases.</p>
<h3>Always choose your database data types carefully.</h3>
<p>Don't assume that something should be stored as an integer simply because its value consists of digits. Think about what the data actually represents and how it will be used.</p>
<p>For example, phone numbers, postal codes, product SKUs, and other identifiers generally don't need arithmetic operations. They're identifiers, not quantities. Storing them as strings (<code>VARCHAR</code>) is often a more appropriate choice.</p>
<p>Why does this matter? Because choosing inappropriate data types can introduce unnecessary complexity and unexpected bugs. This becomes particularly important when working with dynamically typed languages, where certain type-related mistakes might not be caught until runtime. Having appropriate data types and constraints at the database level provides an additional layer of protection, regardless of the programming language you're using.</p>
<p>And one last thing: when migrating a database, don't just focus on the data itself. Pay attention to the database objects and their states as well. Sequences, constraints, indexes, and relationships are all part of the bigger picture.</p>
<p>A migration isn't truly complete just because all the records have made it to their new home.</p>
<p>Anyway, that's all from me! I hope sharing this experience helps someone avoid running into the same problem. Thanks for reading, and happy coding! 😁</p>
]]></content:encoded></item></channel></rss>