MySQL issue with altering column to add default - mysql

I have a table named Users with a column call created. Whenever a record is created I want to add the datetime.
Users Table:
CREATE TABLE `Users` (
`userId` int(11) unsigned NOT NULL AUTO_INCREMENT,
`fullName` varchar(50) DEFAULT NULL,
`firstName` varchar(25) NOT NULL DEFAULT '',
`lastName` varchar(25) NOT NULL DEFAULT '',
`address` varchar(50) NOT NULL DEFAULT '',
`city` varchar(25) DEFAULT NULL,
`state` char(2) DEFAULT NULL,
`zipCode` varchar(25) DEFAULT NULL,
`email` varchar(50) NOT NULL DEFAULT '',
`cellPhone` varchar(15) DEFAULT NULL,
`birthDate` date NOT NULL,
`creditCard` varchar(250) NOT NULL DEFAULT '',
`subscriptionStarted` date NOT NULL,
`subscriptionEnded` date NOT NULL,
`basicPlan` tinyint(1) DEFAULT NULL,
`standardPlan` tinyint(1) DEFAULT NULL,
`premiumPlan` tinyint(1) DEFAULT NULL,
`staff` tinyint(1) DEFAULT NULL,
`admin` tinyint(1) DEFAULT NULL,
`systemAdmin` tinyint(1) DEFAULT NULL,
`edited` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=latin1;
now i added this extra query to make my created field get the current datetime when a new record is created.
ALTER TABLE Users
ALTER COLUMN created SET DEFAULT CURRENT_TIMESTAMP
The problem is that I get the following error when running the alter table query
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_TIMESTAMP' at line 2

Your syntax is slightly off, I think you have to specify the column to change:
ALTER TABLE Users CHANGE created created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
See this sample SQL Fiddle for an example.

Related

Createdatetime columns is populating as 0000-00-00

I have created one table and inserting values in the table from a csv file using a python code .The createdatetime and updatedatetime columns are set to default CURRENT_TIMESTAMP.But when I am populating the data updatedatetime is populating the correct value but createdatetime is populating as 0000-00-00 00:00:00.
Here is my table definition:
CREATE TABLE `fico_details` (
`adf_contact_id` varchar(100) NOT NULL,
`sf_contact_id` varchar(100) DEFAULT NULL,
`Name` varchar(100) NOT NULL,
`BirthDate` date DEFAULT NULL,
`Address1` varchar(100) DEFAULT NULL,
`City` varchar(100) DEFAULT NULL,
`State` varchar(2) DEFAULT NULL,
`Zipcode` varchar(10) DEFAULT NULL,
`SSN` varchar(10) DEFAULT NULL,
`Address2` varchar(100) DEFAULT NULL,
`City2` varchar(100) DEFAULT NULL,
`State2` varchar(2) DEFAULT NULL,
`Zipcode2` varchar(10) DEFAULT NULL,
`Customerinput` varchar(10) DEFAULT NULL,
`AddrDiscrepancyFlg` varchar(10) DEFAULT NULL,
`Permid` varchar(10) DEFAULT NULL,
`score_date` varchar(10) DEFAULT NULL,
`reason_code_1` varchar(10) DEFAULT NULL,
`reason_code_2` varchar(10) DEFAULT NULL,
`reason_code_3` varchar(10) DEFAULT NULL,
`reason_code_4` varchar(10) DEFAULT NULL,
`CreateDateTime` TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP,
`UpdateDateTime` TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP,
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `SSN` (`SSN`)
) ENGINE=InnoDB AUTO_INCREMENT=876800 DEFAULT CHARSET=utf8;
please help me to solve it.
I am working on same thing these days.
First of all I use timestamp as the datatype as apart from having datetime capabilities, it has MANY usable functions as a string as well as timestamp datatype.
I got the SAME issue as yours, what I did was alter my table was created, I would click on ALTER table using any Db tool (SQLYog in my case) and then Delete the 0000-00-00 00:00:00 value and uncheck the Not NULL check box.
This issue gets resolved EVERYTIME (whenever I create same type of table/columns)after this simple one step.
Hope this helps you too, let me know if anything still bothers you....!!

Not getting expected Output while trying to alter a column default value

Problem:
I have created a table with a given structure:
CREATE TABLE `X` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`MSISDN` varchar(25) DEFAULT NULL,
`subservice_id` varchar(25) DEFAULT NULL,
`SUB_START_DATE` datetime DEFAULT NULL,
`START_DATE` datetime DEFAULT NULL,
`END_DATE` datetime DEFAULT NULL,
`scheduler_renewal_status` varchar(25) NOT NULL DEFAULT 'scheduled',
`STATUS` varchar(20) DEFAULT NULL,
`LAST_RENEW_DATE` datetime DEFAULT NULL,
`LAST_CALL_DATE` datetime DEFAULT NULL,
`TRANSACTION_STATUS` varchar(15) DEFAULT NULL,
`CIRCLE` varchar(3) DEFAULT NULL,
`COUNTRY` varchar(3) DEFAULT NULL,
`LANGUAGE` varchar(3) DEFAULT NULL,
`price` float DEFAULT '0',
`CALL_ATTEMPTS` int(3) DEFAULT NULL,
`PRIMARY_ACT_MODE` varchar(25) DEFAULT NULL,
`SECONDARY_ACT_MODE` varchar(25) DEFAULT NULL,
`ERROR_MSG` varchar(25) DEFAULT NULL,
`SUB_TYPE` varchar(10) DEFAULT NULL,
`SUB_TIME_LEFT` int(3) DEFAULT '0',
`SUB_SERVICE_NAME` varchar(25) DEFAULT NULL,
`OPERATOR` varchar(25) DEFAULT NULL,
`GIFT_ID` varchar(25) DEFAULT NULL,
`service_id` varchar(25) DEFAULT NULL,
`RETRY_COUNT` int(2) NOT NULL DEFAULT '0',
`NEXT_RETRY_DATE` datetime DEFAULT NULL,
`CPID` int(11) DEFAULT NULL,
`SCHEDULER_RETRY_STATUS` varchar(25) DEFAULT 'scheduled',
`scheduler_statechanger_status` varchar(25) DEFAULT 'scheduled',
`scheduler_subs_msgs_status` varchar(25) DEFAULT 'scheduled',
`serviceName` varchar(25) DEFAULT NULL,
`transactionId` varchar(25) DEFAULT NULL,
`nextAction` varchar(25) DEFAULT NULL,
`topUpPrice` int(3) DEFAULT NULL,
`topUp_time_left` int(5) NOT NULL DEFAULT '0',
`autoRenew` varchar(10) DEFAULT NULL,
`option1` varchar(25) DEFAULT NULL,
`callBackRecvFlag` varchar(10) DEFAULT NULL,
`last_msg_date` date DEFAULT NULL,
`accountType` varchar(10) DEFAULT 'prepaid',
`optkey` varchar(20) DEFAULT NULL,
`successCallCount` int(3) DEFAULT '0',
PRIMARY KEY (`ID`),
UNIQUE KEY `UK_3` (`MSISDN`,`subservice_id`)
) ENGINE=InnoDB AUTO_INCREMENT=27793 DEFAULT CHARSET=utf8
I want to change the column SUB_START_DATE default type from NULL to TIMESTAMP.
Can anyone guide me the proper syntax for this
Solution:
I am running the following Command:
ALTER TABLE `X` MODIFY COLUMN SUB_START_DATE TIMESTAMP NOT NULL DEFAULT current_timestamp;
It is affecting the rows of the table.
But,if I want to have column datatype datetime only and change the default value to current_timestamp.
I ran the following command:
ALTER TABLE `X` MODIFY COLUMN SUB_START_DATE datetime DEFAULT current_timestamp;
OutputShown:
Error Code : 1067
Invalid default value for 'SUB_START_DATE'
In this case my SQL server does not allow to modify existing default constraint value. So to change the default value we need to delete the existing system generated or user generated default constraint. And after that default value can be set for a particular column.
Follow some steps :
List all existing default value constraints for columns.
Execute this system database procedure, it takes table name as a parameter. It returns list of all constrains for all columns within table.
execute [dbo].[sp_helpconstraint] 'table_name'
Drop existing default constraint for a column.
Syntax:
alter table 'table_name' drop constraint 'constraint_name'
Add new default value constraint for that column:
Syntax:
alter table 'table_name' add default 'current_timestamp' for 'SUB_START_DATE '

database error invalid values

i am getting error in my database. i am encountering invalid default value for timestamp. how can i fix this.
here's my database:
CREATE TABLE IF NOT EXISTS `thread` (
`id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`dateCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`userId` int(11) NOT NULL,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`categoryId` int(11) NOT NULL,
`view` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
`fullname` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`username` varchar(60) NOT NULL,
`password` varchar(60) NOT NULL,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`profileUrl` varchar(200) NOT NULL DEFAULT 'https://mymonas.com/forum/img/nophoto.png',
`profileBg` varchar(200) NOT NULL,
`dateCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`aboutMe` varchar(500) NOT NULL,
`isModerator` tinyint(4) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;
My guess is you're running MySQL 5.5. If that's the case, you can't use CURRENT_TIMESTAMP with DATETIME. DATETIME has to have a default of null or no default value. You can, however, change them to TIMESTAMP, but then you can only have one default and one ON UPDATE per table. You can also use a post-insert trigger to fill in a NOW() value on new records. Here's the docs to help.
use TIMESTAMP instead of datetime
This may be helpful.

MySQL delete data without query?

I have a client that is describing an occurrence when they are adding new data from a web form. If the submitted data matches any existing database entries, the system deletes the existing entry.
I've checked the scripts and I don't see a DELETE query that would affect the related table. There are UPDATE queries, none of which affect a field in the DB indicating a deletion or marked as deleted.
Are there ways data could be lost without the execution of a DELETE query?
As asked for, here's the "create table" statement:
CREATE TABLE `msp_zip_codes`
(
`zip_code` varchar(5) DEFAULT NULL,
`city` varchar(35) DEFAULT NULL,
`state_prefix` varchar(2) DEFAULT NULL,
`county` varchar(45) DEFAULT NULL,
`area_code` varchar(45) DEFAULT NULL,
`CityType` varchar(1) DEFAULT NULL,
`CityAliasAbbreviation` varchar(13) DEFAULT NULL,
`CityAliasName` varchar(35) DEFAULT NULL,
`lat` decimal(18,6) DEFAULT NULL,
`lon` decimal(18,6) DEFAULT NULL,
`time_zone` varchar(7) DEFAULT NULL,
`Elevation` int(10) DEFAULT NULL,
`CountyFIPS` varchar(5) DEFAULT NULL,
`DayLightSaving` varchar(1) DEFAULT NULL,
`PreferredLastLineKey` varchar(25) DEFAULT NULL,
`ClassificationCode` varchar(2) DEFAULT NULL,
`MultiCounty` varchar(1) DEFAULT NULL,
`StateFIPS` varchar(2) DEFAULT NULL,
`CityStateKey` varchar(6) DEFAULT NULL,
`CityAliasCode` varchar(5) DEFAULT NULL,
`PrimaryRecord` varchar(50) DEFAULT NULL,
`CityMixedCase` varchar(50) DEFAULT NULL,
`CityAliasMixedCase` varchar(50) DEFAULT NULL,
KEY `AreaCode` (`area_code`),
KEY `CityAliasCode` (`CityAliasCode`),
KEY `CityStateKey` (`CityStateKey`),
KEY `ClassificationCode` (`ClassificationCode`),
KEY `PreferredLastLineKey` (`PreferredLastLineKey`),
KEY `ZipCode` (`zip_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
One of the possibilities is that the table has an UPDATE TRIGGER set which fires every time there's an update. Or the other one, there's an Event Scheduler running on the server.
Code to show all triggers on the database:
SELECT *
FROM INFORMATION_SCHEMA.TRIGGERS a
WHERE a.TRIGGER_SCHEMA LIKE CONCAT('%', 'databaseNameHERE', '%')
Code to show all events on the database:
SHOW EVENTS FROM databaseNameHERE;

why Mysql is giving me error 1280 "Wrong Index"

Can anyone explain why Mysql is giving me error 1280 ("wrong index for 'fk_chart_aid_aid' ") error whend I try to create the "CHART OF ACCOUNTS" table. I'm completly confused here. How can I fix this so I can create the table? The "ACCOUNT" table already exists in the database and has data in it.
Thanks for the help.
MYSQL Server version: 5.1.54
CHART OF ACCOUNTS:
DROP TABLE IF EXISTS `rst`.`acctg_chart_of_accounts` ;
CREATE TABLE IF NOT EXISTS `rst`.`acctg_chart_of_accounts` (
`acctg_chart_of_accounts_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`account_id` INT UNSIGNED NOT NULL ,
`account_nbr` VARCHAR(45) NULL ,
`description` VARCHAR(45) NULL ,
`account_type` INT UNSIGNED NULL ,
`commissionable` TINYINT UNSIGNED NULL ,
`hidden` TINYINT UNSIGNED NULL ,
`deduct_balance_from_owner_check` TINYINT UNSIGNED NULL ,
PRIMARY KEY (`acctg_chart_of_accounts_id`) ,
CONSTRAINT `fk_chart_aid_aid`
FOREIGN KEY (`account_id` )
REFERENCES `rst`.`account` (`account_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE INDEX `fk_chart_aid_aid` ON `rst`.`acctg_chart_of_accounts` (`account_id` ASC) ;
ACCOUNTS TABLE THAT IS BEING REFERENCED:
CREATE TABLE IF NOT EXISTS `account` (
`account_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`account_status_id` int(10) unsigned NOT NULL,
`company_name` varchar(155) DEFAULT NULL,
`address1` varchar(155) DEFAULT NULL,
`address2` varchar(155) DEFAULT NULL,
`city` varchar(155) DEFAULT NULL,
`state` varchar(155) DEFAULT NULL,
`zip` varchar(45) DEFAULT NULL,
`country` varchar(255) DEFAULT NULL,
`work_phone` varchar(45) DEFAULT NULL,
`mobile_phone` varchar(45) DEFAULT NULL,
`time_zone` varchar(45) DEFAULT NULL,
`subdomain` varchar(155) DEFAULT NULL,
`cname_URL` varchar(255) DEFAULT NULL,
`promotion_code` varchar(45) DEFAULT NULL,
`can_we_contact_you` tinyint(4) DEFAULT NULL COMMENT '0=false, 1=true',
`units_managed_nbr` varchar(10) DEFAULT NULL,
`a_hear_about_us_list_id` tinyint(3) unsigned DEFAULT NULL COMMENT 'populated from dropdown list.',
`receive_special_offers` tinyint(4) DEFAULT NULL,
`receive_announcements` tinyint(4) DEFAULT NULL,
`receive_newsletter` tinyint(4) DEFAULT NULL,
`create_ts` timestamp NULL DEFAULT NULL,
`expires` timestamp NULL DEFAULT NULL,
`storage_capacity` varchar(255) DEFAULT NULL COMMENT '1073741824 = 1GB',
`logo` varchar(455) DEFAULT NULL,
`max_active_connections` int(11) DEFAULT '3',
`_product_id` int(11) DEFAULT NULL,
`report_footer` varchar(455) DEFAULT NULL,
`welcome_dialog` tinyint(4) DEFAULT '1',
`ARB_subscription_id` int(11) DEFAULT NULL,
`trashbin` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`account_id`),
KEY `fk_account_account_status_id` (`account_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=58 ;
Are you getting the error after the CREATE TABLE statement, or after the subsequent CREATE INDEX?
Looks like you are attempting to name both a FOREIGN KEY constraint and an INDEX fk_chart_aid_aid. Try choosing a different name for either one of them.
Also, in the accounts table, account_id is INT(10). Try also to change the column definition in acctg_chart_of_accounts to:
`account_id` INT(10) UNSIGNED NOT NULL ,
Though, I think that mysql defaults type INT to INT(10) anyway...
I met the same issue; tried manually rename the index to a different name but don't like the idea of 'manually' and neither I don't really understand why we need to generate the index separately. so I decide to generate it within the create statement by unchecking the option of 'generate separate index statement' in 'forwarding engineer', and this fix the issue.