Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash of two columns in mysql

Tags:

mysql

I have a MYSQL table, with 5 columns in it:

id bigint
name varchar
description varchar
slug

Can I get MySQL to automatically generate the value of slug as a 256 Bit Hash of name+description?

I am now using PHP to generate an SHA256 value of the slug prior to saving it.

Edit:

By automatic, I mean see if it's possible to change the default value of the slug field, to be a computed field that's the sha256 of name+description.

I already know how to create it as part of an insert operation.

like image 763
EastsideDev Avatar asked Aug 02 '16 23:08

EastsideDev


People also ask

What is hash function in MySQL?

The MySQL SHA1() function is used for encrypting a string using the SHA-1 technique. The SHA1 stands for secure hash algorithm and it produces a 160-bit checksum for a user inputted string. The MySQL SHA1() function returns NULL if the string passed as an argument is a NULL string.

What is HASH Partitioning in MySQL?

HASH partitioning. With this type of partitioning, a partition is selected based on the value returned by a user-defined expression that operates on column values in rows to be inserted into the table. The function may consist of any expression valid in MySQL that yields an integer value.

Can have indexes on multiple columns in MySQL?

MySQL can use multiple-column indexes for queries that test all the columns in the index, or queries that test just the first column, the first two columns, the first three columns, and so on.


2 Answers

MySQL 5.7 supports generated columns so you can define an expression, and it will be updated automatically for every row you insert or update.

CREATE TABLE IF NOT EXISTS MyTable (
  id int NOT NULL AUTO_INCREMENT,
  name varchar(50) NOT NULL,
  description varchar(50) NOT NULL,
  slug varchar(64) AS (SHA2(CONCAT(name, description), 256)) STORED NOT NULL,
  PRIMARY KEY (id)
) DEFAULT CHARSET=utf8;

If you use an earlier version of MySQL, you could do this with TRIGGERs:

CREATE TRIGGER MySlugIns BEFORE INSERT ON MyTable
FOR EACH ROW SET slug = SHA2(CONCAT(name, description));

CREATE TRIGGER MySlugUpd BEFORE UPDATE ON MyTable
FOR EACH ROW SET slug = SHA2(CONCAT(name, description), 256);
like image 106
Bill Karwin Avatar answered Oct 11 '22 16:10

Bill Karwin


Beware that concat returns NULL if any one column in the input is NULL. So, to hash in a null-safe way, use concat_ws. For example:

select md5(concat_ws('', col_1, .. , col_n));
like image 36
Slawomir Avatar answered Oct 11 '22 16:10

Slawomir