SQL data truncation for date value - sql

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')

Related

SQL Beginner trying to insert data on tables

I have started my journey in learning SQL and right I am having trouble creating and inserting data into tables. Here is the code that I have tried, I get an error message saying that there aren't enough values. I am using Oracle.
Create table project
(
proj_id number(10),
medic_name varchar2(10),
purpose varchar2(12),
start_date date,
end_date date,
pi_id null,
CONSTRAINT pkprojid primary key (proj_id),
CONSTRAINT fkproject foreign key (pi_id) references researcher
);
alter session set nls_date_format = 'mm/dd/yyyy';
Insert into project values (PR001, 'Medic1', 'heart', '09/01/2017', '07/31/2019');
Insert into project values (PR002, 'Medic1', 'diabetes', '10/01/2016', '07/31/2020);
Insert into project values (PR003, 'Medic3', 'lung', '11/1/2014', '12/31/2020');
Insert into project values (PR004, 'Medic3', 'blood', '01/10/2017', '07/31/2019');
Insert into project values (PR005, 'Medic5', 'blood', '07/10/2018', '01/31/2020');
alter session set nls_date_format = 'mm/dd/yyyy';
Insert into project values (PR001, 'Medic1', 'heart', '09/01/2017', '07/31/2019');
Issues:
Your table has 6 columns, you are only passing 5 for insert; it seems like you are missing last column (pi_id), hence the error message that you are getting. If you want to skip the last column (which is possible since it is declared as nullable), you can explictly list the column when inserting
first column (proj_id) is of number datatype; PR001 is not a number (neither a string, since it is not quoted: this is a syntax error); did you mean 1 instead? Or, if you want to insert string values, you need to change the datatype of column proj_id to varchar(N) (N being the maximum length of the string, in bytes).
Here is an insert statement that should work for your current table definition:
insert into project(proj_id, medic_name, purpose, start_date, end_date)
values (1, 'Medic1', 'heart', '09/01/2017', '07/31/2019');
Note: there is a missing quote at the end of the date on the second insert statement; I assume that this is a typo.

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.

SQL - Inserting into postgresql table produces error on semi-colon

I'm trying to insert some test data into a table to check the functionality of a web servlet, however, using pgAdmin4 to do the insert, I am running into an issue I'm not sure how to rectify. What I want to see is the last value (an image byte stream) is null for this test info. Here is my insert statement:
INSERT INTO schema.tablename("Test Title", "Test Content", "OldWhovian", "2016-07-29 09:13:00", "1469808871694", "null");
I get back:
ERROR: syntax error at or near ";"
LINE 1: ...ldWhovian", "2016-07-29 09:13:00", "1469808871694", "null");
^
********** Error **********
ERROR: syntax error at or near ";"
SQL state: 42601
Character: 122
I've tried removing the semi-colon just for kicks, and it instead errors on the close parenthesis. Is it an issue related to the null? I tried doing this without putting quotations around the null and I get back the same error but on the null instead of the semi-colon. Any help is appreciated, I am new to DBA/DBD related activities.
Related: Using PostgreSql 9.6
The insert statement usually has first part where you specify into which columns you want to insert and second part where you specify what values you want to insert.
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
You do not need to specify into which columns part only if you supply all values in the second part. If you have a table with seven columns you can omit the first part if in the second part you supply seven values.
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example:
drop table if exists my_table;
create table my_table (
id int not null,
username varchar(10) not null,
nockname varchar(10),
created timestamptz
);
INSERT INTO my_table (id, username) VALUES (1, 'user01');
You insert into columns id and username. The column created has default value specified so when you do not supply value in insert the default is used instead. Nickname and identification_number can accept null values. When no value is supplied NULL is used.
INSERT INTO my_table VALUES (2, 'user02', NULL, NULL, current_timestamp);
That is the same as the previous but here is omitted the fist part so you must supply values for all columns. If you did not you would get an error.
If you want insert multiple values you can use several statements.
INSERT INTO my_table (id, username, identification_number) VALUES (3, 'user03', 'BD5678');
INSERT INTO my_table (id, username, created) VALUES (4, 'user04', '2016-07-30 09:26:57');
Or you can use the postgres simplification for such inserts.
INSERT INTO my_table (id, username, nickname, identification_number) VALUES
(5, 'user05', 'fifth', 'SX59445'),
(6, 'user06', NULL, NULL),
(7, 'user07', NULL, 'AG1123');
At the beginning I have written that you can omit the first part (where you specify columns) only if you supply values for all columns in the second part. It is not completely true. In special cases when you have table that has nullable columns (columns that can contain NULL value) or you have specified DEFAUL values you can also omit the first part.
create sequence my_seq start 101;
create table my_table2 (
id int not null default nextval('my_seq'),
username varchar(10) not null default 'default',
nickname varchar(10),
identification_number varchar(10),
created timestamptz default current_timestamp
);
INSERT INTO my_table2 DEFAULT VALUES;
INSERT INTO my_table2 DEFAULT VALUES;
INSERT INTO my_table2 DEFAULT VALUES;
Result:
101 default NULL NULL 2016-07-30 10:28:27.797+02
102 default NULL NULL 2016-07-30 10:28:27.797+02
103 default NULL NULL 2016-07-30 10:28:27.797+02
When you do not specify values defaults are used or null. In the example above the id column has default value from sequence, username has default string "default", nickname and identification_number are null if not specified and created has default value current timestamp.
More information:
PostgreSQL INSERT

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.

SET datatype set in SQL Server

While creating a table I have to use the datatype SET, but it looks like there is no datatype SET in SQL Server. I was looking on the Microsoft's website and those are the datatypes that it supports: http://msdn.microsoft.com/en-us/library/ms187752.aspx
Which one should I use to replace the SET?
I have used SET in MySQL database like this:
CREATE TABLE IF NOT EXISTS `configurations` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`configDuration` int(5) NOT NULL,
`configDurationPerspective` set('list_this_day','list_remaining') NOT NULL,
PRIMARY KEY (`index`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And then when I insert data into the table it looks like this:
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_this_day');
Never mind the quotes. Something messed up while pasting the code.
Now I want to do the same thing, but in SQL Server.
You'd either have to use separate bit fields (one column with bit datatype per value) or you'd pack the values into a column with a integer datatype. If you'd use integer you'd have to use t-sql bitwise operators to read and write the values.
If you use bitwise operators you'll only get one column
The create table statement should look like this:
CREATE TABLE configurations(
[index] int NOT NULL IDENTITY (1,1) PRIMARY KEY,
user_id int NOT NULL,
configDuration int NOT NULL,
configDurationPerspective int NOT NULL,
)
And then you'd have to insert values that are possible to bitmask like 1,2,4,8,16,32 into configDurationPerspective
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_this_day');
would translate to
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 1);
And
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_remaining');
would translate to
INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 2);
and selecting could look like:
select [index], configDuration,
case when configDurationPerspective & 1 > 0 then 'list_this_day' else '' end
+ case when configDurationPerspective & 2 > 0 then 'list_remaining' else '' end as configDurationPerspective
from configurations
The list of basic types in MS SQL Server does not support the same. But what we have are constraints and user types. In this question you can see how MySQL enum is solved
SQL Server equivalent to MySQL enum data type?
And you can also observe user types (I've seen that they were used for the similar purpose)
http://msdn.microsoft.com/en-us/library/ms175007.aspx
But as the most typical solution to this issue, we were (on our projects) using some "CodeList/StaticList" table and referencing it by Primary key (int, shortint, tinyint)