inserting into new added columns in an existing table - mysql

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.

Related

Can't set default value for column

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.

Mysql default value for new records only

Is it possible to set a default value for new records only in a mysql column?
I want all rows before today to be null if nothing has been entered, but any new rows added after today to be a specific string if nothing has be entered for that column.
Is this possible?
Search in all rows in the table and check if the specific column is empty, if yes set it to null.
UPDATE tablename SET column = CASE column WHEN '' THEN NULL ELSE column END
For future entries you can add to your table a Default Constraint like this:
ALTER TABLE tablename ALTER column SET DEFAULT 'specific string'
This is an old post but I do think this answer might help other folks.
ALTER TABLE object_table_name ADD `value` INT NULL;
ALTER TABLE object_table_name MODIFY COLUMN `value` INT DEFAULT 0;
Doing it this way will only impact newly inserted records, this code did not work for me
ALTER TABLE object_table_name ADD `value` INT DEFAULT 0
I'm using MySQL 5.6

What should be the query to set an attribute of 'NOT NULL' on a column in MySQL database?

I've a table titled 'user' in MySQL database.
It has a field titled 'full_name'(varchar(255)). I want to set 'NOT NULL' attribute to this column and update the column with value 'Dummy User' where 'full_name' column contains blank value.
So my question is how should I achieve both these things in one single update query?
The query I tried is as below but it gave me error:
ALTER TABLE `user` MODIFY COLUMN full_name NOT NULL DEFAULT 'Dummy User' WHERE full_name = '';
Please somebody help me.
As the noble #jens pointed out in his comment, there is no way to alter the type of the full_name column to NOT NULL and also replace the empty strings with a default value in a single query.
The first query below changes the full_name column type to NOT NULL and sets the default column value to Dummy User. It also will replace all already-existing NULL entries with your desired default value. We are halfway done. To cover the records which have empty string, I use a simple UPDATE statement.
ALTER TABLE users
MODIFY COLUMN full_name VARCHAR(255) NOT NULL DEFAULT 'Dummy User';
UPDATE users
SET full_name = 'Dummy User'
WHERE full_name = ''

Not null confusion

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.

how to pass a null value to a foreign key field?

I have 2 tables:
university:
university_id(p.k) | university_name
and user:
uid | name | university_id(f.k)
How to keep university_id NULL in user table?
I am writting only 1 query, my query is:
INSERT INTO user (name, university_id) VALUES ($name, $university_id);
Here $university_id can be null from front end.
university table will be set bydefault by me.
In the front end, student will select the university name, according to that the university_id will pass to user table, but if student is not selecting any university name then is should pass null value to the user table for university_id field.
Just allow column university_id of table user to allow NULL value so you can save nulls.
CREATE TABLE user
(
uid INT NOT NULL,
Name VARCHAR(30) NOT NULL,
university_ID INT NULL, -- <<== this will allow field to accept NULL
CONSTRAINT user_fk FOREIGN KEY (university_ID)
REFERENCES university(university_ID)
)
UPDATE 1
based on your comment, you should be inserting NULL and not ''.
insert into user (name,university_id) values ('harjeet', NULL)
UPDATE 2
$university_id = !empty($university_id) ? "'$university_id'" : "NULL";
insert into user (name,university_id) values ('harjeet', $university_id);
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Here suppose i have foreign key user_id and i want to insert null value for that.
Checkbox must be checked for insert null value for foreign key.
I was using MySQL InnoDB and even allowing NULL in the FK column and using NULL as default I was getting an error.
So I used the SET syntax:
INSERT INTO (table) SET value1=X...
And I just don't set the FK column.