how to generate auto increment column which will be have some pattern in postgresql? - postgresql

I have a table named dept_registration it has a column dept_code so I have to make this field auto-generate but in a specific pattern.
example:- test0001
test0002
test0003
test0004
the "test" should be appended before number automatically after insertion

The column definition could be
dept_code text DEFAULT 'test' || lpad(nextval('myseq')::text, 4, '0')
where myseq is a sequence.
You will get in trouble once the counter reaches 10000...

Related

How to limit the length of array text objects in PostgreSQL?

Is there any way to add a constraint on a column that is an array to limit length text objects?
I know that I can do this without constraint:
colA varchar(100)[] not null
I tried to do it in the following way:
alter table "tableA" ADD CONSTRAINT "colA_text_size"
CHECK ((SELECT max(length(pc)) from unnest(colA) as pc) <= 100) NOT VALID;
alter table "tableA" VALIDATE CONSTRAINT colA_text_size;
But got error: cannot use subquery in check constraint (SQLSTATE 0A000)
Try the following definition for your check constraint: (see demo, for demo I limit length to 25).
check (length(replace(array_to_string( text_array ,','), ',','')) <= 100)
What it does:
First the function array_to_string( ... ) converts the array to a csv.
The replace() function then removes the commas replacing them with the zero length string ''.
The length() function gets number of remaining characters in the string.
Finally that number is compared to the limit value (100) and the check constraint is either passed of failed.
References:
array_to_string(),
replace(), length()

Check if character varying is between range of numbers

I hava data in my database and i need to select all data where 1 column number is between 1-100.
Im having problems, because i cant use - between 1 and 100; Because that column is character varying, not integer. But all data are numbers (i cant change it to integer).
Code;
dst_db1.eachRow("Select length_to_fault from diags where length_to_fault between 1 AND 100")
Error - operator does not exist: character varying >= integer
Since your column supposed to contain numeric values but is defined as text (or version of text) there will be times when it does not i.e. You need 2 validations: that the column actually contains numeric data and that it falls into your value restriction. So add the following predicates to your query.
and length_to_fault ~ '^\+?\d+(\.\d*)?$'
and length_to_fault::numeric <# ('[1.0,100.0]')::numrange;
The first builds a regexp that insures the column is a valid floating point value. The second insures the numeric value fall within the specified numeric range. See fiddle.
I understand you cannot change the database, but this looks like a good place for a check constraint esp. if n/a is the only non-numeric are allowed. You may want to talk with your DBA ans see about the following constraint.
alter table diags
add constraint length_to_fault_check
check ( lower(length_to_fault) = 'n/a'
or ( length_to_fault ~ '^\+?\d+(\.\d*)?$'
and length_to_fault::numeric <# ('[1.0,100.0]')::numrange
)
);
Then your query need only check that:
lower(lenth_to_fault) != 'n/a'
The below PostgreSQL query will work
SELECT length_to_fault FROM diags WHERE regexp_replace(length_to_fault, '[\s+]', '', 'g')::numeric BETWEEN 1 AND 100;

Update a varchar column depending of the actual value

I'm using PostgreSQL 9.3.
I have a varchar column in a table that can be null and I want to update it depending of its value is null or not.
I didn't manage to do a function that takes a String as argument and updates the value like this:
If the column is null, the function concatenates the current string value, a comma and the string given as argument, else it just adds the string at the end of the current string value (without comma).
So how can I make a different Update depending of the column value to update?
You can use a case statement to conditionally update a column:
update the_table
set the_colum = case
when the column is null then 'foobar'
else the_column||', '||'foobar'
end
An another approach
UPDATE foo
SET bar = COALESCE(NULLIF(concat_ws(', ', NULLIF(bar, ''), NULLIF('a_string', '')), ''), 'a_string')

how to use identity and concatenate it into the other columns of the table?

If I generate an identity for a table on the column cust-id, I want the next column userid to be cust-id+CID.
E.g. 000000001CID, 0000000002CID
What sql do I include for this?
Similarly if I have 00001 in the column Cust-id and abcd in the column section, the 3rd column must have value 00001abcd
Please let me know the solutions
You just need to create a trigger. Something like
CREATE TRIGGER A
BEFORE INSERT ON TABLE B
REFERENCING NEW AS N
FOR EACH ROW
BEGIN
SET N.userid = N.CUST_ID + N.CID ;
IF (N.CUST_ID = '00001' AND N.SECTION = 'abcd') THEN
SET N.THIRD = N.CUST_ID + N.SECTION
END IF;
END #
By the way, generating values in column shows that your module is not normalize, and sometimes this is a source of errors.

Is it possible to create a DEFAULT clause with an incrementing identifier?

I would like to know whether it is possible to achieve something like the following in PostgreSQL:
I have a table named Dossier (means "folder" in English), with the the following table structure: name, taille,...
Now, what I'd like to have on my table is a condition such that each time a new instance of Dossier is created, the value in the name column is automatically supplemented with a self-incrementing identifier like so: ref00001, ref00002 etc. (To clarify, after the second insertion, the value for the name column should be ref00002 automatically...)
CREATE SEQUENCE seq_ref;
CREATE TABLE dossier
(
ref TEXT NOT NULL PRIMARY KEY DEFAULT 'ref' || NEXTVAL('seq_ref'),
value TEXT
);
If you want zero-padded numbers, use this:
CREATE SEQUENCE seq_ref;
CREATE TABLE dossier
(
ref TEXT NOT NULL PRIMARY KEY DEFAULT 'ref' || LPAD(NEXTVAL('seq_ref')::TEXT, 10, '0'),
value TEXT
);