I unable to Insert a value from a char that has been CAST as Integer and added by 1 - mysql

I convert an id which is in a char column datatype. after that, I want to add it by 1 (plus 1).
Could you help me? why my query is not working?
query:
INSERT INTO `countries` (`id`, `country_name`) VALUES ((SELECT MAX(CAST(`id` as INTEGER)) AS `max_id` FROM `countries`) + 1, 'India');

The following would run:
INSERT INTO `countries` (`id`, `country_name`)
SELECT MAX(CAST(`id` as INTEGER)) + 1, 'India'
FROM `countries`;
But I think it would be easier if you just make the id column an AUTO_INCREMENT.

This is not how you should be doing identifiers.
If you want incrementing id values, you want to use the AUTO_INCREMENT feature when creating your table.
Your way is dangerous, there's always a possibility of two transactions running at the same time picking the same "next ID".
Just create a table with the flag on:
CREATE TABLE countries (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO countries (`name`) VALUES ('India');

Related

If I modify a primary key's type, will auto_increment remain intact?

Let's suppose that I have a table created like:
create table my_rows(
id int primary key auto_increment;
/*...*/
)
and I want to earn some unused space and would like to convert it into a smallint, then, I think about modifying it like
alter table my_rows
modify column id unsigned int primary key auto_increment;
Let's assume that there were some ids, up to a certain level, let's say, 257. Is it true that after such a change the value of the id of the next row will be exactly 258, that is, the auto_increment counter will be intact? If not, how should I remedy this?
Works without issues you can play with it here: http://sqlfiddle.com/#!9/85a2d1/3/0
See how you can insert rows with setting the id by hand or letting the auto_increment do it's magic
create table my_rows(
id int NOT NULL primary key auto_increment,
name varchar(50)
);
insert into my_rows(name) values ('One'), ('Two');
insert into my_rows(id, name) values (3, 'Three');
ALTER TABLE my_rows MODIFY id smallint NOT NULL auto_increment;
insert into my_rows(name) values ('Four');
insert into my_rows(id, name) values (5, 'Five');
select * from my_rows;
SHOW COLUMNS FROM my_rows;
/* output looks like: */
id name
1 One
2 Two
3 Three
4 Four
5 Five
Note: Auto_increment does not fill "empty" spots. So if you set ids by hand and leave some empty spots in between and then continue with auto_increment the "empty spots" will not be filled. So here 6 and 7 will be missing
create table my_rows(
id int NOT NULL primary key auto_increment,
name varchar(50)
);
insert into my_rows(name) values ('One'), ('Two');
insert into my_rows(id, name) values (3, 'Three');
ALTER TABLE my_rows MODIFY id smallint NOT NULL auto_increment;
insert into my_rows(name) values ('Four');
insert into my_rows(id, name) values (5, 'Five');
insert into my_rows(id, name) values (8, 'Eight');
insert into my_rows(name) values ('Nine');
http://sqlfiddle.com/#!9/9b993d/1/0

Using SQL Sub-queries in an INSERT Statement

Here are the two tables created:
CREATE TABLE category_tbl(
id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
subcategory varchar(255) NOT NULL,
PRIMARY KEY(id),
CONSTRAINT nameSubcategory UNIQUE KEY(name, subcategory)
) ENGINE=InnoDB;
CREATE TABLE device(
id INT NOT NULL AUTO_INCREMENT,
cid INT DEFAULT NULL,
name VARCHAR(255) NOT NULL,
received DATE,
isbroken BOOLEAN,
PRIMARY KEY(id),
FOREIGN KEY(cid) REFERENCES category_tbl(id)
) ENGINE=InnoDB;
Below is the instruction that was given to me:
-- insert the following devices instances into the device table (you should use a subquery to set up foriegn keys referecnes, no hard coded numbers):
-- cid - reference to name: phone subcategory: maybe a tablet?
-- name - Samsung Atlas
-- received - 1/2/1970
-- isbroken - True
I'm getting errors on the insert statement below from attempting to use a sub-query within an insert statement. How would you solve this issue?
INSERT INTO devices(cid, name, received, isbroken)
VALUES((SELECT id FROM category_tbl WHERE subcategory = 'tablet') , 'Samsung Atlas', 1/2/1970, 'True');
You have different table name in CREATE TABLE and INSERT INTO so just choose one device or devices
When insert date format use the good one like DATE('1970-02-01')
When insert boolean - just TRUE with no qoutes I beleive.
http://sqlfiddle.com/#!9/b7180/1
INSERT INTO devices(cid, name, received, isbroken)
VALUES((SELECT id FROM category_tbl WHERE subcategory = 'tablet') , 'Samsung Atlas', DATE('1970-02-01'), TRUE);
It's not possible to use a SELECT in an INSERT ... VALUES ... statement. The key here is the VALUES keyword. (EDIT: It is actually possible, my bad.)
If you remove the VALUES keyword, you can use the INSERT ... SELECT ... form of the INSERT statement statement.
For example:
INSERT INTO mytable ( a, b, c) SELECT 'a','b','c'
In your case, you could run a query that returns the needed value of the foreign key column, e.g.
SELECT c.id
FROM category_tbl c
WHERE c.name = 'tablet'
ORDER BY c.id
LIMIT 1
If we add some literals in the SELECT list, like this...
SELECT c.id AS `cid`
, 'Samsung Atlas' AS `name`
, '1970-01-02' AS `received`
, 'True' AS `isBroken`
FROM category_tbl c
WHERE c.name = 'tablet'
ORDER BY c.id
LIMIT 1
That will return a "row" that we could insert. Just precede the SELECT with
INSERT INTO device (`cid`, `name`, `received`, `isbroken`)
NOTE: The expressions returned by the SELECT are "lined up" with the columns in the column list by position, not by name. The aliases assigned to the expressions in the SELECT list are arbitrary, they are basically ignored. They could be omitted, but I think having the aliases assigned makes it easier to understand when we run just the SELECT portion.

Keep from creating duplicate entry above zero

Would it be possible to create a database-level restriction to prevent creating a row that has a column x INT with a value that already exists and is above 0?
Is there a way to use CONSTRAINT for this purpose?
A possible solution is to do the following:
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
myfield INT,
CONSTRAINT check_myfield UNIQUE ( myfield )
);
Now, the column myfield might be NULL. So when we do the following, there will be a total of 0 errors.
INSERT INTO `test` VALUES ( '', '1' );
INSERT INTO `test` VALUES ( '', '0' );
INSERT INTO `test` VALUES ( '', '5' );
INSERT INTO `test` VALUES ( '', '7' );
etc, you get the point...
Each and every row has a unique value in the column myfield, but there is still the possibility to create rows where the value in this particular column is NULL which is almost exactly what I wanted. I wanted all values above 0 unique, this is all above NULL. The beauty of this solution is that it feels more 'professional', no unnecessary logic.

INSERT statement for MySQL table

CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (ID=4,Name='xxx')
or
INSERT INTO MyTable (Name) VALUES (Name='xxx')
The problem is that both INSERT statements produce the entry (4,0). Why 0 instead of "xxx"?
UPDATE: Primary key changed.
This should do the job :
INSERT INTO MyTable (ID, Name) VALUES (4, 'xxx')
I'm pretty sure it would be something like this, instead...
INSERT INTO MyTable (Name) VALUES ('xxx')
No need for the Name= part, since you've already specified which column you wish to insert into with the first (Name) definition.
Because the expression Name='xxx' is false, hence evaluates as zero.
You use the column=expression method use in on duplicate key update clauses as described here, not in the "regular" section of inserts. An example of that:
insert into mytable (col1,col2) values (1,2)
on duplicate key update col1 = col1 + 1
You should be using the syntax:
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
Is that syntax of Name='xxx' valid? Never seen it before, i assume it is seeing it as an unquoted literal, trying to convert it to a number and coming up with 0? I'm not sure at all
Try this:
INSERT INTO MyTable (Name) VALUES ('xxx')
This is because you should mention the name of the column in the values part. And also because you do not define you primary key correctly (airlineID is not part of the field list)
CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
INSERT INTO MyTable (Name) VALUES ('xxx')
Try this
INSERT INTO MyTable (ID,Name) VALUES (4,xxx)
For more Info just visit this link

mysql Getting the same auto_increment value into another

This may have a really easy answer. I have done much database stuff for a while. I am trying to get the auto_increment value from one table inserted into the value on another table. is there an easy way of doing this. For eg i have done:
CREATE TABLE table_a (
id int NOT NULL AUTO_INCREMENT,
a_value varchar(4),
PRIMARY KEY (id)
);
CREATE TABLE table_b (
id int NOT NULL,
b_value varchar(15),
FOREIGN KEY (id) REFERENCES table_a (id)
);
Now i want to insert values into the table but I would like 'id' values for table_a and table_b to be the same. So far i have:
INSERT INTO table_a VALUES (NULL, 'foobar');
But I do not know how to go about extracting the auto_incermented 'id' number from table_a into the 'id' value of table_b. I have looked at SELECT #id = LAST_INSERT_ID() but can not get it to work.
You cannot do that at once. You'll have to first insert into the first table:
INSERT INTO table_a (a_value) VALUES ('foobar');
and then insert into the second using the generated id:
INSERT INTO table_b (id, b_value) VALUES (##IDENTITY, 'foobar');
LAST_INSERT_ID() and no need for the select statement part.