MySQL Automatic ID column - mysql

I was wondering how to make MySQL automatically have a column that adds 1 to every row that is made (Row 1 will have ID 1, Row 2 will get ID 2, etc.)
For example:
Every time a new user signs up on a website, they are assigned an ID number. Starting at 1, then 2, etc.
ID|Username|Password
1 |Bob |drowssaP
2 |Jill |cats

Try AUTO_INCREMENT. Documentation here
If you add, that magic word :) to your table creation declaration, it will do the magic for you :)
mysql> CREATE TABLE Users (
-> ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Username varchar(255) NOT NULL,
-> Password varchar(255) NOT NULL
-> );
Query OK, 0 rows affected (0.52 sec)
mysql> INSERT INTO Users(Username, Password) VALUES('vladimir', 'ilich_lenin');
Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO Users(Username, Password) VALUES('friedrich', 'engels');
Query OK, 1 row affected (0.04 sec)
mysql> SELECT * FROM Users;
+----+-----------+-------------+
| ID | Username | Password |
+----+-----------+-------------+
| 1 | vladimir | ilich_lenin |
| 2 | friedrich | engels |
+----+-----------+-------------+
2 rows in set (0.02 sec)
EDIT
mysql> CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, Username varchar(255) NOT NULL, Password varchar(255) NOT NULL);
Query OK, 0 rows affected (0.25 sec)
mysql> SHOW CREATE TABLE
CREATE TABLE `Persons` (
`ID` int(11) NOT NULL,
`Username` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
1 row in set (0.00 sec)
mysql> ALTER TABLE Persons MODIFY ID INTEGER NOT NULL AUTO_INCREMENT;
Query OK, 0 rows affected (0.50 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE Persons;
CREATE TABLE `Persons` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Username` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
1 row in set (0.00 sec)
mysql> INSERT INTO Persons(Username, Password) VALUES('friedrich', 'engels');
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO Persons(Username, Password) VALUES('karl', 'marx');
Query OK, 1 row affected (0.08 sec)
mysql> SELECT * FROM Persons
-> ;
+----+-----------+----------+
| ID | Username | Password |
+----+-----------+----------+
| 1 | friedrich | engels |
| 2 | karl | marx |
+----+-----------+----------+
2 rows in set (0.00 sec)

Related

Converting from VARCHAR to BINARY(16) in MySQL?

I have as table with this column and type:
sales_channel_id BINARY(16)
In the row I have this value: 5DBACA1114B24872ACCFE679037DF670
I have written this value into another table, but this time the table column has the type VARCHAR(255). In the table I see this value: 5dbaca1114b24872accfe679037df670 (no capitals).
Now I have created another table with a column of type BINARY(16). When I make something like this to transform the data from the varchar column to the new column like this:
INSERT INTO
setting_sales_channel (sales_channel_id)
SELECT sales_channel_id from mcn_setting
I get the error: Query 1 ERROR: Data too long for column 'sales_channel_id' at row 1
Why does this happen and how can I transfer the data from the VARCHAR column into the new column which is of type BINARY(16)?
Try this.
change your query to:
INSERT INTO
setting_sales_channel (sales_channel_id)
SELECT CONVERT(sales_channel_id,BINARY(16)) from mcn_setting;
sample (MariaDB)
MariaDB [bernd]> show create table b;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| b | CREATE TABLE `b` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`bbinary` binary(16) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.001 sec)
MariaDB [bernd]> show create table bs;
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| bs | CREATE TABLE `bs` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`bvarchar` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.000 sec)
MariaDB [bernd]> SELECT * from b;
Empty set (0.002 sec)
MariaDB [bernd]> SELECT * from bs;
+----+----------------------------------+
| id | bvarchar |
+----+----------------------------------+
| 1 | 5dbaca1114b24872accfe679037df670 |
+----+----------------------------------+
1 row in set (0.000 sec)
MariaDB [bernd]>
MariaDB [bernd]> INSERT INTO b (bbinary)
-> SELECT CONVERT(bvarchar,BINARY(16)) FROM bs;
Query OK, 1 row affected, 1 warning (0.003 sec)
Records: 1 Duplicates: 0 Warnings: 1
MariaDB [bernd]> SELECT * from bs;
+----+----------------------------------+
| id | bvarchar |
+----+----------------------------------+
| 1 | 5dbaca1114b24872accfe679037df670 |
+----+----------------------------------+
1 row in set (0.000 sec)
MariaDB [bernd]>
In my case it worked when using UNHEX now. The result looked like this:
INSERT INTO setting_sales_channel (sales_channel_id)
SELECT UNHEX(sales_channel_id) from setting;

MySQL select default value

I have foreign key in one table, references on another table, not null. How can I select the default value for it?
Something like this:
ALTER TABLE table_a MODIFY COLUMN not_null_column BIGINT NOT NULL DEFAULT
(SELECT id FROM table_b WHERE name_field = 'some name');
Or this:
SET #defaultValue = (SELECT id FROM table_b WHERE name_field = 'some name');
ALTER TABLE table_a MODIFY COLUMN not_null_column BIGINT NOT NULL DEFAULT #defaultValue;
One option is to use 13.5 Prepared SQL Statement Syntax.
mysql> DROP TABLE IF EXISTS `table_b`, `table_a`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `table_a` (
-> `not_null_column` VARCHAR(20)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `table_b` (
-> `name_field` VARCHAR(255) NOT NULL,
-> `value` VARCHAR(255) NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `table_b`
-> (`name_field`, `value`)
-> VALUES
-> ('some name', '5');
Query OK, 1 row affected (0.00 sec)
mysql> DESC `table_a`;
+-----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| not_null_column | varchar(20) | YES | | NULL | |
+-----------------+-------------+------+-----+---------+-------+
1 row in set (0.00 sec)
mysql> SET #`stmt` := CONCAT('ALTER TABLE `table_a`
'> MODIFY COLUMN `not_null_column` BIGINT NOT NULL
'> DEFAULT ', (SELECT `value`
-> FROM `table_b`
-> WHERE `name_field` = 'some name'));
Query OK, 0 rows affected (0.01 sec)
mysql> SELECT #`stmt`;
+-------------------------------------------------------------------------------------------------------------------------------+
| #`stmt` |
+-------------------------------------------------------------------------------------------------------------------------------+
| ALTER TABLE `table_a`
MODIFY COLUMN `not_null_column` BIGINT NOT NULL
DEFAULT 5 |
+-------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> PREPARE `stmt` FROM #`stmt`;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE `stmt`;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> DEALLOCATE PREPARE `stmt`;
Query OK, 0 rows affected (0.00 sec)
mysql> DESC `table_a`;
+-----------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+------------+------+-----+---------+-------+
| not_null_column | bigint(20) | NO | | 5 | |
+-----------------+------------+------+-----+---------+-------+
1 row in set (0.00 sec)
Example db-fiddle.

Set column value of this/next auto_increment value

Is there any way to accomplish below sql result as a one liner.
create table test( id int not null primary key auto_increment, name char(10));
insert into test (name) values ('voda'+ this_value_of_id);
// so select would return
MariaDB [testdb]> select * from test;
+----+------+
| id | name |
+----+------+
| 1 | foo1 |
+----+------+
Yes, I know the other way is
begin transaction;
insert into test (name) values ('voda');
update test set name = concat('voda', id) where id = 1;
commit;
An option or approach can be via a Virtual (Computed) Columns.
Example:
MariaDB [testdb]> DROP TABLE IF EXISTS `test`;
Query OK, 0 rows affected (0.00 sec)
MariaDB [testdb]> CREATE TABLE `test` (
-> `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `name` CHAR(10),
-> `nameid` VARCHAR(20) AS (CONCAT(`name`, `id`)) VIRTUAL
-> );
Query OK, 0 rows affected (0.00 sec)
MariaDB [testdb]> INSERT INTO `test`
-> (`name`)
-> VALUES
-> ('foo'), ('voda');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
MariaDB [testdb]> SELECT
-> `id`,
-> `nameid` `name`
-> FROM
-> `test`;
+----+-------+
| id | name |
+----+-------+
| 1 | foo1 |
| 2 | voda2 |
+----+-------+
2 rows in set (0.00 sec)

MYSQL have set a column to not null but still it's accepting null value [duplicate]

This question already has answers here:
A constraint to prevent the insert of an empty string in MySQL
(2 answers)
Closed 8 years ago.
Structure for a table in mysql5.5
tablename:
id:
name:
detail:
here even altering the table:
ALTER TABLE tablename MODIFY name VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL;
OR
ALTER TABLE `tablename` CHANGE `name` `name` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL DEFAULT NOT NULL;
after inserting value:
INSERT INTO `databasename`.`tablename` (`id`, `name`, `detail`) VALUES (NULL, '', 'asdfasfdadsfadsfafd');
query has run successfully no error row has been added to table,
how can i prevent such empty or null.
regards
Try this:
ALTER TABLE tablename
MODIFY COLUMN name VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL CHECK (name <> '');
DEMO:
mysql> create table tablename(id int(2) not null, something varchar(25) null, primary key(id));
Query OK, 0 rows affected (0.15 sec)
mysql> insert into tablename values(0,'hello');
Query OK, 1 row affected (0.38 sec)
mysql> insert into tablename values(1,'salut');
Query OK, 1 row affected (0.31 sec)
mysql> select * from tablename;
+----+-----------+
| id | something |
+----+-----------+
| 0 | hello |
| 1 | salut |
+----+-----------+
2 rows in set (0.00 sec)
Now, I run the UPDATE command:
mysql> ALTER TABLE tablename MODIFY COLUMN something VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL;
Query OK, 2 rows affected (0.70 sec)
Records: 2 Duplicates: 0 Warnings: 0
I insert a normal row:
mysql> insert into tablename values(2,'france');
Query OK, 1 row affected (0.29 sec)
But it does not allow me to insert a NULL value:
mysql> insert into tablename values(3,NULL);
ERROR 1048 (23000): Column 'something' cannot be null
I check to be sure:
mysql> select * from tablename;
+----+-----------+
| id | something |
+----+-----------+
| 0 | hello |
| 1 | salut |
| 2 | france |
+----+-----------+
3 rows in set (0.00 sec)

MySQL INSERT ... ON DUPLICATE KEY not updating table with no errors or warnings

So I have the following table:
mysql> show create table user_api_skills \G
*************************** 1. row ***************************
Table: user_api_skills
Create Table: CREATE TABLE `user_api_skills` (
`characterID` int(11) NOT NULL,
`typeID` int(11) NOT NULL,
`level` enum('0','1','2','3','4','5') NOT NULL DEFAULT '0',
`skillpoints` int(11) NOT NULL,
`currentTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`characterID`,`typeID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
mysql>
And in that table a row which I am trying to insert/update:
mysql> SELECT * FROM `user_api_skills` WHERE `characterID` =93192782 AND `typeID` =3359;
+-------------+--------+-------+-------------+---------------------+
| characterID | typeID | level | skillpoints | currentTime |
+-------------+--------+-------+-------------+---------------------+
| 93192782 | 3359 | 3 | 135765 | 2013-09-30 16:58:35 |
+-------------+--------+-------+-------------+---------------------+
1 row in set (0.00 sec)
I believe my query is correctly formed and when executed it doesn't throw any errors or warnings:
mysql> INSERT INTO user_api_skills (characterID,typeID,level,skillpoints)
VALUES (93192782,3359,4,135765) ON DUPLICATE KEY UPDATE level=4,
skillpoints=135765,currentTime=NOW();
Query OK, 2 rows affected (0.22 sec)
I get 2 rows updated (as I would expect from an insert on dup update)
mysql> SELECT * FROM `user_api_skills` WHERE `characterID` =93192782 AND `typeID` =3359;
+-------------+--------+-------+-------------+---------------------+
| characterID | typeID | level | skillpoints | currentTime |
+-------------+--------+-------+-------------+---------------------+
| 93192782 | 3359 | 3 | 135765 | 2013-09-30 16:59:13 |
+-------------+--------+-------+-------------+---------------------+
1 row in set (0.00 sec)
mysql>
but the row itself only changes a single value (the currentTime). Can anybody explain why the other two fields are not updating?
Sorry, I have solved this myself. The level field is an ENUM and the query specified the new value as a number. Updating the query to the following resulted in the expected results.
mysql> INSERT INTO user_api_skills (characterID,typeID,level,skillpoints) VALUES
(93192782,3359,4,135765) ON DUPLICATE KEY UPDATE level='4', skillpoints=135765,
currentTime=NOW();
By providing a int to the update it updated to the one based number choice of the enum, so in this instance, the 4th choice is '3'.