I would like to add a new autoincrement column to a pre-existing table. However, I need the ids that are in that column to start at a particular value, ie
alter table MyTable
add column MyColumn int unsigned not null primary key auto_increment=999999;
Is this possible? I tried issuing:
alter table MyTable auto_increment=999999;
before I added the column, but it had no effect. Because adding the column will automatically generate the ids, it is not sufficient to run the second statement after the first.
No, it works to add an AI column with a starting position. But you almost got the syntax right. Here's a demo:
mysql> CREATE TABLE foo (v varchar(10));
mysql> INSERT INTO foo VALUES ('one'), ('two'), ('three');
Then comes the tricky syntax. You have to declare the column as AUTO_INCREMENT, but then also give the table option for the AUTO_INCREMENT starting value. And you need a comma to separate the ADD COLUMN from the table option.
mysql> ALTER TABLE foo ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY,
AUTO_INCREMENT=999999;
mysql> select * from foo;
+-------+---------+
| v | id |
+-------+---------+
| one | 999999 |
| two | 1000000 |
| three | 1000001 |
+-------+---------+
Related
I have a table with various fields including a primary key, id, which is auto-incrementing:
+-------------------------------+------------------+------+-----+---------+
| Field | Type | Null | Key | Default | Extra
+-------------------------------+------------------+------+-----+---------+
| id | tinyint(11) | NO | PRI | NULL | auto_increment
The table is already populated with 114 items:
mysql> select count(*) as cnt from beer;
+-----+
| cnt |
+-----+
| 114 |
+-----+
And I am trying to insert a group of new items into the table. I am not explicitly inserting an id key. Here's a sample query:
mysql> INSERT INTO beer (name, type, alcohol_by_volume, description, image_url)
VALUES('Test Ale', 1, '4.6', '', 'https://untappd.s3.amazonaws.com/site/assets/images/temp/badge-beer-default.png');
I get the following error when attempting to manually insert that query (the insertion is actually done with a PHP script to the same results):
ERROR 1062 (23000): Duplicate entry '127' for key 1
What's going on? I thought the id would automatically increment upon insertion. I should note that the first 13 entries are blank/null for some reason, and the last key is currently 127. (it's not my table -- I'm just writing the script).
Tiny int is not the good choice for auto_increment primary key... Range is just (-128...127). Normally it's used as a flag; you need to use unsigned int
Try resetting the auto increment of primary key manually using this:
ALTER TABLE `beer` AUTO_INCREMENT = 128;
Lets say we have table A with just one column, id(which is the primary key)
How do we insert a new row into the table without specifying an id?
I tried this
INSERT INTO A (`id`) VALUES (NULL)
and it doesn't work
Edit: I forgot to mention that id, the primary key has the auto_increment and NOT NULL attribute.
Edit 2: The exact error when running the query above is
Column 'id' cannot be null
As soon as 'id' as the auto-increment enable (assuming ID is an integer), you can just do:
INSERT INTO A (id) values (null)
and 'id' will keep incrementing each time.
only works if you're using an auto_increment primary key (PK) as every PK must have a unique, non null value.
drop table if exists A;
create table A
(
id int unsigned not null auto_increment primary key
)
engine=innodb;
insert into A (id) values (null),(null);
mysql> select * from A order by id;
+----+
| id |
+----+
| 1 |
| 2 |
+----+
2 rows in set (0.00 sec)
I had a similar issue, then I noticed that I didn't apply the changes when I changed id to primary key + not null + auto incremental.
INSERT INTO `table` () VALUES ();
is working too.
Try it without the ``..
As in:
INSERT INTO A(sid) VALUES(NULL); //i used sid instead of id...
worked fine for me..
Also wwhile creating the table A, specify unique(sid)...
i.e
create table A(sid int(3) not null auto_increment unique(sid));
I'm looking at this Mysql question link:
And I can't repeat the behavior described in the answer to that question.
I tried creating tables with CHAR and VARCHAR column of various lengths and it doesn't matter what length - SHOW CREATE TABLE always return the data type that I've originally defined.
So - no CHAR->VARCHAR switching is going on.
Is answer to the question below only partially correct (I'm talking only about items 1 and 2)?
Q:
When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables?
A (supposedly):
VARCHARs with length less than 4 become CHARs
CHARs with length more than 3 become VARCHARs.
NOT NULL gets added to the columns declared as PRIMARY KEYs
Default values such as NULL are specified for each column
There is a page in the MySQL's manual that answers some of your questions : 12.1.14.2. Silent Column Specification Changes.
Quoting some portions that correspond to items you posted in your question :
For item 3 :
Columns that are part of a PRIMARY
KEY are made NOT NULL even if not
declared that way.
About the size of varchar columns (not exactly one of your items, though) :
If strict SQL mode is not enabled, a
VARCHAR column with a length
specification greater than 65535 is
converted to TEXT, and a VARBINARY
column with a length specification
greater than 65535 is converted to
BLOB. Otherwise, an error occurs in
either of these cases.
And that page ends with the following sentence :
To see whether MySQL used a data type
other than the one you specified,
issue a DESCRIBE or SHOW CREATE
TABLE statement after creating or
altering the table.
So I'm guessing you might expect some additional differences, that are not listed.
Doing a quick test, here's a create table statement :
create table test_2 (
id int primary key,
blah_vc varchar(2),
blah_c char(5)
) engine=InnoDb;
And the table that's created gives :
mysql> desc test_2;
+---------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| blah_vc | varchar(2) | YES | | NULL | |
| blah_c | char(5) | YES | | NULL | |
+---------+------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> show create table test_2;
+--------+--------------------------------------------+
| Table | Create Table |
+--------+--------------------------------------------+
| test_2 | CREATE TABLE `test_2` (
`id` int(11) NOT NULL,
`blah_vc` varchar(2) DEFAULT NULL,
`blah_c` char(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+--------+--------------------------------------------+
1 row in set (0.00 sec)
So :
no : varchar has not been transformed to char
no : char has not been transformed to varchar
yes : not null has been added to primary key
well, that one is funny : describe says it hasn't,
but show create table indicates it has...
Anyway : it makes sense, for a primary key column, to not be nullable.
yes : null is specified as default for columns that can be null.
That question is pretty old, written back in the days of MySQL 4.
As of MySQL 5.0, 1 & 2 from that list are no longer true.
I'm currently trying to create a mySQL database that holds hashes such as MD5 hashes. I'm using PHPmyAdmin version 3.3.9, and MySQL client version: 4.1.22
I already created a database named hashes. I'm new to mySQL so how can I add a table with data for a hash?
Hash column should be a CHAR(32) as that is the length of the hash:
CREATE TABLE `hashes` (
`id` INT NOT NULL AUTO_INCREMENT,
`hash` CHAR(32),
PRIMARY KEY (`id`)
);
mysql> describe hashes;
+-------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| hash | char(32) | YES | | NULL | |
+-------+----------+------+-----+---------+----------------+
If you want to select from the table given user input:
-- Insert sample data:
mysql> INSERT INTO `hashes` VALUES (null, MD5('hello'));
Query OK, 1 row affected (0.00 sec)
-- Test retrieval:
mysql> SELECT * FROM `hashes` WHERE `hash` = MD5('hello');
+----+----------------------------------+
| id | hash |
+----+----------------------------------+
| 1 | 5d41402abc4b2a76b9719d911017c592 |
+----+----------------------------------+
1 row in set (0.00 sec)
You can add a key on hash for better performance.
A hash can be stored as binary data or (more convenient) as text. The PHP MD5 function by default outputs a string of 32 characters, so you will need a table with a field that can hold a string of 32 character. That's all. :)
Take a look here:
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
You can do it using phpMyAdmin of course but it is better to understand the actual SQL.
If you open the database (click it's name in the left hand column), there will be a "Create new table on database dbname" section. Enter the name of the table you want (e.g. hashes), and the number of fields you want.
This is where we need a bit more information: if you just want to store hashes and hashes alone then you'll need two fields: a unique hash ID (of type integer, with auto_increment set to true) and a 32 character text field. I'm a little unsure of the utility of this, so if you post a bit more information we might be able to help you out with what you're trying to achieve a little better?
Edit:
In that case, you'll need three fields: a hash id (a unique reference for each entry in the table), the hash, and the plaintext to which it correlates. Set the hash id to be an integer, with auto_increment set to true. Set the field for the hash to be varchar of length 32, and the plaintext field to 'text'.
ALTER TABLE tada_prod.action_6_weekly ADD COLUMN id INT NULL AUTO_INCREMENT UNIQUE AFTER member_id;
works,
so i thought, to add the column as the first column i could do
ALTER TABLE `tada_prod`.`action_6_weekly` ADD COLUMN `id` INT NULL AUTO_INCREMENT UNIQUE BEFORE `code`;
but i get a syntax error,
what is the correct syntax?
ALTER TABLE `tada_prod`.`action_6_weekly`
ADD COLUMN `id` INT NULL AUTO_INCREMENT UNIQUE FIRST;
You can add column only after particular field or at first not before.
The mysql query for add column after particular filed is:ALTER TABLE table_name ADD COLUMN column_name VARCHAR(30) AFTER column_name
Actually,
alter table table_name ADD column_name VARCHAR(12) NOT NULL BEFORE specific_column_name;
This command is not allowed in mySQL syntax. If you use it I think you get
" ERROR 1064: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'before specific_column_name' at line 1 " message.
You can try:
ALTER TABLE table_name ADD column_name VARCHAR(12) NOT NULL FIRST;
Extending #php answer, I think the rationale behind not including BEFORE is because all the effects of BEFORE can be easily achieved using AFTER and FIRST
For Ex:
Let's say, initially you have a relational schema like
+----------------------+
| name | age | address |
+----------------------+
and then for some reason you're compelled to add a new column dob(date of birth) just before age, but since BEFORE is not allowed, what you can do instead is insert dob just after the name using AFTER and very well achieve the same effect.
+----------------------------+
| name | dob | age | address |
+----------------------------+
But what if you wanted to insert a new column `id` before `name`?
Since there is no column before name we cannot use AFTER to place the id column. In-order to resolve this, the language designers introduced FIRST which makes the desired id column as the first column of the table.
+---------------------------------+
| id | name | dob | age | address |
+---------------------------------+
Although I personally think AFTER and BEFORE would've made a more intuitive pair.