I am trying to change an existing column in a table I have to allow for null values and then set the default value to null. I tried running the following but it does not seem to be updating the table:
mysql> ALTER TABLE answers_form MODIFY sub_id int unsigned NULL DEFAULT NULL;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc answers_form;
+--------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| answer_id | int(10) unsigned | NO | PRI | 0 | |
| sub_id | int(10) unsigned | NO | PRI | 0 | |
| form_id | int(10) unsigned | NO | PRI | NULL | |
| value | varchar(255) | NO | | NULL | |
| non_response | bit(1) | YES | | b'0' | |
+--------------+------------------+------+-----+---------+-------+
5 rows in set (0.01 sec)
Can anyone see what I am doing wrong here?
its a primary key , mysql doesn't allow any part of the primary key to be null, which does make the fact that it allows a default value of null for the form_id odd, however the docs at
http://dev.mysql.com/doc/refman/5.5/en/optimizing-primary-keys.html
say "Query performance benefits from the NOT NULL optimization, because it cannot include any NULL values".
Just out of curiosity, does it actually allow you to put in null values in the form_id field?
You have 2 non-nullable columns with the default value of null. This shouldn't be allowed by your database engine. If it is, it is rather far from a best practice.
sub_id is listed as a primary key
From the MySQL docs (5.7, but other versions say the same thing):
A PRIMARY KEY is a unique index where all key columns must be defined
as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL
declares them so implicitly (and silently).
As to the discussion about the Non-null columns having a Default of NULL...
The NULL value in the Default column means that there is no default, not that the default is NULL.
Fiddle: http://sqlfiddle.com/#!2/c718d/1
If I create a simple table like so:
CREATE TABLE name_num(
Number INT PRIMARY KEY,
Name TEXT NOT NULL
);
And then do desc name_num, I get:
| FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA |
---------------------------------------------------
| Number | int(11) | NO | PRI | (null) | |
| Name | text | NO | | (null) | |
Again, from the MySQL docs:
If the column cannot take NULL as the value, MySQL defines the column with no explicit DEFAULT clause. Exception: If the column is defined as part of a PRIMARY KEY but not explicitly as NOT NULL, MySQL creates it as a NOT NULL column (because PRIMARY KEY columns must be NOT NULL), but also assigns it a DEFAULT clause using the implicit default value. To prevent this, include an explicit NOT NULL in the definition of any PRIMARY KEY column.
Related
I am getting duplicate entry error for key 'primary' when trying to insert values and I can't get past it. I added auto_increment to the integer part of the composite key (term_taxonomy_id). Isn't auto_increment supposed to resolve duplicate entries in these situations by incrementing the error-causing record on the fly?
+------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+---------------------+------+-----+---------+----------------+
| object_id | varchar(50) | NO | PRI | NULL | |
| term_taxonomy_id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| term_order | int(11) | NO | | 0 | |
+------------------+---------------------+------+-----+---------+----------------+
https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html says:
When you insert any other value into an AUTO_INCREMENT column, the column is set to that value and the sequence is reset so that the next automatically generated value follows sequentially from the largest column value.
So the auto-increment column generates a new, unique value only if you insert NULL or 0. If you specify a nonzero integer value, you override the auto-increment, and MySQL trusts that you are inserting the value you want. But that means you take responsibility for ensuring the values you insert are unique.
Edit: Not sure why this is marked as a duplicate. The error I am getting is different
I am trying to remove a primary key definition but am receiving an error for some reason.
mysql> ALTER TABLE `aux_sponsors` DROP PRIMARY KEY;
ERROR 1091 (42000): Can't DROP 'PRIMARY'; check that column/key exists
mysql> desc aux_sponsors;
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| unit | varchar(8) | NO | | MF | |
| code | varchar(32) | NO | PRI | NULL | |
| userid | varchar(32) | NO | | | |
| fullName | varchar(64) | NO | | | |
| department | varchar(255) | NO | | | |
| description | varchar(255) | NO | | NULL | |
+-------------+--------------+------+-----+---------+-------+
6 rows in set (0.01 sec)
Am I doing something wrong here? I simply want no more primary key in this table.
mysql> SHOW CREATE TABLE aux_sponsors;
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| aux_sponsors | CREATE TABLE `aux_sponsors` (
`unit` varchar(8) NOT NULL DEFAULT 'MF',
`code` varchar(32) NOT NULL,
`userid` varchar(32) NOT NULL DEFAULT '',
`fullName` varchar(64) NOT NULL DEFAULT '',
`department` varchar(255) NOT NULL DEFAULT '',
`description` varchar(255) NOT NULL,
UNIQUE KEY `code` (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
You don't have a PRIMARY KEY; you have a UNIQUE key. So, you can't do this:
ALTER TABLE `aux_sponsors` DROP PRIMARY KEY
Instead, just do
ALTER TABLE `aux_sponsors` DROP KEY `code`
DESC (a/k/a DESCRIBE) is not a true MySQL feature; according to the docs, "The DESCRIBE statement is provided for compatibility with Oracle."
More from the documentation:
A UNIQUE index may be displayed as PRI if it cannot contain NULL values and there is no PRIMARY KEY in the table. A UNIQUE index may display as MUL if several columns form a composite UNIQUE index; although the combination of the columns is unique, each column can still hold multiple occurrences of a given value.
In your case, the column code is NOT NULL and is the only column in a UNIQUE key, so DESC is showing it as PRI. Because of this type of problem, it's better to use SHOW INDEX to find out the types of keys on a table.
I have a table that contains NULL values. This table is meant only to store numerical values, except the second column which contains a time-stamp for each record. This table has been in use for some time and so has accumulated a lot of NULL values in varying columns. Here's the table's description:
+-----------------------------------------+-----------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------------------------+-----------+------+-----+-------------------+----------------+
| results_id | int(11) | NO | PRI | NULL | auto_increment |
| time_stamp | timestamp | NO | | CURRENT_TIMESTAMP | |
| test_col | int(11) | YES | | NULL | |
| test_col-total | int(11) | YES | | NULL | |
| test_col_B | int(11) | YES | | NULL | |
| test_col_B-total | int(11) | YES | | NULL | |
+-----------------------------------------+-----------+------+-----+-------------------+----------------+
12 rows in set (0.01 sec)
I now want to UPDATE/ALTER the table so that:
from now on any NULL value being added to the table is handled and processed as a '0' value instead (really interested to know if this is indeed possible; if it is then I wont need to change a load of INSERT queries in a lot of my Python scripts elsewhere!)
all stored NULL values are updated/changed to '0'.
I am entirely stuck with this because on the one hand I want my SQL query to update a new rule to the table while on the other change current NULL values and as a novice this is a little more intermediate for my current understanding.
So far I have:
ALTER TABLE `results` MODIFY `<col_name>` INT(11) NOT NULL;
And I will do this for each column that currently allows NULL values. However, I do not know how to change stored NULL values to '0'.
Any input appreciated.
to change NULL values to 0
try
UPDATE results SET `col_name` = 0 WHERE `col_name` IS NULL;
to change columns to have NOT NULL and default to 0 try
ALTER TABLE results MODIFY `col_name` INT(11) NOT NULL DEFAULT 0;
you have to do it in the above order, i just tested this on http://sqlfiddle.com/
First change your values to 0 where they are null:
UPDATE results SET col1 = 0 WHERE col1 IS NULL;
...
Then you can add a DEFAULT of 0, that will be added whenever you supply no values to that table on an insert
ALTER TABLE `results` MODIFY `<col_name>` INT(11) NOT NULL DEFAULT 0;
I am trying to make a order system, but I am stuck right now.
In the mysql tabel right now, I am using varchar(255) in a column named "bestillinger", but it can only store 255 chars. So I searched a bit, and remembered that i could use longtext or just text, but now when i try to do it, i get a error saying:
#1170 - BLOB/TEXT column 'bestilling' used in key specification without a key length
I have tried to search here and in Google, but got no luck with me.
My MySQL tabel is:
CREATE TABLE IF NOT EXISTS `bestillinger` (
`id` int(11) NOT NULL,
`bestilling` TEXT NOT NULL PRIMARY KEY,
`accepted` varchar(255) DEFAULT NULL,
UNIQUE KEY `id_bestilling` (`id`,`bestilling`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
I am using UNIQUE KEY because I am using "ON DUPLICATE KEY UPDATE" in my PHP part. But don't mind that.
Thanks in advance.
you can't set a text as a primary key. Mysql only can Index some characters, and type text could be too big to index.
take a look here:
http://www.mydigitallife.info/mysql-error-1170-42000-blobtext-column-used-in-key-specification-without-a-key-length/
MySQL error: key specification without a key length
From your definition above, and the verbose monologue in this answer below I suggest the following revision:
CREATE TABLE IF NOT EXISTS `bestillinger` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`bestilling` TEXT NOT NULL,
`hashcode` CHAR(32) AS (MD5(bestilling)),
`accepted` VARCHAR(255) DEFAULT NULL,
UNIQUE KEY `id_bestilling` (hashcode,bestilling(333))
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Specific to MySQL, the default max length for a single-column index key is 1000 bytes long (767 bytes for InnoDB tables, unless you have innodb_large_prefix set). The same length limit applies to any index key prefix (the first N characters for CHAR, VARCHAR, TEXT or first N bytes for BINARY, VARBINARY, BLOB). Note the character versus byte difference; assuming a UTF-8 character set and the maximum of 3 bytes for each character, you might hit this limit with a column prefix index of more than 333 characters on a TEXT or VARCHAR column. In practice, 333 tends to be a good max for me.
Similarly in SQL Server, there is a 900-byte limit for the maximum total size of all index key columns.
But that only uses the first characters of your TEXT as your key, with the obvious collisions imminent.
In the accepted answer, the suggestion is to use a FULLTEXT index. A FULLTEXT index is specially designed for text searching, and it has not-so-good performance for INSERT/DELETE since it maintains an N-gram over the vocabulary of the column records and stores the resulting vector. This would work if every operation were to use text search functions in a where clause...but not for a unique index. There is also both a primary key and a unique key defined on 'id', which seems redundant or I miss the intent.
Instead, I suggest a computed hash. you'd be correct to point out there is a chance (Birthday Paradox) that there will be a collision with a hash, so a UNIQUE index alone isn’t enough. We'll couple it with a column prefix index, as described above, to give us faith in the uniqueness.
I gather the intent of your ID column is to allow proper foreign key referencing from other tables. Quite right, but then that would be the more useful primary key for this table. As well, int(11) refers to the display width of the column, not the underlying value. I put an unsigned auto_increment on 'id' as well, to clarify its role for the larger audience.
And that brings us to the proposed design above.
use this
CREATE TABLE IF NOT EXISTS `bestillinger` (
`id` int(11) NOT NULL,
`bestilling` TEXT NOT NULL PRIMARY KEY,
`accepted` varchar(255) DEFAULT NULL,
UNIQUE KEY `id_bestilling` (`id`,`bestilling`(767))
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
767 is the limit in mysql while dealing with blob/text indexes
Ref : http://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html
I think the following example will best explain this problem.
I got the problem because I was trying to set a text field to UNIQUE. I fixed the problem by changing data type of email(TEXT) to email(VARCHAR(254)).
mysql> desc users;
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| fname | varchar(50) | NO | | NULL | |
| lname | varchar(50) | NO | | NULL | |
| uname | varchar(20) | NO | | NULL | |
| email | text | NO | | NULL | |
| contact | bigint(12) | NO | | NULL | |
| profile_pic | text | NO | | NULL | |
| password | varchar(20) | NO | | admin | |
+-------------+-------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
mysql> ALTER TABLE users ADD UNIQUE(email);
ERROR 1170 (42000): BLOB/TEXT column 'email' used in key specification without a key length
mysql>
mysql> ALTER TABLE users MODIFY email VARCHAR(254);
Query OK, 9 rows affected (0.02 sec)
Records: 9 Duplicates: 0 Warnings: 0
mysql> ALTER TABLE users ADD UNIQUE(email);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc users;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| fname | varchar(50) | NO | | NULL | |
| lname | varchar(50) | NO | | NULL | |
| uname | varchar(20) | NO | | NULL | |
| email | varchar(254) | YES | UNI | NULL | |
| contact | bigint(12) | NO | | NULL | |
| profile_pic | text | NO | | NULL | |
| password | varchar(20) | NO | | admin | |
+-------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
mysql>
Try to use all column length in varchar. Text should be not allowed because of size.
I have a mysql table with a compound primary key. The table definition looks like(some column omitted):
CREATE TABLE `wasteitem` (
`categoryid` char(4) NOT NULL,
`classid` char(4) NOT NULL,
`LIflag` int(11) NOT NULL,
PRIMARY KEY (`categoryid`,`classid`)
);
And I want to determine if any of known keys have been used.
If the table have only a simple primary key I can use query like this:
select categoryid from wasteitem where categoryid in ('key1','key2','key3','key4')
Things to be concerned:
The primary key is a compound key.
The known keys in the list might be very long.
This table is very big(26GB)
You could put the keys you're interested in in another (temporary) table, and join.
use it, to look for keys
DESCRIBE wasteitem
that would be something similar:
mysql> describe wasteitem;
+------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| categoryid | char(4) | NO | PRI | NULL | |
| classid | char(4) | NO | PRI | NULL | |
| LIflag | int(11) | NO | | NULL | |
+------------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)