Jekyll2023-01-21T22:42:19+00:00https://knsankar.github.io/feed.xmlNavaneetha Sankar KA security blogResize a column in a PostgreSQL table without changing data2019-08-14T14:23:09+00:002019-08-14T14:23:09+00:00https://knsankar.github.io/Resize-a-column-in-a-PostgreSQL-table-without-changing-data<p>I needed to increase the length of a column without any change in data. I went through stackoverflow as usual :) and found a old article by <a href="https://sniptools.com/databases/resize-a-column-in-a-postgresql-table-without-changing-data/">sniptools</a> .</p>
<p>The original article was writen in 2009 and few things has to be changed.</p>
<p>TL;DR</p>
<p><br /></p>
<p>In the below example table name is TAB1 and the column that we want to alter is COL1</p>
<p>To check the existing size, simply run the following query.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
SELECT atttypmod FROM pg_catalog.pg_attribute
WHERE attrelid = 'TAB1'::regclass
AND attname = 'COL1';
</code></pre></div></div>
<p><br /></p>
<p>The sample result is</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>attypmod
---------
34
</code></pre></div></div>
<p>This means that the column current size is 30 (4 was added for a legacy reason it seems.)</p>
<p><br /></p>
<p>Now we can change it to <strong><em>varchar(40)</em></strong> by executing the following query.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>UPDATE pg_catalog.pg_attribute SET atttypmod = 40+4
WHERE attrelid = 'TAB1'::regclass
AND attname = 'COL1';
</code></pre></div></div>
<p><br /></p>
<p>The sample result is</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>UPDATE 1
</code></pre></div></div>
<p><br /></p>
<p>This can be verified by running <strong><em>\d DATABASENAME</em></strong></p>
<p>Cheers!!!</p>Navaneetha SankarI needed to increase the length of a column without any change in data. I went through stackoverflow as usual :) and found a old article by sniptools .New Blog!!2017-10-12T15:04:23+00:002017-10-12T15:04:23+00:00https://knsankar.github.io/welcome-to-my-blog<p>Hello Guys,
I am excited to start a blog and ramble about things :)</p>
<p>I will write something soon ;)</p>
<p>Checkout my social media presence in <a href="http://twitter.com/knsankar">twitter</a> , <a href="https://fb.com/navaneethasankar">facebook</a>, <a href="https://linkedin.com/in/navaneethasankar">LinkedIn</a></p>Navaneetha SankarHello Guys, I am excited to start a blog and ramble about things :)