mysql table default formula - mysql

In mysql (Ubuntu 13.10, MySql 5.5) I'm trying to create a table that will automatically create a random alphanumeric ID with this code:
create table YGraph (
YGraphEdgeId CHAR(8) NOT NULL PRIMARY KEY DEFAULT SUBSTRING(MD5(RAND()) FROM 1 FOR 8),
YGraphStartVertex CHAR(6) NOT NULL,
YGraphEndVertex CHAR(6) NOT NULL
);
but phpmyadmin is complaining:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SUBSTRING(MD5(RAND()) FROM 1 FOR 8), YGraphStartVertex CHAR(6) NOT NULL, ' at line 2
. . . and putting quotes around the formula only give a generic
#1067 - Invalid default value for 'YGraphEdgeId'
I simply want a new record creation to run the default formula and stick an 8-place random alphanum in the YGraphEdgeId field. I seem to remember this formula working in an INSERT. What am I doing wrong?

Currently you can't use a function to provide a default value for a column, see https://dev.mysql.com/doc/refman/5.5/en/data-type-defaults.html

As per MySQL Documentation on Data Type Default Values
...the default value must be a constant; it cannot be a function or an expression....
Hence you can't use functions or expressions there.
Secondly, you can assign a default string value but it should abide by the length of the column data-type used. String used to define default value was more that 8 characters. And hence the error thrown.

Related

MySQL GENERATED ALWAYS AS ... VIRTUAL syntax error on import

Trying to import table from backup to another server and getting error in SQL syntax
CREATE TABLE IF NOT EXISTS `book` (
`bid` bigint(20) NOT NULL AUTO_INCREMENT,
`bookdate` datetime NOT NULL,
`create_date` datetime NOT NULL,
`bookdate_date` date GENERATED ALWAYS AS (cast(`bookdate` as date)) VIRTUAL,
`create_date_date` date GENERATED ALWAYS AS (cast(`create_date` as date)) VIRTUAL,
PRIMARY KEY (`bid`),
KEY `IDX_book_bookdate_date` (`bookdate_date`),
KEY `IDX_book_create_date_date` (`create_date_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=316;
phpMyAminError
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GENERATED ALWAYS AS (cast(`bookdate` as date)) VIRTUAL,
`create_date_date` da' at line 5
How do i fix import error? I dont know what this means its beyond my paygrade
`bookdate_date` date GENERATED ALWAYS AS (cast(`bookdate` as date)) VIRTUAL,
`create_date_date` date GENERATED ALWAYS AS (cast(`create_date` as date)) VIRTUAL,
Those are generated columns. They are set automatically, so you cannot assign values in an insert or update. These were introduced in some version of MySQL 5.7, so older versions do not support them. You can replace the idea using views, for similar functionality.
They are calculated -- using the expression -- when the table is queried. This is convenient, because the value is always correct. The VIRTUAL means that the column value is not stored in the table.
The alternative to VIRTUAL is STORED. That calculates the value once when the row is inserted or updated. It uses up storage space but can be convenient if the calculation is expensive.
EDIT:
Based on your comment, you have a problem. One method is to create a view but that can be tricky. Assuming that existing code is referencing the columns, your best best is to define the generated columns as regular columns and use triggers (insert and update) to set them.

How to fix syntax error when escaping table name? [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 2 years ago.
CREATE TABLE 'test'.'sensor' (
'id' INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
'time' TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
'value' VARCHAR( 10 ) NOT NULL
);
This is my code which I entered in phpMyAdmin. And when I pressed go I got the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''test'.'sensor' (
'id' INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
'time' TIMES' at line 1
I have tried changing some statements but couldn't get the error.
MySQL uses backticks to escape identifiers, single and double quotes for strings.
In this case you should do:
CREATE TABLE `test`.`sensor` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`value` VARCHAR( 10 ) NOT NULL
);
It's worth noting that backticks are only strictly required when your name conflicts with a reserved keyword and even then many are only relevant in a specific context. Terms like ORDER or SELECT always need to be escaped, so using them for columns or table names is best avoided. Likewise, TIME is also a column type, so you may want to pick a different name.
Additionally the TIMESTAMP column type is quite limited, values can only exist in the range of 1970 to 2038, so using it is not recommended. The DATETIME type by comparison has a range of years 1000 to 9999, more than adequate for most needs. There's a few other quirks of TIMESTAMP worth keeping in mind, too, like automatic UTC conversion.
Check that which version of php and MySQL u are using i have face this problem but solved after research . this query is working on MySQL 5.5 or newer
and MariaDB 5.5 or newer
CREATE TABLE Ghee(
country_code char(1) NOT NULL default '',
description varchar(10) NOT NULL default '',
PRIMARY KEY (country_code)
)

SQL Column Names same as names for data types - causing errors

I am very new to SQL and having problems with creating a table structure.
I want to create a table with four columns - id,text,date and replace. Problem is this is giving me an error in MySQL, I think because the words TEXT and DATE are also names for data types and REPLACE is another term used in SQL so MySQL is getting confused about what my column names should be or doesn't realise the names I've given are actual names. Is there any way I can get around this to get the column names I want, without having to call the columns something else and then change them back manually once created?
Here's my SQL:
CREATE TABLE message (
id INT UNIQUE AUTO_INCREMENT NOT NULL,
text TEXT,
date INT,
replace INT DEFAULT 0
);
And the error I'm getting:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'replace INT DEFAULT 0 )' at line 5
CREATE TABLE message(
id INT UNIQUE AUTO_INCREMENT NOT NULL ,
TEXT TEXT,
DATE INT,
REPLACE INT DEFAULT 0
);
CREATE TABLE message (
`id` INT UNIQUE AUTO_INCREMENT NOT NULL,
`text` TEXT,
`date` INT,
`replace` INT DEFAULT 0
);
General rule is don't use these keywords, come up with something different than 'text' for your field name. If you must, use ` (back-tick) around the column name to tell SQL it's a column name and not what the keyword means. I recommend against calling your columns 'from' 'select' and 'where' as well ;)

Cannot use functions and variables in DEFAULT constraint when creating a new database table

I'm trying to create a new database using the CREATE command. Here's the SQL:
CREATE TABLE test(
rok_utworzenia timestamp DEFAULT CURRENT_DATE
);
But it throws an error saying
'#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CURRENT_DATE )' at line 2'
It works if I change the DEFAULT constraint to a constant, but not if I try to use any function or variable. Why is that so?
Use this:
CREATE TABLE test( rok_utworzenia timestamp DEFAULT CURRENT_TIMESTAMP );
From MySQL site:
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.
Try this CURRENT_TIMESTAMP:
CREATE TABLE test( rok_utworzenia timestamp DEFAULT CURRENT_TIMESTAMP );

Define default date value in MySQL, similar to timestamp

I'm using MySQL (nobody's perfect), version 4.1 and I'm used to define some timestamp columns like that:
ALTER TABLE foo ADD creation TIMESTAMP DEFAULT NOW() ;
I'd like to do exactly the same thing, but for a DATE field. The reason being I don't need a TIMESTAMP precision and since no functional index exists in MySQL, I cannot access quickly to the rows with a given date (regardless of time of day). So I tried the following but it just does not work:
ALTER TABLE foo ADD creation_date DATE DEFAULT CURDATE() ;
ERROR 1067 (42000): Invalid default value for 'creation_date'
Or even
ALTER TABLE foo ADD creation_date DATE DEFAULT DATE(NOW()) ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(now())' at line 1
Which does not work either.
Any Ideas?
In MySQL default values have to be constant.
Functions or expressions are not allowed.
The exception ist the TIMESTAMP type, for which CURRENT_TIMESTAMP is a valid non constant default value.
See 4.1 manual: Data Type Default Values