Can't insert a int value in a decimal column SQL - sql

Currently working on a school project.
I'm trying to create the following table:
CREATE TABLE Purchase (
ID INT NOT NULL,
Type INT DEFAULT 3 NOT NULL,
Price DECIMAL(5,5) NOT NULL,
CONSTRAINT check_3 CHECK (TYPE = 3),
CONSTRAINT price_check CHECK (Cost>0),
CONSTRAINT pk_1 PRIMARY KEY (ID),
CONSTRAINT fk_1 FOREIGN KEY (ID,Type) REFERENCES Part(ID,Type));
My problem is when I'm trying to insert values into this column.
When I try to do this:
INSERT INTO Purchase VALUES (12, 3, 200);
I get the following error:
SQL> INSERT INTO Purchase VALUES (12, 3, 200);
INSERT INTO Purchase VALUES (12, 3, 200)
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
I don't get what I'm doing wrong. Can't I add integers to a decimal column? Is that the problem? Doesn't make much sense to me.
Thank you for taking the time to read this!

First, always list the columns for an insert:
INSERT INTO Purchase (id, type, price)
VALUES (12, 3, 200);
Second, your price is declared as DECIMAL(5, 5). That means that the prices range from 0.00000 to 0.99999.
Presumably, you want a broader range. I don't know what that is, but DECIMAL(10, 5) would solve your problem. More generally, just NUMBER solves your problem in Oracle.

DECIMAL(5,5) means you will recieve space for 5 number after the comma (5 of 5). Please try to create your table like that: DECIMAL(10,5)

Related

How can I insert values into a table with a composite primary key?

These are the tables I already have:
CREATE TABLE Gyartok
(
GyID INT IDENTITY(2, 3),
Nev VARCHAR(20),
CONSTRAINT PK_Gyartok PRIMARY KEY (GyID)
)
CREATE TABLE Focicsuka
(
CsID INT IDENTITY(2, 2),
Meret INT,
CONSTRAINT PK_Focicsuka PRIMARY KEY (CsID)
)
CREATE TABLE FcsGyartjaGya
(
GyID INT IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1
FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2
FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya
PRIMARY KEY (GyID, CsID)
)
The problem is that every time I try to add new values to the table (like such)
INSERT INTO FcsGyartjaGya (Ar) VALUES (300);
I get an error saying I didn't initialize the CsID INT column:
Cannot insert the value NULL into column 'CsID', table 'Lab3.dbo.FcsGyartjaGya'; column does not allow nulls. INSERT fails.
I know I must initialize it with something, but I have no idea what do to it with, because IDENTITY(x, y) doesn't work (it's occupied by another column already) and adding another parameter to the code (like such)
INSERT INTO FcsGyartjaGya (Ar, CsID) VALUES (300, 7);
creates another error which says
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Lab3a", table "dbo.Gyartok", column 'GyID'.
It is important to note that I already filled every column with data, so that couldn't be the problem.
As I mention in the comments, your INSERT will work fine, provided the stars align correctly. For your table Gyartok you have GyID as your PRIMARY KEY, which is defined as a IDENTITY(2,3); so the first value generated is 2 and then each row attempted to be INSERTed will increment by 3.
So, if we run the following, we get the IDs 2, 5, 7 and 17. (11 and 14 are skipped as the INSERT failed).
CREATE TABLE Gyartok (
GyID INT IDENTITY(2, 3),
Nev VARCHAR(20),
CONSTRAINT PK_Gyartok PRIMARY KEY (GyID)
);
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES ('asdfjahsbvd'),
('ashjkgdfakd'),
('kldfbhjo');
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES (REPLICATE('A',25)), --Force a truncation error
('ashjkgdfakd');
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES (REPLICATE('A',15));
Let's now add some data for your other table:
CREATE TABLE Focicsuka (
CsID INT IDENTITY(2, 2),
Meret INT,
CONSTRAINT PK_Focicsuka PRIMARY KEY (CsID)
)
INSERT INTO dbo.Focicsuka (Meret)
VALUES(12),
(25);
Now we want to INSERT into the table FcsGyartjaGya, defined as the following:
CREATE TABLE FcsGyartjaGya (
GyID INT IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1 FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2 FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya PRIMARY KEY (GyID, CsID)
)
This has a IDENTITY on GyID, but defined as an IDENTITY(3,2), so the first value is 3 and then incremented by 2.
As this has 2 foreign keys, on GyID and CsID when we INSERT the row the values must appear in the respective tables. As GyID is defined as anIDENTITY(3,2) however, this is where we need to rely on the Stars luck for the INSERT to work. Why? Well 2 + (3*n) and 3+(2*n) can give very different numbers. The first are as you saw at the start of this answer. For the latter, we have numbers like 3, 5, 7, 9, 11. As you can see, only 1 in 3 of these numbers match a number in our original sequence, so luck is what we are going to be relying on.
Let's, therefore, try a single INSERT.
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(2,1);
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Sandbox", table "dbo.Gyartok", column 'GyID'.
Well, that didn't work, but it was expected. 3 isn't a value in the table Gyartok. Let's try again!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(2,2);
It worked! The stars Luck was our side, and the IDENTITY value was a value in the table Gyartok. Let's try a couple of rows this time!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,3),
(4,4);
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Sandbox", table "dbo.Gyartok", column 'GyID'.
No!! Not again. :( That's because the stars didn't align; 7 and 9 aren't in the other table. But wait, 11 was in the sequence, so let's try that:
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,5);
Error, again?! No, it cannot be!!! :( Oh wait, I forgot, the stars were against us before, because that INSERT failed against Gyartok for the value of 11. I need to wait for 17!
--13 fails
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
GO
--15 fails
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
GO
--17 works!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
And now we have another row in our table.
So what is the problem? Your design. GyID is defined as an IDENTITY and a FOREIGN KEY; meaning you are at the "whims" of SQL Server generating a value valid. This is not what you want. Just don't define the column as an IDENTITY and then INSERT the data with all 3 of your columns defined:
CREATE TABLE FcsGyartjaGya (
GyID int,-- IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1 FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2 FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya PRIMARY KEY (GyID, CsID)
)
GO
INSERT INTO dbo.FcsGyartjaGya (GyID, CsID, Ar)
VALUES(2,2,1),
(2,4,2),
(5,4,3),
(8,2,4),
(8,4,5);
And all these rows insert fine.
I think there is a bit confusion, if I understand correctly what You're trying to do, then you have two tables each with their own id, which is based on an identity column, so you get new values in those for free.
Then you are trying to make a relation table with extra data.
Issue 1: You cannot have FcsGyartjaGya.GyID be identity if it refers to Gyartok.GyID because you will want to insert into it and not rely on an auto increment. If it doesn't refer to the same it should have another name or my head will possibly explode :))
Issue 2: When populating a relation table you need to insert it with what pairs you want, there is no way SQL server can know how it should match these identity pairs in the relation table
I think this is what people are aiming at in the comments, for example
to insert a relationship between row with Focicsuka.CsID = 1 to Gyartok.GyID 7 and adding Ar = 300 have to look like
INSERT INTO FCSGYARTJAGYA(GYID, CSID, AR)
VALUES(7, 1, 300)
Unless You've forgotten to mention that you want to put some value for each of some value or based on something which can be scripted, in other words unless You have logics to define the pairs and their values, relationship tables cannot have defaults on their foreign key fields.

SQL data truncation for date value

I'm having a hard time creating a simple table:
CREATE TABLE `csat` (
`csat_id` INT NOT NULL AUTO_INCREMENT,
`value` INT,
`month` DATE NOT NULL,
PRIMARY KEY (`csat_id`)
);
CREATE TABLE `migrated` (
`migrated_id` INT NOT NULL AUTO_INCREMENT,
`title` INT,
`description` INT,
`month` DATE NOT NULL,
PRIMARY KEY (`migrated_id`)
);
INSERT INTO csat
VALUES (1, 1, 2017-06-15);
INSERT INTO migrated
VALUES (1, 2, 2018-06-15);
I get the error:
Data truncation: Incorrect date value: '1996' for column 'month' at row 1
It seems like my date is in the right format:
https://www.w3schools.com/sql/func_mysql_date.asp
I'm also wondering why I need to specify a value on the csat_id, because I thought SQL would just put that in for me since its the primary key.
You have to wrap your date values in single quotation marks: '2017-06-15', not 2017-06-15. Right now, MySQL is evaluating this as 2017 minus 6 minus 15, which comes to 1996.
Also, when inserting, it's best to specify the columns you're inserting into. And if your column is set to AUTO_INCREMENT, you don't need to specify it:
INSERT INTO csat
(`value`, `month`)
VALUES
(1, '2017-06-15');
I would also consider changing your column names. Perhaps make "value" more descriptive (value of what?) And month is misleading, since it's actually a date-type column.
You haven't said which database server you're using, but generally speaking dates are inputted as strings.
You should try the following inserts;
INSERT INTO csat (`csat_id`, `value`, `month`)
VALUES (1, 1, '2017-06-15');
INSERT INTO migrated (`migrated_id`, `title`, `description`, `month`)
VALUES (1, 2, 2, '2018-06-15');
Also, you should specify which columns you're inserting into. This prevents data from being entered into the wrong fields, especially when schema changes occur.
SQL does auto increment primary key fields (if defined that way). However, you had to define it in your insert statements because you didn't specify the columns you were inserting to.
Try this instead;
INSERT INTO csat (`value`, `month`)
VALUES (1, '2017-06-15');
INSERT INTO migrated (`title`, `description`, `month`)
VALUES (2, 2, '2018-06-15');
I guess you missed the single qoutes (as per Sql standards) at first in your date and then while inserting even if the column is autoincrement you need to specify columns other than the autoincrement column so as to make sure the data you are inserting belongs to that specific column or not
Try this
INSERT INTO
csat(value,month) values
(1,'2017-06-15')

How should I handle multiple foreign keys that all point to the same column in another table?

So let's say I have these two tables...
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='UnitsDef' AND xtype='U')
CREATE TABLE UnitsDef
(
UnitsID INTEGER PRIMARY KEY,
UnitsName NVARCHAR(32) NOT NULL,
UnitsDisplay NVARCHAR(8) NOT NULL
);
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Dimensions' AND xtype='U')
CREATE TABLE Dimensions
(
DimID INTEGER PRIMARY KEY IDENTITY(0,1),
DimX FLOAT,
DimXUnitsID INTEGER DEFAULT 0,
DimY FLOAT,
DimYUnitsID INTEGER DEFAULT 0,
DimZ FLOAT,
DimZUnitsID INTEGER DEFAULT 0,
FOREIGN KEY (DimXUnitsID) REFERENCES UnitsDef(UnitsID),
FOREIGN KEY (DimYUnitsID) REFERENCES UnitsDef(UnitsID),
FOREIGN KEY (DimZUnitsID) REFERENCES UnitsDef(UnitsID)
);
I'll insert data into the first table similar to this...
INSERT INTO UnitsDef (UnitsID, UnitsName, UnitsDisplay) VALUES (0, 'inch', 'in.');
INSERT INTO UnitsDef (UnitsID, UnitsName, UnitsDisplay) VALUES (1, 'millimeter', 'mm');
INSERT INTO UnitsDef (UnitsID, UnitsName, UnitsDisplay) VALUES (2, 'degree', '°');
Am I going about this the right way? This is a simplified version of the problem, but I need to know which unit each measurement is given in. Is there a better design practice for this type of situation?
How would I handle the ON DELETE and ON UPDATE for these foreign keys? If I try to cascade deletes and updates, SQL Server would not be so happy about that.
Your method is pretty good. I would make the suggestion right off that UnitsId be an identity column, so it gets incremented. Your inserts would then be:
INSERT INTO UnitsDef (UnitsName, UnitsDisplay) VALUES ('inch', 'in.');
INSERT INTO UnitsDef (UnitsName, UnitsDisplay) VALUES ('millimeter', 'mm');
INSERT INTO UnitsDef (UnitsName, UnitsDisplay) VALUES ('degree', '°');
You should also make the string columns unique in UnitsDef and give them case-sensitive collations. After all, Ml and ml are two different things ("M" is mega and "m" is milli).
You might also want to combine the units and values into a single type. This has positives and negatives. For me it adds overhead, but it can help if you want to support a fuller algebra of types.

How to add row to a SQL Server table with uniqueidentifier type column?

I need to add a row to a SQL Server table called Customers.
Here is the table design:
Here how I try to add a row to the table above:
INSERT INTO Customers (Id, Name)
VALUES (1, 'test');
But I get this error:
Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with uniqueidentifier
As you can see the ID column of type uniqueidentifier. How do I add a uniqueidentifier to the column above?
The uniqueidentifier data type stores 16-byte binary values that operate as globally unique identifiers (GUIDs).
Example using:
insert into customers values('7E3E3BC1-9B15-473C-A45A-46D89689156C', 'Tomas')
insert into customers values(newid(), 'Tomas')
See more details: https://technet.microsoft.com/en-US/library/ms190215(v=sql.105).aspx
Use newid():
INSERT INTO Customers(Id, Name) VALUES (newid(), 1);
Note that this would often be done using a default value:
create table customers (
id uniqueidentifier default newid(),
. . .
);
For various technical reasons, it is not recommended to make the uniqueidentifier column a primary key -- although you can get around some of the problems using newsequentialid().. Instead, make it a unique key and have another key (typically an identity() column) as the primary key.

Why can I insert a number into a VARCHAR2 column?

I have an odd problem with a table, I'm inserting rows into tables, and now I am trying to test it, on one of my tests it allows an entry that it shouldn't.
My table definition:
CREATE TABLE ITEMS(
ITEM_NUMBER VARCHAR2(3)
CONSTRAINT ITEMS_ITEM_NUMBERf_PK PRIMARY KEY,
ITEM_DESCRIPTION VARCHAR2(30),
ITEM_SIZE VARCHAR2(2),
ITEM_COST NUMBER(30,0),
ITEM_QTY NUMBER(2,0),
ORDER_NUMBER VARCHAR2(4));
When I try and test the ITEM_SIZE column by putting in a number it just inserts it.
INSERT INTO ITEMS VALUES ('I32', 'Leather blazer', 'L', 14.00, 1, 'O114');
INSERT INTO ITEMS VALUES ('I33', 'Fleece vest', 'L', 28.00, 1, 'O128');
INSERT INTO ITEMS VALUES ('I34', 'Khaki pants', 'S', 22.00, 3, 'O122');
INSERT INTO ITEMS VALUES ('I35', 'Muscle Tee', 'M', 12.99, 1, 'O122');
INSERT INTO ITEMS VALUES ('I36', 'Trench Coat', 'M', 03.00, 1, 'O133');
INSERT INTO ITEMS VALUES ('I37', 'Crewneck sweater', 'XL', 07.00, 1, 'O107');
INSERT INTO ITEMS VALUES ('I38', 'Varsity Sweater', 'M', 08.99, 1, 'O108');
INSERT INTO ITEMS VALUES ('I39', 'CROOK', 'M', 12.00, 1, 'O112');
//--the tester--//
INSERT INTO ITEMS VALUES ('I49', 'bROOK', 10, 12.00, 1, 'O112');
In the statement above I insert the number 10 into ITEM_SIZE VARCHAR2(2). How can I avoid that?
As #kevinsky said, Oracle is doing implicit data conversion from number to string while you insert.
If you want to restrict the values that can be put into a column then you can add a check constraint:
alter table items add constraint items_size_chk
check (item_size in ('XXS','XS','S','M','L','XL','XXL','XXXL'));
Table ITEMS altered.
INSERT INTO ITEMS VALUES ('I49', 'bROOK', 10, 12.00, 1, 'O112');
SQL Error: ORA-02290: check constraint (SCHEMA.ITEMS_SIZE_CHK) violated
02290. 00000 - "check constraint (%s.%s) violated"
*Cause: The values being inserted do not satisfy the named check
If you want different restrictions you can change the way the check is done; for example you could have a regular expression check to exclude digits but allow any characters. In this case it seems more likely you want a list of specific values to be allowed though.
Note though that when a new valid size is added, you will have to modify the check constraint; and any of those size values will be allowed for any item.
If the valid sizes are coming from another table then you can use a foreign key constraint instead. You probably really want a list of sizes (or other attributes) that are valid for each item, so your data model might need some fleshing out.
Oracle is implicitly converting the number 10 into the varchar2 string '10'.
and here is another implicit conversion
SELECT item_size + 1 FROM items;
Result in Oracle 11g is
11
I'm not sure whether this was intended to be helpful when the parser was being built but it does cause a lot of confusion. However Oracle will not convert an alphabetical character into a number implicitly. It will fail.