In sql-server there is function to auto-increment guid fields.
CREATEGUID()
how can I do the same thing in Mysql?
I'm new in database programing.
I want to create primary key field 16byte auto-incremented.
You can create a BEFORE INSERT trigger to check new value for the auto-increment guid field, and if it is NULL, set value = UUID().
This function may be useful too - UUID_SHORT().
UUID_SHORT() - Returns a “short” universal identifier as a 64-bit unsigned integer (rather than a string-form 128-bit identifier as returned by the UUID() function).
MySQL has UUID() function which returns char/varchar. You can use, for example, either BINARY(16) or CHAR(36) to save data like that (binary requires some data translation before insertion).
But MySQL supports AUTO_INCREMENT for numeric datatypes only.
Related
I'm new to this website and using Mysql and phpMyAdmin. I need help with one of my table and I would really appreciate it. So, I created a table that has an Integer column I want to be able to limit it to only 7(Seven) digits I'm not quiet sure if this is possible using Mysql or phpMyAdmin.
I haven't tried any query on it. I want to limit the Integer type to only 7(Seven) digits.
This might not be the best possible solution but I think that if you were to store the integer as string in the format char(7) to limit the number of characters able to be entered it would get the job done.
I'm not familiar with Mysql in particular but here's some documentation on it : https://dev.mysql.com/doc/refman/8.0/en/char.html
I hope this helped.
In MySQL <8.0.16 You can't restrict the number of digits for an Integer. That has no meaning.
You can, however, use a DECIMAL type that allows you to specify the number of digits and the number of decimal places.
For example, DECIMAL(7,0) will define what you want.
Your CREATE statement becomes something like
CREATE TABLE IF NOT EXISTS myTable (
id INT AUTO_INCREMENT PRIMARY KEY,
someText VARCHAR(255) NOT NULL,
decimalValue DECIMAL(7,0)
) ;
If you're using MySQL 8.0.16 or later you can use a CHECK constraint to limit the value (as distinct from limiting the number of digits).
The example above becomes
CREATE TABLE IF NOT EXISTS myTable (
id INT AUTO_INCREMENT PRIMARY KEY,
someText VARCHAR(255) NOT NULL,
decimalValue INT,
CONSTRAINT `decValue_chk` CHECK (`decimalValue` <= 9999999))
) ;
I am trying to add a column to an existing table in MySql 8.0.17. The column needs to contain a UUID and I am trying to set it as a default value.
This is the statement I am executing
ALTER TABLE myTable ADD COLUMN UUID varchar(36) NOT NULL DEFAULT (UUID());
However I am getting the following error
Error Code: 1674. Statement is unsafe because it uses a system function that may return a different value on the slave.
I have read from other posts that it is possible to create a Trigger on the table however i would like to find out whether it is possible to set it directly as the default value on the column.
Also, what would be the advantage of using a binary conversion of the UUID over just a simple UUID ?
Eg.
ALTER TABLE myTable ADD COLUMN UUID binary(16) NOT NULL DEFAULT (UUID_TO_BIN(UUID(), true));
Thanks for your help.
assigning UUID() as DEFAULT value won't work, because It does not guarantee that the same value will be generated on your replica. That is why using TRIGGER is good option for new records (insertions).
If your intention is to update current records as well, you can write an update statement
update myTable
set UUID = UUID()
your column is of type binary(16) which means UUID data is implicitly converted to binary. using UUID_TO_BIN is not needed.
EDIT:
CHAR/VARCHAR is the human-readable format. whereas, binary is the compact format.
That means compressing the 32 characters (36 or more with separators) to the 16-bit format or back to the human-readable format.
If you dont mind about reading UUID, best is to use binary format
Change VARCHAR to CHAR, this will let you use 16bit.
Old Method
ALTER TABLE myTable ADD COLUMN UUID varchar(36) NOT NULL DEFAULT (UUID());
New Method
ALTER TABLE myTable ADD COLUMN UUID BINARY(36) NOT NULL DEFAULT (UUID_TO_BIN(UUID()));
I am trying to concatenate two integers as the default value in a third field. My create table in SQL Server works fine:
CREATE TABLE MEI_Tbl
(
MEI_ID int PRIMARY KEY IDENTITY (1,1),
SRC tinyint NOT NULL DEFAULT '2',
HEI_ID AS (Cast (SRC as varchar)+ Cast (MEI_ID as varchar))
);
but when I try to create it in MySQL, I cannot find the equivalent for the concatenation of the two integers (Line 5 HEI_ID...).
**
I am aware of changing IDENTITY (1,1) to AUTO_INCREMENT for MySQL.
**
I have also tried several concat methods, but to no avail.
MySQL seems happier if I define the datatype for HEI_ID, and I have done so as varchar and int but again no success.
I have spent too much time reading about tool kits to convert SQL Server to MySQL. I just want to create the table in MySQL.
Any input would be appreciated.
MySQL does not support computed columns. Instead, you can use a view:
CREATE TABLE MEI_Tbl (
MEI_ID int PRIMARY KEY AUTO_INCREMENT,
SRC tinyint NOT NULL DEFAULT 2
);
CREATE VIEW v_MEI_Tbl as
SELECT MEI_ID, SRC,
CONCAT(src, mei_d) as HEI_ID
FROM MEI_Tbl
);
Then query from the view.
I have an application which I am porting from Postgres to MySQL. Nevermind why. The application uses Entity Framework 4 to query the database.
For various reasons, I have to use Guids in my C# code, save them to the database, and then query data based on the saved values of the Guids. I'm not very familiar with MySQL & how it handles what are essentially blobs.
First, there is no UUID type in MySQL. I have to save them as BINARY(16) values. OK, fine. I have created the columns as BINARY(16) and the data is written into the table. Good.
My problem is that I can't see to match on the stored values of the Guids. I have written a unit test that writes data with a known Guid to the table then tries to retrieve it. The data is going into the database fine but when I try to read it back, I get no rows.
Here's a sample table schema:
CREATE TABLE `MyDatabase`.`MyTable` (
`id` INT NOT NULL AUTO_INCREMENT,
`guid` BINARY(16) NOT NULL,
`applicationId` INT(11) NOT NULL,
`name` VARCHAR(256) NOT NULL,
Description VARCHAR(256) NULL,
SessionTimeout INT NOT NULL,
DomainId INT NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT IX_aspnetx_groups UNIQUE ( `applicationId`, `id` )
);
Here's the Entity Framework code:
var g = ( from r in context.MyTable
where r.guid = id
select r ).Single();
Here's the query that's generated by Entity Framework:
SELECT
`Extent1`.`id`,
`Extent1`.`guid`,
`Extent1`.`applicationId`,
`Extent1`.`name`,
`Extent1`.`Description`,
`Extent1`.`SessionTimeout`,
`Extent1`.`DomainId`
FROM `aspnetx_groups` AS `Extent1`
WHERE `Extent1`.`guid` = '81d7de5e-4212-4ff8-b3d4-9f115261971d' LIMIT 2;
When this executes, it returns no rows, resulting in a "sequence contains no elements" exception being thrown in my C# code.
How do I make this work?
In the WHERE clause on your SELECT, it looks like you are comparing a BINARY(16) (guid on the left side of the equals) with a character string literal on the right side.
To perform a valid comparison, I would convert that character string literal into a BINARY(16), and then compare that to guid.
So, removing all the dash characters and then using the UNHEX function should do the trick:
WHERE `Extent1`.`guid` =
UNHEX(REPLACE('81d7de5e-4212-4ff8-b3d4-9f115261971d','-',''))
For performance, you'll want your query to reference the bare guid column on the left side (just like it does), and not wrap the guid column in any sort of functions. You'll want any conversion to be done on the literal side of the predicate, so that the conversion only has to be done once at the beginning of the query, rather than having to do a conversion for each row in the table.
It turns out that the problem I was having had to do with quirks of the Entity Framework connector in the MySQL Connector/Net package. There is a connection string setting that you need to add if you are using BINARY(16) as the data type of your Guids in the database:
Old Guids=True
Once you add that to the connection string, Entity Framework starts to emit code that really works when inserting, updating, or comparing Guids.
I've also come to the conclusion that UUID / Guid support in MySQL is only half-baked and needs some serious work to bring it up to a usable state.
How can I limit my database column's integral input to a specific number of digits ?
CREATE TABLE tab (id INT <1 digit> not null, value INT <10 digits> not null);
Thank you
Add a check constraint (SQL Server) or trigger (MySQL, doesn't support CHECK constraints)
SQL Server example:
CREATE TABLE tab (
id tinynot null CHECK (id BETWEEN 0 AND 9),
value INT not null CHECK (id BETWEEN 1000000000 AND 9999999999)
);
If you only want one digit though, then use tinyint
If you aren't storing numbers (eg "123456789 bananas") but, say, phone numbers then use a varchar type. See https://stackoverflow.com/a/8284674/27535
Edit, you'd need a trigger in MySQL
The short version is using TINYINT UNSIGNED NOT NULL will be a more suitable data type, but it can't limit the values stored.
The longer version is that you may wish to read up on MySQL integer data types. You'll see that TINYINT is sufficient for your purpose as that is a 1-byte column that stores values from -128 to +127, or 0 to +255.
Secondly if you define it as TINYINT(1) then you are defining it as being a TINYINT with a display width of 1 digit. This will not prevent values larger than 10 being stored though. For more reading on this behaviour check numeric type attributes.