ORA-001722 Invalid Number when insert in Oracle SQL - sql

CREATE TABLE the_user( Name VARCHAR(40) not null,
Address VARCHAR(255) not null,
Delivery_address VARCHAR(255),
Email VARCHAR(25) not null,
Phone INTEGER not null,
Status INTEGER not null,
Password VARCHAR(25) not null,
DOB DATE not null,
PRIMARY KEY (Email),
FOREIGN KEY (Status) REFERENCES User_Status (Status_Id),
CONSTRAINT check_Password CHECK (Password > 4)
);
INSERT INTO the_user VALUES (
'Pergrin Took',
'12 Bag end, hobbiton, The Shire, Eriador',
'The address, Dublin',
'ptook#lotr.com',
'8679046',
'001',
'treebeard',
TO_DATE('2013/11/04 14:11:34', 'yyyy/mm/dd hh24:mi:ss')
);
I have the above database in Oracle but when I try to run the insert command I get an ORA-1722 error, Invalid Number. There is a entry in the user_status table which corresponds to the 1 in the insert.
I have been stuck on this for days.

Quotes are not a problem - it will be converted implicitly to numbers as far as they are valid.
Check your constraints:
CONSTRAINT check_Password CHECK (Password > 4)
Here you try to compare string and number -> in this comparison Oracle always tries to cast both as numbers -> password fails and you see an error.
Try to use instead of password e.g. '55' and you will see the row is inserted.
Perhaps you wanted to do this?
CONSTRAINT check_Password CHECK (length(Password) > 4)

Related

Constraint not working as desired for my INSERT?

I am creating a Table named "Cliente" with some constraints on it as it follows:
CREATE TABLE public."Cliente" (
"K_CODCLIENTE" numeric(5) NOT NULL,
"N_NOMBRE1" varchar(15) NOT NULL,
"N_NOMBRE2" varchar(15) NOT NULL,
"N_APELLIDO1" varchar(15) NOT NULL,
"N_APELLIDO2" varchar(15),
"N_DIRECCION" varchar(50) NOT NULL,
"Q_TELEFONO" numeric(10) NOT NULL,
"K_CODREF" numeric(5),
"I_TIPOID" varchar(2) NOT NULL,
"Q_IDENTIFICACION" varchar(10) NOT NULL,
CONSTRAINT "PK_Cliente" PRIMARY KEY ("K_CODCLIENTE"),
CONSTRAINT "UQ_ID_TIPOID_CLIENTE" UNIQUE ("I_TIPOID","Q_IDENTIFICACION"),
CONSTRAINT "CK_CODCLIENTE" CHECK ("K_CODCLIENTE" >= 100),
CONSTRAINT "CK_Q_IDENTIFICACION" CHECK ("Q_IDENTIFICACION" IN ('CC', 'PA', 'CE', 'NI', 'OT'))
);
When I try to insert some values on it:
INSERT INTO "Cliente"
VALUES ('101','Juan','Felipe','Ortiz','Rojas','AK 15 no. 28-05','3101125507',null,'CC','51111111');
I get the following error (in PostgreSQL 14, on Fedora):
[23514] ERROR: new row for relation "Cliente" violates check constraint "CK_Q_IDENTIFICACION"
Detail: Failing row contains (101, Juan, Felipe, Ortiz, Rojas, AK 15 no. 28-05, 3101125507, null, CC, 51111111).
I am trying to restrict the "Q_IDENTIFICACION" column so it can only be filled with 'CC', 'PA', 'CE, 'NI' or 'OT'.
Maybe I'm doing something wrong when declaring the constraint "CK_Q_IDENTIFICACION"?
Seems like you messed up the mapping of values and are trying to insert '51111111' to "Q_IDENTIFICACION".
Consider this more revealing variant with a formatted list of target columns:
INSERT INTO "Cliente"
("K_CODCLIENTE", "N_NOMBRE1", "N_NOMBRE2", "N_APELLIDO1", "N_APELLIDO2", "N_DIRECCION" , "Q_TELEFONO", "K_CODREF", "I_TIPOID", "Q_IDENTIFICACION")
VALUES ('101' , 'Juan' ,'Felipe' , 'Ortiz' , 'Rojas' , 'AK 15 no. 28-05', '3101125507', NULL , 'CC' , '51111111'); -- !
Maybe you want to switch the last two column names in the table definition - and (not) adapt the VALUES list in the INSERT accordingly? (varchar(2) vs. varchar(10) seems switched as well.)
For persisted code, it's generally advisable to spell out target columns in an INSERT command in any case.
Asides:
Reconsider all these pesky double-quoted upper case identifiers. See:
Are PostgreSQL column names case-sensitive?
Consider plain type text instead of varchar(n) with strikingly tight character limits. See:
Any downsides of using data type "text" for storing strings?

How to prevent a input of certain letters using Oracle

The code is the category of the video, it is represented by one upper case character, excluding I, O,
Q, V, Y and Z, followed by a numeric character.
So far, I took a guess and got this. Any suggestions on how to fix it?
create table channelTable (
channelID number NOT NULL,
ChannelName varchar(100) NOT NULL,
ChannelDate date NOT NULL,
UserName varchar(100) NOT NULL UNIQUE,
TopicCode varchar(4) NOT NULL);
CONSTRAINT channelID_pk PRIMARY KEY (channelID)
CONSTRAINT c_topicCode LIKE '[A-Za-z][0-9] NOT (I,O,Q,N,Y,Z)
);
Some comments:
NOT NULL is not needed for PRIMARY KEY columns.
In Oracle, use VARCHAR2().
Then, I would suggests regular expressions. If the value is supposed to be exactly two characters, then declare it as such:
create table channelTable (
channelID number,
ChannelName varchar(100) NOT NULL,
ChannelDate date NOT NULL,
UserName varchar2(100) NOT NULL UNIQUE,
TopicCode char(2) NOT NULL;
CONSTRAINT channelID_pk PRIMARY KEY (channelID)
CONSTRAINT check (REGEXP_LIKE(c_topicCode, '^[A-HJ-NPR-UYZ][0-9]$')
);
Or perhaps more simply:
CONSTRAINT REGEXP_LIKE(c_topicCode, '^[A-Z][0-9]$') AND NOT REGEXP_LIKE(c_topicCode, '^[IOQNYZ]'))
All that said, I would rather see a table of TopicCodes that is populated with the correct values. Then you can just use a foreign key relationship to define the appropriate codes.
Use the regular expression ^[A-HJ-MPR-X]\d$ to match an upper-case character excluding I,O,Q,N,Y,Z followed by a digit:
CREATE TABLE channels (
id number CONSTRAINT channel__id__pk PRIMARY KEY,
Name varchar(100) CONSTRAINT channel__name__nn NOT NULL,
DateTime date CONSTRAINT channel__date__nn NOT NULL,
UserName varchar(100) CONSTRAINT channel__username__NN NOT NULL
CONSTRAINT channel__username__U UNIQUE,
TopicCode varchar(4),
CONSTRAINT channel__topiccode__chk CHECK ( REGEXP_LIKE( topiccode, '^[A-HJ-MPR-X]\d$' ) )
);
db<>fiddle
Also, you don't need to call the table channeltable just call it channels and you don't need to prefix the column names with the table name and you can name all the constraints (rather than relying on system generated constraint names which makes it much harder to track down issues when you are debugging).
Consider the following check constrait:
create table channelTable (
...
topicCode varchar(4) not null
check(
substr(c_topicCode, 1, 1) not in ('I', 'O', 'Q', 'V', 'Y', 'Z')
and regexp_like(topicCode, '^[A-Z]\d')
),
...
);
The first condition ensures that the code does not start with one of the forbidden characters, the second valides that it stats with an upper alphabetic character, followed by a number.
To avoid using two conditions, an alternative would be to list all allowed characters in the first position:
check(regexp_like(topicCode, '^[ABCDEFGHJKLMNPRSTUVWX]\d'))
This works in Oracle, and in very recent versions of MySQL.

sql- not null with default, check constraint

I have created a table and I'm asked to add a constraint to a column called no_semesters. the condition is that the no has to be >= 0 and it should be not null with default, and the default value is 6. When I run this statement:
INSERT INTO PREMIERD08/PGM (PGM_ID, PGM_NAME)
VALUES('CPD', 'COMPUTER PROGRAMMING')
I get an error message saying column - no_semesters cant be null. why wont it set to the default value which is 6?
this was the statement -
CREATE TABLE PREMIERD08/PGM (
PGM_ID CHAR(3) NOT NULL,
PGM_NAME CHAR(40) NOT NULL,
NO_SEMESTERS NUMERIC ( 1) NOT NULL WITH DEFAULT 6,
CONSTRAINT PGM_PGM_NAME_UK UNIQUE (PGM_NAME),
CONSTRAINT PGM_PGM_ID_CK CHECK (PGM_ID IN ('CPA', 'CPD') ),
CONSTRAINT PGM_PGM_ID_PK PRIMARY KEY (PGM_ID), CONSTRAINT PGM_NO_SEMESTERS_CK CHECK (NO_SEMESTERS >= 0)
)
Your code works in Db2 (for LUW) - the only thing to change is the table name needs to be in "" because of the /
CREATE TABLE "PREMIERD08/PGM" .....
INSERT INTO "PREMIERD08/PGM" (PGM_ID, PGM_NAME)
VALUES('CPD', 'COMPUTER PROGRAMMING')

Insert fails due to "column not allowed here" error

I am a beginner with SQL. I have created 4 tables and added data to my SHIP table. I am having some issues with inserting data into the CRUISE table. I get the error message at the bottom.
I have researched and can not figure out what i am doing wrong. Is there an issue with my sequence and/or trigger that is not allowing me to do this or is my syntax in the CREATE TABLE CRUISE causing the error? Everything i have done has been successful up until trying to insert the first column into the CRUISE table.
The tables:
CREATE TABLE SHIP
( Ship_Name VARCHAR2(100) PRIMARY KEY,
Ship_Size INTEGER,
Ship_Registry VARCHAR2(50),
Ship_ServEntryDate INTEGER,
Ship_PassCapacity INTEGER,
Ship_CrewCapacity INTEGER,
Ship_Lifestyle VARCHAR2(40),
CONSTRAINT Size_ck CHECK (Ship_Size > 0),
CONSTRAINT Registry_ck CHECK (Ship_Registry IN ('Norway','Liberia','The Netherlands','Bahamas'))
)
CREATE TABLE CRUISE (
Cruise_ID INTEGER Primary Key,
Ship_Name VARCHAR(100),
Cruise_DeptDate DATE NOT NULL,
Cruise_DeptCity VARCHAR(80) NOT NULL,
Cruise_Duration INTEGER,
FOREIGN KEY (Ship_Name) REFERENCES SHIP(Ship_Name)
)
CREATE TABLE PASSENGERS (
Pass_ID INTEGER PRIMARY KEY,
Pass_Name VARCHAR(100) NOT NULL,
Pass_City VARCHAR(80),
Pass_Telephone VARCHAR(15),
Pass_NextOfKin VARCHAR(100)
)
CREATE TABLE RESERVATIONS (
Pass_ID INTEGER NOT NULL,
Cruise_ID INTEGER NOT NULL,
Res_TotalCost NUMERIC(9,2),
Res_BalanceDue NUMERIC(9,2),
Res_SpecialRequest VARCHAR(30),
Res_Room VARCHAR(10),
FOREIGN KEY (Pass_ID) REFERENCES PASSENGERS(Pass_ID),
FOREIGN KEY (Cruise_ID) REFERENCES CRUISE(Cruise_ID),
CONSTRAINT Cost_ck CHECK (Res_TotalCost >= 0),
CONSTRAINT BalanceDue_ck CHECK (Res_BalanceDue >= 0),
CONSTRAINT SpecialRequest_ck CHECK (Res_SpecialRequest IN ('Vegetarian','Vegan','Low salt','Gluten free','Kosher','Other'))
)
The sequence/trigger is an attempt to auto number Cruise_ID.
Create SEQUENCE cruise_id_sq
START WITH 1
INCREMENT BY 1;
CREATE OR REPLACE TRIGGER cruise_id_t
BEFORE INSERT
ON CRUISE
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
if(:new.Cruise_ID is null) then
SELECT cruise_id_sq.nextval
INTO :new.Cruise_ID
FROM dual;
end if;
END;
ALTER TRIGGER cruise_id_t ENABLE;
Inserting into SHIP is okay....
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Carribean Princess',142000,'Liberia',1000,3100,1181,'Contemporary');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Carribean Sunshine',74000,'Norway',1992,1950,760,'Premium');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Ship of Dreams',70000,'Liberia',2004,1804,735,'Contemporary');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Sunshine of the Seas',74000,'The Netherlands',1990,2354,822,'Luxury');
Inserting into CRUISE fails...
INSERT INTO Cruise
(Ship_Name, Cruise_DeptDate,Cruise_DeptCity,CruiseDuration)
Values ('Sunshine of the Seas',25-may-15,'Miami',10);
Error starting at line : 1 in command - INSERT INTO Cruise (Ship_Name,
Cruise_DeptDate,Cruise_DeptCity,CruiseDuration) Values ('Sunshine of
the Seas',25-may-15,'Miami',10) Error at Command Line : 3 Column : 35
Error report - SQL Error: ORA-00984: column not allowed here
00984. 00000 - "column not allowed here"
*Cause:
*Action:
Oracle thinks that 25-may-15 is the expression 25 minus may minus 15. In looking up the value for may Oracle finds that there is nothing there. Thus the error.
You can, but probably don't want to, quote it like so, '25-may-15'. This will make a string that may or may not be implicitly converted to a date, depending on the settings of NLS_DATE_FORMAT and or NLS_TERRITORY.
To form a date independent of session setting one can use the TO_DATE function with explicit date format, to_date('25-may-15', 'DD-Mon-YY'). Another option is a date literal, date '2015-05-25', which is always YYYY-MM-DD no matter the session settings..

Literal does not match format string when creating a table

I keep trying to create a basic table. Every time I try to create the table I get the error
literal does not match format string
I'm trying to limit the years of the tournament between 2005 and 2100. The error is between DATE '2005'.
This is my code:
Create table Tournament_T
(Tournament_name VARCHAR (50) PRIMARY KEY NOT NULL,
Tournament_year INTEGER NOT NULL,
CONSTRAINT RANGE CHECK (Tournament_year BETWEEN DATE '2005' AND '2100'),
Tournament_rules CLOB NOT NULL,
Tournament_fee VARCHAR(1000) NOT NULL,
Tournment_eligibility VARCHAR (1000) NOT NULL );
COMMIT;
Your constraint is using the date keyword, but you don't need it. Just do:
CONSTRAINT RANGE CHECK (Tournament_year BETWEEN 2005 AND 2100),
Your column is an integer, not a date.