Why can I not change mysql int value? - mysql

It seems like a bug because when I set the integer value on a column it says it has been changed successfully but nothing happens and the integer value remains blank.
I can't use the database because I get the error that all my integer columns have incorrect integer values, but when I try to change them to int(11) e.g. nothing is happening.
Does anyone know how to fix this?
I can set columns with varchar datatypes to have values and they work fine.
Fatal error: Uncaught mysqli_sql_exception: Incorrect integer value: '' for column 'topic_id' at row 1 in C:\wamp64\www\mycode\upload2.php on line 32
mysqli_sql_exception: Incorrect integer value: '' for column 'topic_id' at row 1 in C:\wamp64\www\mycode\upload2.php on line 32
Code:
ALTER TABLE `topics` CHANGE `topic_id` `topic_id` INT(11) NOT NULL
AUTO_INCREMENT;
// This isn't changing the int value at all!

You have multiple errors in what you are attempting to do.
First, there is the problem that the values in the table are not integers.
Second, you cannot set a column to auto-increment unless it is the primary key.
One option is to drop the primary key and auto-increment idea. Then you can update the values to NULL and change the column to an int:
update topics
set topic_id = null
where topic_id regexp '[^0-9]';
ALTER TABLE `topics` CHANGE `topic_id` `topic_id` INT(11) ;
Here is a db<>fiddle.
If you really want topic_id to be an auto-increment primary key, then I would suggest recreating the table. Something like this:
create table temp_topics as
select *
from topics;
drop table topics; -- be very careful here!
create table topics (
topic_id int auto_increment primary key,
. . . -- the rest of the columns
);
insert into topics (<list of columns here>)
select <list of columns here>
from temp_topics;

if you wanna change a value you have to update that row.
what you are trying to do is wrong , int data type has fixed length (4 bytes), so when you give it a length , it actually doesn't mean anything and its been ignored by the sql engine
see MySql Ref: https://dev.mysql.com/doc/refman/8.0/en/integer-types.html
numeric data types are divided into 3 categoies :
Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC
Floating-Point Types (Approximate Value) - FLOAT, DOUBLE

Related

Is it logically correct to have an integer column of length 1 in SQL if we don't need leading zeros?

Let's say we have a simple table of 2 columns with two scenarios.
With ID column of length 10
CREATE TABLE `members` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
)
With ID column of length 1
CREATE TABLE `members` (
`id` int(1) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
)
Can I define the length of column ID by 1 if I don't need the leading zeros in the ID column?
I don't have an idea where the leading zeros are helpful and what are the cons if I define the length of the integer column by 1 if there is no need for leading zeros.
If you don't need leading zeroes, then simply do not use the ZEROFILL column option, which I see is already absent from your create table statement.
The "length" of an integer is meaningless except for display. It does not affect the storage size of the integer, or the maximum value that can be stored in it. The length is optional, and I always omit it.
Example:
CREATE TABLE `members` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
...
This has been the source of confusion for MySQL users for many years.
Finally in MySQL 8.0, they stopped outputting this misleading syntax when you use SHOW CREATE TABLE. Use of the integer length is discouraged.
The short answer is: You can set the zerofill length to 1 if you absolutely have no use of it. However, sometimes you may want your numbers to be neatly aligned . e.g Instead of displaying ID values from 1 all the way up to 9999, defining an int(4) zerofill makes the values show up from 0001 to 9999. That could be helpful in certain formal scenarios.

Not null confusion

In phpMyAdmin, as we create table there is not null constraints by default for all fields...and as per my knowledge when we set the constraint to not null...it doesn't allow user to remain field empty which are not null as per this link.....
http://www.techopedia.com/definition/27370/not-null-constraint
now my question is..according to this link, not null means every row of data must contain a value - it cannot be left blank during insert or update operations.....but when i insert data programatically like insert into, i am able to insert data in just two fields and other remains blank although there is not null constraints on that fields ...and still not generates any error....so i don't understand how not null works???
for example, i create table with lets say 5 fields...
create table myTable
(
Column1 int not null,
Column2 int not null,
Column3 int not null,
Column4 int not null,
Column5 int not null,
)
and insert values in just two fields like
"INSERT INTO myTable (column1,column2) VALUES(10,20)";
but other fields i don't give any '' so it takes 0 as value....and still i am able to insert data with no error...how is that possible??
Everything that has the NOT NULL constraint set needs to contain data. If you insert data programmatically and you do not insert data for a NOT NULL cell, then you will get an SQL Error.
e.g. you have this table:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL,
some_other_value INTEGER);
Then some_value will contain data in every data set returned, some_other_value may or may not contain data in every data set returned. The only thing to work around this would be this:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL DEFAULT 0,
some_other_value INTEGER);
If you now set data programatically and do not set data for some_value, some_value will default to 0 (or to whatever data you set the default to on table creation).
Maybe you can refer to this link:
For multiple-row INSERT statements or INSERT INTO ... SELECT
statements, the column is set to the implicit default value for the
column data type. This is 0 for numeric types, the empty string ('')
for string types, and the “zero” value for date and time types. INSERT
INTO ... SELECT statements are handled the same way as multiple-row
inserts because the server does not examine the result set from the
SELECT to see whether it returns a single row. (For a single-row
INSERT, no warning occurs when NULL is inserted into a NOT NULL
column. Instead, the statement fails with an error.)
If a column definition includes no explicit DEFAULT value and it is defined as "Not Null" then Mysql will automatically assign default value to the column based on datatype. e.g. 0 for integer and "" for varchar
If you create a unique index on a column, the default value will be accepted with the first row but will give an error with subsequent inserts.

Create mysql table limit integer to positive values

I try to create a table with an INTEGER attribute which should be limited to positive numbers. I know there is an UNSIGNED option, but that does the wrong thing. As it allows adding -10 as a value. It will just make a 10 out of it.
Is it possible to deny a wrong entry? I tried using CHECK
DROP TABLE Produkt;
CREATE TABLE Produkt (
Bezeichnung VARCHAR(237) PRIMARY KEY,
ProduktNr INTEGER NOT NULL,
Produktart VARCHAR(3) DEFAULT "XXX",
CONSTRAINT onlyPositive CHECK(ProduktNr >= 0)
);
But I can still add -10 as a value... What am I doing wrong?
1) In a strict sql_mode if you define your column as
ProduktNr INT UNSIGNED NOT NULL,
and then try to insert a negative value you'll get an error
ERROR 1264 (22003): Out of range value for column 'ProduktNr' at row 1
Here is SQLFiddle demo. Uncomment insert statement and click Build Schema
2) MySQL still lacks support for CHECK constraints. The CHECK clause is parsed but ignored by all storage engines.
3) On a side note: don't use a VARCHAR(237) column as a PRIMARY KEY, especially if you're using InnoDB engine (all secondary indices on the table also include PK values).
I believe you can just add the check without naming the constraint. This seemed to work for me:
CREATE TABLE Produkt (
Bezeichnung VARCHAR(237),
ProduktNr INTEGER NOT NULL,
Produktart VARCHAR(3) DEFAULT "XXX",
PRIMARY KEY (Bezeichnung),
CHECK(ProduktNr >= 0)
);
I also moved the declaration of the primary key. I'm not 100% certain that you can declare a key the same time as a field, but I did put what I knew.

MySQL: set field default value to other column

How to set default value for a field to other column in MySQL?
I have done it in Oracle with virtual field, but I do not know how to do it in MySQL.
This is my table:
CREATE TABLE TSM_TRANSACTION_TBL
(
TRANS_ID INT primary key auto_increment,
LOCATION_ID INT,
TRANS_DATE DATE,
RESOURCE_ID INT,
TS_ID INT,
MAX_VALUE INT,
BOOKED_UNITS INT default 0,
REMAINING INT default MAX_VALUE - BOOKED_UNITS,
BOOKED INT not null,
USER_ID INT,
TRANS_TIME TIMESTAMP
);
As documented under Data Type Default Values:
The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column. See Section 11.3.5, “Automatic Initialization and Updating for TIMESTAMP”.
Instead, you can define an insertion trigger:
CREATE TRIGGER foo BEFORE INSERT ON TSM_TRANSACTION_TBL FOR EACH ROW
IF NEW.REMAINING IS NULL THEN
SET NEW.REMAINING := NEW.MAX_VALUE - NEW.BOOKED_UNITS;
END IF;;
The 'NEW' is unacceptable for AFTER insert triggers. You should do the 'field update' by a BEFORE insert trigger. So,
CREATE TRIGGER foo BEFORE INSERT ON TSM_TRANSACTION_TBL FOR EACH ROW
IF NEW.REMAINING IS NULL THEN
SET NEW.REMAINING := NEW.MAX_VALUE - NEW.BOOKED_UNITS;
END IF;;
As of MySQL 8.0.13, you can reference another column as the default value of a column.
An expression default value for one column can refer to other table columns, with the exception that references to generated columns or columns with expression default values must be to columns that occur earlier in the table definition. That is, expression default values cannot contain forward references to generated columns or columns with expression default values.
CREATE TABLE table1 (
id int NOT NULL AUTO_INCREMENT,
name varchar(250) NOT NULL,
name_url varchar(250) NOT NULL DEFAULT (`name`),
created datetime NOT NULL DEFAULT (UTC_TIMESTAMP()),
modified datetime NOT NULL DEFAULT (UTC_TIMESTAMP()),
PRIMARY KEY (id),
)
ENGINE = INNODB,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_0900_ai_ci;
After srearching.. i found some solutions.
first solution: using default
REMAINING INT default (MAX_VALUE - BOOKED_UNITS)
this solution will only give value if you didn't give a value when insert.
second solution: using Trigger
SQL auto-create a value column
third solution: using GENERATED ALWAYS AS
number1 INT,
number2 INT,
result INT GENERATED ALWAYS AS(number2 - number1),
this solution will always fill it for you after insert

How to add a not null constraint to an already existing column with null values?

I've seen a similar question on stackexchange, but it's answer did not give me the correct results.
For demonstration purposes, I have a simple table PURCHASES with columns PURCHASE_NUM, PURCHASE_DATE, CUSTOMER_ID. I want to enforce a not null constraint on the CUSTOMER_ID table. I tried the following:
ALTER TABLE PURCHASES MODIFY CUSTOMER_ID char NOT NULL;
That syntax is fine, but then I insert with the following: INSERT INTO PURCHASES VALUES (333, NULL, NULL); and the tuple is added without issue. Why is the constraint not being enforced? Would having NULL values already in that column before adding the constraint affect things?
Thanks
edit DESCRIBE PURCHASES; says the following for the column of interest:
Field, Type, Null, Key, Default, Extra
CUSTOMER_ID, char(5), YES, , NULL,
Your ALTER command didn't work, the Null column still says YES. Your ALTER command syntax looks just fine, it should have worked. Check your typing and try again.
Is your customer ID really just a char?
Maybe you have to change to
ALTER TABLE PURCHASES MODIFY CUSTOMER_ID char NOT NULL;
According to the manual, data entry into a NOT NULL column that has no explicit DEFAULT clause will set the column to NULL. Thus, you should ALTER your column to contain a DEFAULT. From 4.0 documentation:
Implicit defaults are defined as follows:
For numeric types, the default is 0, with the exception that for integer or floating-point types declared with the AUTO_INCREMENT attribute, the default is the next value in the sequence.
For date and time types other than TIMESTAMP, the default is the appropriate “zero” value for the type. For the first TIMESTAMP column in a table, the default value is the current date and time. See Section 10.3, “Date and Time Types”.
For string types other than ENUM, the default value is the empty string. For ENUM, the default is the first enumeration value.