mySQL adding column with NULL values - mysql

I am using mySQL and am trying to get my head around the difference between NULL and empty. If I add a column to my table using...
alter table data add result VARCHAR(4);
Then every field in the column is automatically populated with NULL.
Does this take up any more space than an empty field? How could I add that column with blank values instead?

You can use default, if you don;t like nulls, but Null is more descriptive:
alter table data add result VARCHAR(4) DEFAULT ''
Generally you should be using null, as it means -none has set a value to this column.
As for the space I am not aware is MySQL is treating empty values, but I assume that NULL takes less space, because NULL is generally a singleton in most languages.

Related

Making value required in insert Statement

I want to make ItemCode value in my table required when using the insert statement, I thought of using a NOT NULL constraint but I do not know if that is correct. Here is the structure of my table
CREATE TABLE Item
(
ID INT auto_increment,
ItemCode VARCHAR(10) unique NOT NULL,
ItemDescription VARCHAR(50),
Price DECIMAL(4,2) DEFAULT 0,
PRIMARY KEY(ID)
);
Using not null will only enforce a value for this field when the record is saved to the database. If the user enters a string of spaces, it will still get saved. You need to put data validation rules in the front end of your application.
By default, columns in SQL accept NULL values. And, if a value is not provided in an INSERT, then the default is NULL.
When you declare a DEFAULT value ("constraint") for a column, then you can change the value that is inserted, when no value is provided. You haven't declared a DEFAULT, so NULL is used.
Then, NOT NULL prevents a NULL value from being inserted. So, if no value is provided, a DEFAULT value will be used. However, with no DEFAULT an error will occur -- violating the NOT NULL constraint.
In short, your definition does what you want.
Note: Triggers can affect this functionality, so the above assumes that triggers do not use the value in that column.

Do I need to put NOT NULL when using AUTO_INCREMENT in SQL?

I'm implementing a DB for a project I'm doing in my research and, after using some AUTO_INCREMENTS I got curious... Once the AUTO_INCREMENT is already automatically inserting a value in the column, why do we need to put the NOT NULL together?
Example:
user_id INT NOT NULL AUTO_INCREMENT
Thanks.
You don't have to specify NOT NULL on the column definition with AUTO_INCREMENT.
You can leave it off, and MySQL will make the column NOT NULL.
And if you specify NULL in place of NOT NULL, MySQL will accept the syntax, but it will ignore that, and make the column NOT NULL anyway.

How to add a not null constraint to an already existing column with null values?

I've seen a similar question on stackexchange, but it's answer did not give me the correct results.
For demonstration purposes, I have a simple table PURCHASES with columns PURCHASE_NUM, PURCHASE_DATE, CUSTOMER_ID. I want to enforce a not null constraint on the CUSTOMER_ID table. I tried the following:
ALTER TABLE PURCHASES MODIFY CUSTOMER_ID char NOT NULL;
That syntax is fine, but then I insert with the following: INSERT INTO PURCHASES VALUES (333, NULL, NULL); and the tuple is added without issue. Why is the constraint not being enforced? Would having NULL values already in that column before adding the constraint affect things?
Thanks
edit DESCRIBE PURCHASES; says the following for the column of interest:
Field, Type, Null, Key, Default, Extra
CUSTOMER_ID, char(5), YES, , NULL,
Your ALTER command didn't work, the Null column still says YES. Your ALTER command syntax looks just fine, it should have worked. Check your typing and try again.
Is your customer ID really just a char?
Maybe you have to change to
ALTER TABLE PURCHASES MODIFY CUSTOMER_ID char NOT NULL;
According to the manual, data entry into a NOT NULL column that has no explicit DEFAULT clause will set the column to NULL. Thus, you should ALTER your column to contain a DEFAULT. From 4.0 documentation:
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.
For date and time types other than TIMESTAMP, the default is the appropriate “zero” value for the type. For the first TIMESTAMP column in a table, the default value is the current date and time. See Section 10.3, “Date and Time Types”.
For string types other than ENUM, the default value is the empty string. For ENUM, the default is the first enumeration value.

Add the NOT NULL constraint to a column

I'm using PHPMyAdmin and I try to add the NOT NULL constraint to a column of my table.
PHPMyAdmin accepts my following query :
ALTER TABLE `wall` MODIFY `token_message` varchar(40) NOT NULL;
But I can still insert empty strings (=NULL), I don't understand why.
PS : If you're going to give me some other queries to add this constraint, note I've have tried these 3 which don't work in my PHPMyAdmin (kind of error : #1064 - You have an error in your SQL syntax; check the manual) :
ALTER TABLE `wall` ALTER COLUMN `token_message` SET NOT NULL;
ALTER TABLE `wall` ALTER COLUMN `token_message` varchar(40) NOT NULL;
ALTER TABLE `wall` MODIFY `token_message` CONSTRAINTS token_message_not_null NOT NULL;
You wrote, "I can still insert empty strings (=NULL)," which sounds like a misunderstanding. In SQL, an empty string does not evaluate to NULL, or vice versa. Try inserting an empty string and doing SELECT from wall where token_message is NULL. You should get zero rows back. Then try doing an insert where you specify NULL (unquoted) as the value for your column, and you should get the expected error message.
If those tests work as expected, then everything is fine, and your problem is actually that you want to prevent blank strings from being inserted. Check out this question for suggestions, or just check for blank strings during validation, before the query.
MySQL's column alter syntax requires you to completely re-specify the column. You can't just change one attribute of a column, you have to re-define it completely:
ALTER TABLE wall MODIFY token_message varchar(40) NOT NULL default ''
The only 'SET' version allowed is to change the default value.
ref: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
I think this is a matter of scrubbing your inputs. As octern mentioned, an empty string ('') is not a NULL value in sql. The best way to handle this is to only allow updates through a store procedure which strips out empty strings, even space characters:
CREATE PROC InsertIntoMyDb (#MyVarChar VARCHAR(2000)) AS
SET #MyVarChar = NULLIF(RTRIM(LTRIM(#MyVarChar)), '')
INSERT INTO [TBL] (MyVarChar)
VALUES #MyVarChar
This will truncate any number of spaces to an empty string, turn an empty string into a NULL, and then it will not allow the NULL value to be inserted based on the constraint you already have in place.
Try to use this query
Alter table table_name
change column_name column_name datatype(length) definition
ie,
Alter table wall
change tocken_message tocken_message varchar(40) NOT NULL DEFAULT

What is the default value for a field if no default value is provided?

I hope this isn't a dumb question. You can set a default value for all variables or a function for when it is inserted. but if the field is not required to insert and you don't allow null values, what is the "blank" value that you see in phpMyAdmin? in a query is it returned as empty string, etc?
just trying to figure it out, I want to query for all records such that the value for a specific column in that record is not "empty" or blank or whatever.
thanks.
Referring to the manual,
For data entry for a NOT NULL column that has no explicit DEFAULT
clause, if an INSERT or REPLACE statement includes no value for the
column, or an UPDATE statement sets the column to NULL, MySQL handles
the column according to the SQL mode in effect at the time:
If strict SQL mode is not enabled, MySQL sets the column to the implicit default value for the column data type.
If strict mode is enabled, an error occurs for transactional tables and the statement is rolled back. For nontransactional tables, an
error occurs, but if this happens for the second or subsequent row of
a multiple-row statement, the preceding rows will have been inserted.
So your question now may be, what are the implicit default values for the various column data types? Here you go:
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.
For date and time types other than TIMESTAMP, the default is the appropriate “zero” value for the type. For the first TIMESTAMP column
in a table, the default value is the current date and time. See Section 10.3, “Date and Time Types”.
For string types other than ENUM, the default value is the empty string. For ENUM, the default is the first enumeration value.
There IS no default value unless you specify one (i.e. unless you define a "default constraint" for the column in question).
Here's an example for adding a default on an existing column:
ALTER TABLE dbo.customer ALTER COLUMN contactname SET DEFAULT 'Unknown'
Here's an example creating the table with a default:
CREATE TABLE Books (
ID SMALLINT NOT NULL,
Name VARCHAR(40) NOT NULL,
PubID SMALLINT NOT NULL DEFAULT 0
)
It's good practice to declare ALL columns "not null", and provide default constraints as appropriate.
In the "books" example above, if you "insert" without specifying PubID, the PubID will be zero.
In the same example, if you "insert" without specifying ID or Name ... you'll get an error.
If you want MySQL to auto-assign an ID, use this syntax instead:
CREATE TABLE Books (
ID SMALLINT NOT NULL AUTO_INCREMENT,
Name VARCHAR(40) NOT NULL,
PubID SMALLINT NOT NULL DEFAULT 0
)
If you want to disallow null :-
alter table YOUR_TABLE modify column COLUMN varchar(255) not null default '';
The above query will disallow null and assign an empty string when the value is not supplied.
In phpmysqladmin, blank = empty.
Via PHP mysqli function or mysql function, null value is returned as null still.
Once you have apply the query, you can easily filter that by using
select ... from YOUR_TABLE
where COLUMN != ""; <-- no need to check is null
<-- because the first query already enforce not null
However, is best for you do this before perform the alter :-
update YOUR_TABLE set COLUMN = ""
where COLUMN is null;