I can't set default value for for column in my table. I see lot of many example, but i can't resolve my issue. I have table with two columns: id, name. I'm need, if id == null, then set default value.
ALTER TABLE my_table ALTER id SET DEFAULT nextval('val_seq')
INSERT INTO my_table (id, name) VALUES (null, 'test_name')
I receive error: null value in column "id" violates not-null constant. How fixed this?
Just try not to include the column that you want to use the default value for in your insert statement.
INSERT INTO my_table (name) VALUES ('test_name')
The default constraint will provide a default value for a column IF no other value is specified.
Related
I have initialized a database users like this create table users (id not null auto_increment primary key, first_name varchar(256) not null, last_name varchar(256) not null);
However, I can just execute insert into users values (2,'James','Bond'); and no error is thrown. I want to create a table so that the primary key gets auto incremented and one can simply add entries like so: insert into users values ("firstname","lastname"); is this even possible?
When you use the syntax insert into users values ('firstname','lastname'); i.e. you do not specify a list of columns, this implies your VALUES clause will contain values for all columns. This is not related to using auto_increment, it applies to any table.
You can work around this by specifying the columns:
insert into users (firstname, lastname) values ('firstname','lastname');
By omitting id from the list of columns, it should also be omitted from the VALUES clause.
Another form of INSERT syntax supported by MySQL (although it's nonstandard) might be more clear. It also allows you to omit columns you don't want to set in your INSERT statement.
insert into users SET firstname='firstname', lastname='lastname;
If you do include the id column either implicitly or explicitly, you can trigger the auto-increment behavior by using NULL, DEFAULT, or if the sql mode permits it, 0.
If you specify any other value for the id, it overrides the auto-increment.
This is all documented here: https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html and related pages linked by that page.
you can name the columns that you want to insert.
But if you have more t columns , you have to define DEFAULT values, so that Mysql knows how to fill the not inserted values
INSERT INTO users (first_name ,last_name ) VALUEs("firstname","lastname");
The fact a column is auto-incrementing doesn't mean you can just ignore it in an insert statement. You could, however, avoid assigning a value to it and letting the auto_increment property handle it by using the default keyword:
insert into users values (default, 'firstname', 'lastname');
I've a table item that has some columns that are nullable.
To one of them type, I'd like to automatically insert a default value (instead of a NULL) whenever a new record in inserted in the table and do not specify a value for that column.
Can it be done without affecting the existing data?
The type column is a varchar.
I can update the current nulls.
You can try to ALTER column set a default value.
ALTER TABLE `T` MODIFY `type` varchar(50) DEFAULT 'default';
then insert by DEFAULT keyword:
INSERT INTO T (type) VALUES (DEFAULT);
Results:
This query will work for you.
For update table.
ALTER TABLE `column_name` CHANGE `tab` `my_id` INT(11) NOT NULL DEFAULT '0';
For insert table
CREATE TABLE `db_name`.`Tbale_name` ( `demo` INT NOT NULL DEFAULT '0');
In phpMyAdmin, as we create table there is not null constraints by default for all fields...and as per my knowledge when we set the constraint to not null...it doesn't allow user to remain field empty which are not null as per this link.....
http://www.techopedia.com/definition/27370/not-null-constraint
now my question is..according to this link, not null means every row of data must contain a value - it cannot be left blank during insert or update operations.....but when i insert data programatically like insert into, i am able to insert data in just two fields and other remains blank although there is not null constraints on that fields ...and still not generates any error....so i don't understand how not null works???
for example, i create table with lets say 5 fields...
create table myTable
(
Column1 int not null,
Column2 int not null,
Column3 int not null,
Column4 int not null,
Column5 int not null,
)
and insert values in just two fields like
"INSERT INTO myTable (column1,column2) VALUES(10,20)";
but other fields i don't give any '' so it takes 0 as value....and still i am able to insert data with no error...how is that possible??
Everything that has the NOT NULL constraint set needs to contain data. If you insert data programmatically and you do not insert data for a NOT NULL cell, then you will get an SQL Error.
e.g. you have this table:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL,
some_other_value INTEGER);
Then some_value will contain data in every data set returned, some_other_value may or may not contain data in every data set returned. The only thing to work around this would be this:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL DEFAULT 0,
some_other_value INTEGER);
If you now set data programatically and do not set data for some_value, some_value will default to 0 (or to whatever data you set the default to on table creation).
Maybe you can refer to this link:
For multiple-row INSERT statements or INSERT INTO ... SELECT
statements, the column is set to the implicit default value for the
column data type. This is 0 for numeric types, the empty string ('')
for string types, and the “zero” value for date and time types. INSERT
INTO ... SELECT statements are handled the same way as multiple-row
inserts because the server does not examine the result set from the
SELECT to see whether it returns a single row. (For a single-row
INSERT, no warning occurs when NULL is inserted into a NOT NULL
column. Instead, the statement fails with an error.)
If a column definition includes no explicit DEFAULT value and it is defined as "Not Null" then Mysql will automatically assign default value to the column based on datatype. e.g. 0 for integer and "" for varchar
If you create a unique index on a column, the default value will be accepted with the first row but will give an error with subsequent inserts.
I have a table 'user' already in db with fields
create Table user (
id INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(20) NOT NULL,
password varchar(20) NOT NULL,
profilename varchar(20) NOT NULL,
email varchar(40) NOT NULL,
socialemail varchar(40) NOT NULL)engine=InnoDB;
The stated columns also contain values
I altered the table and added some more columns
ALTER TABLE user
ADD COLUMN enabled varchar(1),
ADD COLUMN accountnonexpired varchar(1),
ADD COLUMN credentialsnonexpired varchar(1),
ADD COLUMN accountnonlocked varchar(1);
Now when I am inserting values into new columns with the below command in MYSQL.
insert into user
(id,enabled,accountnonexpired,credentialsnonexpired,accountnonlocked) values ('1','Y','Y','Y','Y'),('2','Y','Y','Y','Y');
I am getting an error
Error Code: 1364. Field 'username' doesn't have a default value
Can anyone tell me why?
What should be the correct way to insert values in new columns?
INSERT adds new rows to your table, and those rows would have to have a non-null username for the INSERT to succeed It's not 100% clear but I think you are saying that you want to set the values of these new columns for all your existing rows. To do that you need UPDATE not INSERT:
UPDATE user SET id='1', enabled = 'Y', accountnonexpired = 'Y' WHERE 1
I omitted a few of your columns for brevity but you get the idea. You may also want to alter the table to make these values the DEFAULT for new rows inserted in the future.
Your table has NOT NULL set for the [username], [password], [profilename], [email] and [socialemail] fields. You will need to provide values while NOT NULL has been set and there is no default value.
Unless your intention is to insert data into pre-existing columns, then use the Update statement.
update user
set enabled = 'Y', accountnonexpired='Y', credentialsnonexpired='Y', accountnonlocked='Y'
from user
where id = 1
An INSERT is creating NEW records. You have a username field that is marked as NOT NULL But in your sql you are not including username and other NOT NULL fields in your statement.
Your insert would need to include all the NOT NULL fields.
insert into user(id,username,password,profilename,email,socialemail,enabled,accountnonexpired,credentialsnonexpired,accountnonlocked)
values ('1',<username>,<password>,<profilename>,<email>,<socialemail>'Y','Y','Y','Y'),('2',<username>,<password>,<profilename>,<email>,<socialemail>'Y','Y','Y','Y');
I suspect you actually want to UPDATE here instead of insert.
An update would look like this:
UPDATE user set enabled = 'Y', accountnonexpired='Y', credentialsnonexpired='Y', accountnonlocked='Y'
FROM user
WHERE id = 1
Give value for 'username' field. it has no default value and default is not null as per your table definition. This will work
In your insert procedure, there is no value assigned for username field, Since username varchar(20) is NOT NULLable, you need to set a default value for that col or alter the col property to accept null values.
Will ignoring the value AUTO_INCREMENT in my table SQL have an effect on my current content?
No, it won't.
15char
no..it won't effect anything..
AUTO_INCREMENT function is for make array number..it make all data which have been input automatically sequential..and also counting..from 1,2,3,..n..
No, it won't. An AUTO_INCREMENT will keep a counter so that you can INSERT a row without specifying a value for that column.
If you ignore the AUTO_INCREMENT and do explicitly state a value for the column, the counter will be updated. The next insert without explicit value will take the previous insert into account - you don't risk a duplicate value.
Testcase:
Create the table:
CREATE TABLE `counter` (
`1` int(11) NOT NULL auto_increment,
PRIMARY KEY (`1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;
Insert a row, without stating the value:
INSERT INTO `test`.`counter` (`1` ) VALUES (NULL);
There will now be one row, with value 1.
Insert another row, without stating the value:
INSERT INTO `test`.`counter` (`1` ) VALUES (NULL);
There will now be two rows, 1 and 2.
Insert a row while explicitly stating the value:
INSERT INTO `test`.`counter` (`1` ) VALUES ('8');
You will now have three rows, 1, 2, 8
Now insert another row without stating the value:
INSERT INTO `test`.`counter` (`1` ) VALUES (NULL);
The new row will not have value 3 or 4, but the correct value 9:
SELECT * FROM `counter`;
1
2
8
9