I have the following table:
CREATE TABLE `events` (
`evt_id` int(11) NOT NULL AUTO_INCREMENT,
`evt_name` varchar(50) NOT NULL,
`evt_description` varchar(100) DEFAULT NULL,
`evt_startdate` date NOT NULL,
`evt_enddate` date DEFAULT NULL,
`evt_starttime` time DEFAULT NULL,
`evt_endtime` time DEFAULT NULL,
`evt_amtpersons` int(11) DEFAULT NULL,
`sts_id` int(11) NOT NULL,
`adr_id` int(11) DEFAULT NULL,
`evt_amtPersonsSubs` int(11) DEFAULT NULL,
`evt_photo` varchar(50) DEFAULT NULL,
`sys-mut-dt` timestamp NULL DEFAULT NULL,
`sys-mut-user` varchar(20) DEFAULT NULL,
`sys-mut-id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`evt_id`),
KEY `sts_id` (`sts_id`),
KEY `adr_id` (`adr_id`),
CONSTRAINT `sts_id` FOREIGN KEY (`sts_id`) REFERENCES `statusses` (`sts_id`) O
N DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1
Now I have got two problems:
Here is my query:
INSERT INTO `events`(`evt_name` , `evt_description` , `evt_startdate` , `evt_enddate` , `evt_starttime` , `evt_endtime` , `evt_amtpersons` , `sts_id` , `adr_id` , `evt_amtPersonsSubs` , `evt_photo` , `sys-mut-user` , `sys-mut-id`) VALUES ('asf' , 'asf' , '2009-04-02' , '2009-04-22' , '00:00:00' , '00:00:00' , '3' , '1' , '' , '' , '' , 'test' , '1')
When I execute this query through my php programs I get no error. But when I execute the query in a shell directly on the mysql database I get two warnings. How can I get PHP to alert me when there are warnings because if there are warnings mysql doesn't do the insert.
About the warnings:
| Warning | 1366 | Incorrect integer value: '' for column 'adr_id' at row 1
| Warning | 1366 | Incorrect integer value: '' for column 'evt_amtPersonsSubs' a t row 1
How can I get rid of these warnings. Tried to make some changes but it didn't work out so far.
You are inserting an empty string. You should remove the '' and put a number in that field
As you said, the column does not have to have a value specified when you insert. The fact is indicated by the "DEFAULT NULL" for that column at table creation. This fact, however, means that if you do not specify the column name in your list of columns while doing INSERT (and therefore you will not specify the corresponding value either), then the tuple can be inserted anyway, and for that column value you will get a NULL automagically by default.
However, in your query you specify that you are going to insert that column value, and the column value you say is '' (an empty string). This is of course not valid, because that column accepts integers (or NULL, because you havent' declared the column NOT NULL), and an empty string is an empty string, not an integer.
The SQL server is generous and accepts the empty string anyway (probably it casts it to zero) but reports you a warning. If you set a strict mode for the server (something I strongly suggest you to do), you will get an error and the insert will fail.
Please note that if you follow my suggestion of setting strict mode, this is server wide, involving all your databases and all your tables (at least with the mysql released one year ago). If you have awfully written software that need a forgiving server, then you cannot use it.
The error message tells you that that the empty string ('') is not a valid value for an integer field - in this case the fields adr_id and evt_amtPersonsSubs. Did you mean to put NULL instead?
In PHP, you can retrieve the error or warning message, for the most recent query only, using the mysql_error() function.
'' is not an integer.... how about using NULL in the query if you actually want a null value?
The warnings tell you that you're trying to insert a string value into an integer column.
In all the places where you have an int column you must not put the value between ' but just put the value as is
[...]'00:00:00' , '00:00:00' , 3 , 1 , [...]
If you don't want to provide a value for a certain column you should define the column with NULL. Then you can even leave your '' for the insert.
BUT
In general it's bad practice to do inserts like that. What if you one day need to add a column to your table? Then you have to go and rewrite your code as well.
Therefore you should do inserts like that:
INSERT INTO tbl_name (col1, col2) VALUES(value1, value2);
This way your code will still work, even if you decide to add columns. Plus the code is easier to read!!
Implicit defaults are defined as follows:
For numeric types, the default is 0, with the exception that for integer or floating-point types declared with the AUTO_INCREMENT
attribute, the default is the next value in the sequence.
Reference:
MySQL 5.7 Reference Manual / Data Types / Data Type Default Values
Related
I faced a problem when inserting a NULL value into a column defined as NOT NULL WITH DEFAULT values.
In this example, I removed most of the columns for illustration purposes.
CREATE TABLE
FKTIM04
(
OBJECTID CHARACTER(32) NOT NULL,
UP_CHANGE_CL CHARACTER(1) DEFAULT '1' NOT NULL,
UP_CTRL_CL CHARACTER(1) DEFAULT '0' NOT NULL,
CONSTRAINT PK_FKTIM04 PRIMARY KEY (OBJECTID)
);
When I execute this SQL statement, there is an error:
INSERT INTO KTI.FKTIM04 (
UP_Change_CL
,UP_ctrl_CL
,ObjectID
)
VALUES (
NULL
,NULL
,'UMSTM0LW8A8Z50DT4WA7U93EEQDRXRTH'
)
Error:
[Code: -407, SQL State: 23502] Assignment of a NULL value to a NOT
NULL column "TBSPACEID=2, TABLEID=1298, COLNO=46" is not allowed..
SQLCODE=-407, SQLSTATE=23502, DRIVER=4.22.29
I know that the column is defined as NOT NULL. If it tries to insert a NULL into the column, shouldn't it take the DEFAULT value instead?
Please teach me how to get the DEFAULT values to be inserted instead.
What should I look out for?
Thank you.
The default value will be used for a column if a value is not supplied in the INSERT statement for this column.
So don't include the columns that you want to get their default values in the list like this:
INSERT INTO KTI.FKTIM04 (
ObjectID
)
VALUES (
'UMSTM0LW8A8Z50DT4WA7U93EEQDRXRTH'
)
this way the row will be inserted and the 2 columns, since they were not specified in the list, will get their default values.
See the demo.
Another way to achieve the same is by using DEFAULT keyword:
INSERT INTO FKTIM04 (
UP_Change_CL
,UP_ctrl_CL
,ObjectID
)
VALUES (
DEFAULT
,DEFAULT
,'UMSTM0LW8A8Z50DT4WA7U93EEQDRXRTH'
)
See the demo.
I have a task to build a table in SQL Server, the task is to have 2 football teams match.
but before starts and ends and then putting the values of the results (HostTeam) (AwayTeam) and (WinnerTeam), they have to be 0-0 at (HostTeam)(AwayTeam) columns and NULL on the (WinnerTeam) column.
"When adding a game record, the starting score should be 0-0 and the winner team name should be empty"
I don't want to to explicitly give you the answer because this seems like you're asking for the answer to a homework/quiz question. That being said, here is some help in the right direction.
You have 2 options, either write out the CREATE TABLE script yourself, or use the built in tools provided within SSMS. Either way, you will name your table, create your desired columns/fields, give those columns/fields a type, determine whether they are allowed to be empty or not (Nullable), and you can then set DEFAULT values (NULL, 0, etc.)
If you have any code showing your current attempt, please post that and we can go from there.
As you can see bellow you have some options about your default value.
AUTO_INCREMENT means x++
DEFAULT NULL means The default value of this column is null
NOT NULL DEFAULT '0' means The deafault Value is NOT NULL but 0 (you
can define it yourself)
CREATE TABLE test_user (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Id Auto_Increment Default Null',
name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'No_name' COMMENT 'Varchar Name
Default Value No_Name',
surname varchar(255) DEFAULT NULL COMMENT 'Varchar Name Default NULL',
num int(11) NOT NULL DEFAULT '0' COMMENT 'Default integer value 0',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I stumbled upon this definition:
CREATE TABLE dbo.whatever (
[flBlahBlah] BIT DEFAULT ((0)) NOT NULL,
[txCity] NVARCHAR (50) DEFAULT ('') NOT NULL,
[cdFrom] VARCHAR (10) DEFAULT ('') NOT NULL
);
I can't think of a reason to add those default values. Not null string is defaulted to '' and bit is defaulted to 0. Is there a reason for defining these default values? Am I missing something? Is this in some best practice handbook I'm not aware of?
I'd just use:
CREATE TABLE dbo.whatever (
[flBlahBlah] BIT NOT NULL,
[txCity] NVARCHAR (50) NOT NULL,
[cdFrom] VARCHAR (10) NOT NULL
);
The database is in MS SQL Server 2012, now migrating to Azure Database.
For example you create table from a first batch of your question. Then insert value like this
INSERT INTO dbo.whatever (flBlahBlah) VALUES (1)
You will get 1 row dbo.whatever
flBlahBlah txCity cdFrom
1
So if you "forget" to insert in one of the column with default values determined - SQL Server will take care of them.
It is very useful when you got table, in which you need to insert new field. With default value determined you don't need to change SP/query's/other stuff that works with this table.
The column name on table [dbo].[payment_info] must be changed from NULL to NOT NULL. If the table contains data, the ALTER script may not work.
To avoid this issue, you must add values to this column for all rows or mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
CREATE TABLE [dbo].[payment_info]
(
[name] VARCHAR (50) NOT NULL,
[card_no] VARCHAR (50) NULL,
[card_type] VARCHAR (50) NOT NULL,
[tel_no] VARCHAR (50) NULL,
[mob_no] VARCHAR (50) NULL,
[address] VARCHAR (MAX) NULL
);
I cannot change NULLto NOT NULL; when I update it's showing the above warning.
I am using visual studio 2013 asp.net and c#.
If table already exists and is fulfilled with data, you have to update all NULLs in column you want to change on some value which is not NULL. Then ALTER command should work wthout warnings and/or errors.
I am not really sure if I understood your problem correctly, but the warning says it all - you can't switch column to not nullable, if there are nulls already in the column.
You have to update and set some values to empty entries or set DEFAULT value
EDIT:
You should try first:
select *
from [dbo].[payment_info]
where name is null
and check if there are any problems
Right-click on your table in server explorer and click "new query". Type:
ALTER TABLE
table
ALTER COLUMN
column
int NOT NULL;
This error is produced by SSDT. This will happen if you have an existing table and you would like to add a new non-nullable column to it. In order to do so, you must have a default for this new column (the default can be some temporary value).
CREATE TABLE [dbo].[payment_info]
(
[WhateverColumn] VARCHAR (50) NOT NULL DEFAULT 'Foo',
-- and so on
);
If you want to change the default to a more meaningful value, you can write the script to update the table and set the column's value to a more meaningful value in a post deployment. In post deployment you can also now drop the default since it was temporary:
ALTER TABLE WhateverTable
ALTER COLUMN WhateverColumn DROP DEFAULT;
Now your deployment will succeed.
Note: If your column is a foreign-key column, the default has to exist in the parent table even if the value is temporary.
The ability and manner in which a table column may be specified with a default empty string appears to be RDBMS implementation dependent.
This answer (default a column with empty string) and this one (Avoid NULL columns using DEFAULT Empty String) indicate that a default empty string may be set with a CREATE TABLE column rule that uses an empty single-quoted literal with the DEFAULT constraint.
Here is a DDL excerpt that I have used in HSQLDB 2.2.9. I am executing SQL against the database with SQuirreL 3.4.0:
CREATE CACHED TABLE Clients (
cli_id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
mRN VARCHAR(24) NOT NULL UNIQUE,
lastName VARCHAR(48) NOT NULL,
midName VARCHAR(24),
firstName VARCHAR(24) DEFAULT '' NOT NULL,
);
lastName may not be NULL
midName has no column rules
firstName is not nullable and an attempt is made to have it default to an empty string by specifying an empty string literal as suggested by the previous answers.
When I use SQuirreL to make this table editable and then insert a row into the table, the following values appear in the columns:
lastName: (empty)
midName: <null>
firstName: ''
It seems that the semantics DEFAULT '' NOT NULL in HSQLDB cause the column to default to two single quotes and not to an empty string. When the column rule NOT NULL is used alone without a DEFAULT rule, it looks as though an empty string is reported by SQuirreL when a new row is inserted.
Can someone confirm that the correct way to have a VARCHAR column in HSQLDB default to a non-null, empty, zero-length string is to use these semantics:
CREATE CACHED TABLE Clients (
cli_id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
mRN VARCHAR(24) NOT NULL UNIQUE,
lastName VARCHAR(48) NOT NULL,
midName VARCHAR(24) NOT NULL,
firstName VARCHAR(24) NOT NULL,
);
Thanks :-)
The correct way is actually your original CREATE TABLE. If a column has no DEFAULT clause but has a NOT NULL constraint, then it has no default value and you must include a value for the column when you insert into the table.
It may be the SQuirreL client is using it's own convention for displaying or inserting the firstName column.
You can insert an incomplete row with an SQL statement, using the HSQLDB DatabaseManager:
INSERT INTO clients(mrn, lastname) VALUES 'mrn00', 'Aname'
And check the result with a SELECT:
SELECT * FROM clients
Which shows this when you switch to View->Results in Text
CLI_ID MRN LASTNAME MIDNAME FIRSTNAME
------ ----- -------- ------- ---------
0 mrn00 Aname (null)