MySQL Integer column, unique values but default possibility? - mysql

I want a table with an integer column, that may or may not be filled (it is a social security number). But if it is filled, I want it to be UNIQUE : there cannot be two entries of the same number.
Using a unique constraint won't work cause integer won't accept NULL values, and MySQL detects multiple 0 values.
How can I set a unique constraint on an integer with a default value ? Or how can I set the integer column to accept NULL values ? (this question takes it for granted : MySQL Foreign Key Constraint - Integer Column but I can't)

create table test (
myint INT NULL, UNIQUE INDEX (myint)
);
This will allow a unique constraint on any integers added but will allow multiple NULL values to be entered.
MySQL treats NULL as 'unknown' value so cant possibly do a comparison to see if a like value is already there 'unknown' !== 'unknown'.
This also depends on which database engine you are using, the above holds true for MyISAM and InnoDB

Please see the code below:
ALTER TABLE test MODIFY myint INT NULL
ALTER TABLE test ADD UNIQUE INDEX (myint)
It works when data inputs are directly from MySQL (PHPMyadmin), saved as NULL, but a php script saves it as zeroes, and so it does not allow multiple entries.

Related

Inserting new data in mysql after creating new field

How can I insert new data in column after adding column without using update function. for example
"alter table Employee add column Gender varchar(1) after Birthdate then I get wrong when I used this statement insert into Employee(ENumber,EmpName,Birthdate,Address,Salary,DNumber,Gender)
-> values
-> ('E001','GSInocencio','1988-01-15','Munoz',18000,'D005','F'),
It gives me error Duplicate entry 'E001' for key 'PRIMARY'
MariaDB [Employees_Valdez]>
The messages is pretty clear: You already have an employee with that ENumber value.
You have a UNIQUE constraint on that column, it's a PRIMARY KEY, so either pick a different value, or use a different primary key.
One thing to note is MySQL doesn't use complex string primary keys very efficiently, they're also a real hassle for relating data since they're so big. It's usually better to include a standard id INT AUTO_INCREMENT PRIMARY KEY column and then have things like ENumber being a secondary UNIQUE constraint.
You can then relate data using the 4-byte id value, or 8-byte if BIGINT is a concern like you might have two billion employees.

Unique VARCHAR(65535) field per <ID> in MySQL

Are there solutions to maintain a VARCHAR(65535) field unique per ID in MySQL?
I would use a hashing function on field's value and store it in a separate unique field on the same table.
So your table would be something like this:
create table my_table (
id integer not null primary key,
text_content varchar(65535) not null,
text_hash varchar(128) not null unique
);
When inserting on that table, you will compute sha256 hash for text_content field and store it in text_hash field. That way you can be pretty sure text_content values are unique on your table.
If you like DB SIDE programming, you can put this logic on a trigger provided MySQL supports them.

MYSQL table column contraint based upon another tables columns

This is my first post and I'm a mysql noob, so I apologize for this question's length.
BACKGROUND
I have a lookup table cctypevals, with a foreign field 'cctypeID', in mysql this would be:
CREATE TABLE `cctypevals` (
`cctypevalsKEY` integer NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`cctypeID` varchar(50) NOT NULL, FOREIGN KEY(cctypeID) REFERENCES cctype(cctypeID) ,
`value` varchar(50) )
cctypeID contains field names from user tables, eg 'taskSTATE', 'serviceTYPE', 'projectCAT' etc.
The value field contains the only allowed values for these user table fields.
Thus cctypevals acts like a 'multi' keyed lookup table, for example:
select value from cctypevals where cctypeID ='serviceTYPE'
might return HomeVisit, BackToBase etc
I know it would be easier to have one lookup table per field but this is what I have.
QUESTION
How do I constrain (in a sql create table or alter statement), tables with fields like task.taskSTATE, service.serviceTYPE etc so they can only accept values from cctypevals.value where cctypeID contains the appropriate field name ?
In create or alter table statement you cannot do that, since the check constraint would be able to such things, but mysql has not implemented the check constraint yet (mysql can parse a check constraint, but it will not work).
You can create before insert and update triggers that check the specific restrictions and raise an sql error message if the updated value does not meet the requirements.

Does Adding a Primary Key to a table checks default columns?

I tried to add primary key in a table and set it as a column that has default value and is not null and is not unique.MySQL accepted that column as Primary Key...I want to know that this is wrong as if a user enters 2 records having default values he will not be able to do so..Is this a problem where SQL should have checked column as non default values or this is a designer end problem that default columns should not be made Primary Key...?
I'm not fully understanding the problem. You have declared a column to be a primary key that has these characteristics:
NOT NULL
Default value
A primary key imposes these characteristics:
NOT NULL
Unique
These characteristics are not mutually incompatible. The only issue is that the default value can only be assigned once in the column. The second time you try to insert a row with the default value, you will get a violation of the uniqueness constraint.
In other words, MySQL (and I think other databases as well) allow you declare this even if it doesn't seem like a good idea.
Null:
every column that is flagged wiht NULL is just specified that this column may contain a NULL value. The column can still have another default value.
Primary key:
A PK is always treated unique and you cannot have two identical values on a row
There can only be one PK per table, its the main index which is very fast when querying the table on its primary column.
A PK is always a single column and cannot be spread over multiple columns as every other index (unique or usual index) can do.
A PK column cannot accept NULL values
Sample:
ID (INT, PK) | Name (varchar)
1 | Foo ->Valid
2 | Bar ->Valid
2 | FooBar ->Invalid (Duplicate Primary key value ID)
Conclusion: Yes MySQL should and will throw an error at second attempt to put a default value because its simply treated UNIQUE and a given default value is const. The MySQL server will attempt to insert the default value when you dont specify any value for this column in your insert statement.
Pretty much means: A PrimaryKey column with a default value makes no sense, except you use an auto-increment which is a pseudo "default value" which is different each time you try to insert something.
I hope this answers your questions

MySQL - How to create an auto increement field in the DB?

I am entering records in the MySQL DB. Now I want to have a "Serial_Number" field that increements automatically whenever a record is entered into the DB.
I don't want this "Serial_Number" field to be the primary key of the DB.
How can I create this field (with the attributes needed to be set).
I am using "SQL YOG" to access MySQL. If you are aware of the SQL YOG then tell me how to do that through SQL YOG.
The AUTO_INCREMENT column has to have a UNIQUE KEY constraint associated to it.
For instance, this will work just fine:
CREATE TABLE AutoNotId
(
Id INTEGER PRIMARY KEY,
Auto INTEGER AUTO_INCREMENT,
UNIQUE (Auto)
);
Edit:
The ALTER statement would look somewhat like this:
ALTER TABLE AutoNotId
MODIFY COLUMN Auto INTEGER AUTO_INCREMENT,
ADD UNIQUE (Auto);
I recommended, however the use of the long-hand syntax to specify the name of the UNIQUE constraint; But you can always refer to MySQL's Reference Manual for the exact specifications.
In MySQL tables can only have one auto increment field and they must be indexed.
There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value.
Is there a reason you don't want it to be the primary key?
If you want an incrementing value, you could fudge it by running updates after each insert:
SELECT MAX(serial) + 1 FROM myTable;
UPDATE myTable SET serial = <that number> WHERE id = ...
I don't think you can have an auto increment field:
CREATE TABLE `t` (`dd` int(11) NOT NULL)
ALTER TABLE `t` CHANGE `dd` `dd` INT( 11 ) NOT NULL AUTO_INCREMENT
MySQL said: Documentation
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
You cannot do this in MySQL. From the doc:
There can be only one AUTO_INCREMENT
column per table, it must be indexed,
and it cannot have a DEFAULT value. An
AUTO_INCREMENT column works properly
only if it contains only positive
values. Inserting a negative number is
regarded as inserting a very large
positive number. This is done to avoid
precision problems when numbers “wrap”
over from positive to negative and
also to ensure that you do not
accidentally get an AUTO_INCREMENT
column that contains 0.
For MyISAM and BDB tables, you can
specify an AUTO_INCREMENT secondary
column in a multiple-column key. See
Section 3.6.9, “Using AUTO_INCREMENT”.
create table mytable (
ID INT IDENTITY(1,1) PRIMARY KEY,
SN INT IDENTITY(1,1)
)