Duplicate key error using nvarchar when adding new row with same number but leading 0 - sql

I want to insert a row into a table where in the primary key column I have a value of 3719. However, in the same table I want to add details with 03719 but I am getting an error:
The duplicate key value is (3719).
The datatype of that column is nvarchar.

I think your problem arises from the fact that you forgot to wrap the string value to be inserted in single quotes, so it is treated like a number, which is auto-converted to nvarchar.
INSERT INTO Table (Column) VALUES (03719)
is equivalent to
INSERT INTO Table (Column) VALUES (3719)
The value (because of the column type) is then converted to the string '3719'. Of course you then get a duplicate key error.
Check the quotes. If you're calling this from an application, use parameterized queries!

Correct statement to insert the records is like
Create table test (id nvarchar(25) primary key, name varchar(20))
insert into test values('111','hello')
insert into test values('0111','hello')
select * from test
You're forgetting to put the quotes.
If you do not put the quotes, you will get the below kind of error
Violation of PRIMARY KEY constraint 'PK__test__3213E83F2C904DEB'.
Cannot insert duplicate key in object 'dbo.test'. The duplicate key value is (111).

Related

SQLite specifying primary key

In short, i have this clause:
CREATE TABLE IF NOT EXISTS `journalData`
(
`JD_Key` INTEGER PRIMARY KEY AUTOINCREMENT,
`JD_Event_Key` INTEGER,
`JD_VarCount` INTEGER,
`JD_VarTypes` TEXT,
`JD_VarValues` TEXT,
`JD_EventDate` TEXT
);
INSERT INTO `journalData`
VALUES (24, 0, '', '', '04.02.2023 20:26:18');
And following SQLite tutorials on AUTOINCREMENT (https://www.sqlitetutorial.net/sqlite-autoincrement/), it says the following:
Second, insert another row without specifying a value for the person_id column:
INSERT INTO people (first_name,last_name)
VALUES('William','Gate');
Implying, that you can add rows to the table, without having to specify primary key of a table, but I get this error:
Uncaught Error: table journalData has 6 columns but 5 values were supplied
What am I doing here wrong? I've tried to add single row with the key before mentioned insert. But I keep getting this error
I found a solution, it seems that error was somewhat misleading, i have to specify columns names.
though, if i specify all of the values in table it is not necessary to specify columns names, so because of that, during testing i assumed that syntax here is similar to MySQL, where from experience i remembered, that you don't have to specify names in this exact case.
so the following query worked for me.
INSERT INTO `journalData`
(JD_Event_Key, JD_VarCount, JD_VarTypes, JD_VarValues, JD_Event_Date)
VALUES (24,0,'','','04.02.2023 20:26:18');

postgres doesn't autogenerate PK if the PK is inserted manually

I have a simple table like this:
CREATE TABLE IF NOT EXISTS myval
(
id integer NOT NULL DEFAULT nextval('myval_myval_id_seq'::regclass),
name character varying(255),
CONSTRAINT "PK_aa671c3359a0359082a84ecb801" PRIMARY KEY (id)
)
the sequence definition is:
CREATE SEQUENCE IF NOT EXISTS myval_myval_id_seq
INCREMENT 1
START 1
MINVALUE 1
MAXVALUE 2147483647
CACHE 1
OWNED BY myval.myval_id;
when I insert data along with the primary key:
INSERT INTO myval(id, name) VALUES (1, 'sdf');
INSERT INTO myval(id, name) VALUES (2, 'sdf');
INSERT INTO myval(id, name) VALUES (3, 'sdf');
INSERT INTO myval(id, name) VALUES (4, 'sdf');
then, I insert it without the PK:
INSERT INTO myval(name) VALUES ('new sdf');
it gives an error saying:
duplicate key value violates unique constraint "PK_aa671c3359a0359082a84ecb801",
DETAIL: Key (myval_id)=(1) already exists.
I expected it to start with PK value of 5 but, instead it gives an error. Can we configure postgres to skip conflicting values and generate from the closest available value to use instead of throwing an error?
The best way to avoid such conflicts is to use identity columns - in this case a GENERATED ALWAYS AS IDENTITY seems the right option.
CREATE TABLE IF NOT EXISTS myval
(
id integer GENERATED ALWAYS AS IDENTITY,
name character varying(255),
CONSTRAINT "PK_aa671c3359a0359082a84ecb801" PRIMARY KEY (id)
);
This will work like a sequence (serial), however it will fail if the user tries to manually insert a value in this column
INSERT INTO myval (id,name)
VALUES (1,'foor');
ERROR: cannot insert a non-DEFAULT value into column "id"
DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
TIP: Use OVERRIDING SYSTEM VALUE to override.
If for whatever reason you must override this behavior in a certain INSERT statement you can do so using OVERRIDING SYSTEM VALUE, as the error message above suggests
INSERT INTO myval (id,name) OVERRIDING SYSTEM VALUE
VALUES (1,'foo');
You might be able to achieve a sequential value using serial even if the user screws things up with inserts, e.g. using trigger functions. But such an architecture is hard to maintain and imho is definitely not worth the trouble.
Demo: db<>fiddle

SQL Server unique constraint issue on unicode characters

I have my table definition as follows:
create table [Language](
Id int primary key identity,
Code varchar(11) not null unique,
NativeName nvarchar(50) not null unique
)
And then, I have a long list of statements that insert into that table. The problem is that some of the insert statements conflict on my NativeName column's unique constraint. The weird thing is that the content is not unique at all. For example, if I only insert the following with the table empty:
insert into Language (Code, NativeName) values('am', N'አማርኛ');
insert into Language (Code, NativeName) values('dv', N'ދިވެހިބަސް‏');
I get for the second insert.
Violation of UNIQUE KEY constraint 'UQ__Language__EB1957A5F98D1F9C'. Cannot insert duplicate key in object 'dbo.Language'. The duplicate key value is (ދިވެހިބަސް‏).
Does anyone know why unicode characters are causing these issues?
Try declaring the NativeName column with a more specific (binary) collation.
eg:
NativeName nvarchar(50) collate SQL_Latin1_General_CP437_BIN not null unique

Inserting Char value into SQL table

I created a SQL table an enforced check constraints on it, but now when I try to insert data I get an error message.
create table BranchTel
(
BrRegNo varchar(10) REFERENCES Branch(BrRegNo),
TelNo char(12)
PRIMARY KEY(BrRegNo)
)
ALTER TABLE BranchTel Add Constraint BranchTelTelNo
Check(TelNo LIKE '[0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
Insert statement
insert into BranchTel values('BG-205','940112571963')
Error message
The INSERT statement conflicted with the CHECK constraint "BranchTelTelNo". The conflict occurred in database "StudentDetails", table "dbo.BranchTel", column 'TelNo'.
The statement has been terminated.
Insert statement
insert into BranchTel values('BG-205','94-011-2571963')
Error message
String or binary data would be truncated.
The statement has been terminated.
Please help me
Your check constraint is 14 characters long (you need to count the - as well), while the field size is 12.
Additionally, 940112571963 does not conform to the pattern xx-xxx-xxxxxxx you have defined in your check constraint.
You need to change the field size to 14 and when inserting make sure the dashes are in the right place:
insert into BranchTel values('BG-205','94-011-2571963')
Insert statement insert into BranchTel values('BG-205','94-011-2571963') Error message String or binary data would be truncated. The statement has been terminated.
Here the value 94-011-2571963 length is greater than 12 which obviously violates the check constraint.

how to generate primary key values while inserting data into table through pl/sql stored procedure

I need to insert data into particular table through pl/sql stored procedure. My requirements are:
while inserting it should generate PRIMARY KEY values for a particular column;
it should return that PRIMARY KEY value to an output variable; and
for another column it should validate my string such that it should contain only characters, not integers.
You can generate primary key values as a surrogate key using an Oracle SEQUENCE. You can create a constraint on a column that uses TRANSLATE to check that no numeric digits exist in newly inserted/updated data.
Some example code, suitable for SQL*Plus:
CREATE SEQUENCE mysequence;
/
CREATE TABLE mytable (
pkidcol NUMBER PRIMARY KEY,
stringcol VARCHAR2(100)
);
/
ALTER TABLE mytable ADD (
CONSTRAINT stringnonnumeric
CHECK (stringcol = TRANSLATE(stringcol,'A0123456789','A'))
);
/
DECLARE
mystring mytable.stringcol%TYPE := 'Hello World';
myid mytable.pkidcol%TYPE;
BEGIN
INSERT INTO mytable (pkidcol, stringcol)
VALUES (mysequence.NEXTVAL, mystring)
RETURNING pkidcol INTO myid;
END;
/
In oracle I believe the "identity" column is best achieved with a sequence and an insert trigger that checks if the primary key columns is null and if so gets the next sequence and inserts it.
you can then use the "returning" clause to get the newly created primary key:
insert into <table> (<columns>) values (<values>) returning <prim_key> into <variable>;
the filtering of the string field I would personally handle in code before going to the database (if that is a possibility). Databases are notoriously inefficient at handling string operations.