Date syntax CHECK constraint in CREATE TABLE - mysql

I am creating the table in SQLite and want to CHECK the syntax of the date. It should be 'YYYY-MM-DD'. When I insert data into this table it should give me error when I type something else when inserting the date, e.g. Insert into Member(DoB) values('2013-120qw'). It should be only for instance '2013-12-04'.
Here is my table:
CREATE TABLE Member(
email VARCHAR(100) NOT NULL,
name VARCHAR(100) NOT NULL,
DoB TEXT(10) NOT NULL CHECK (length(DoB) IN (10) AND date(DoB) BETWEEN date('1900-01-01') AND date(CURRENT_DATE)),
telephone VARCHAR(11) NOT NULL CHECK (length(telephone) IN (11)),
PRIMARY KEY (email)
);

The problem is that date() returns NULL for invalid date strings, and NULL does not make the check constraint fail.
Add a separate check that date() is happy:
...
DoB TEXT(10) NOT NULL CHECK (date(DoB) IS NOT NULL AND
length(DoB) = 10 AND
DoB BETWEEN '1900-01-01' AND CURRENT_DATE),
...

i thank DATE type is useful because MySql doesn't have Constraints
CREATE TABLE Member(
email VARCHAR(100) NOT NULL,
name VARCHAR(100) NOT NULL,
DoB date NOT NULL,
telephone VARCHAR(11) NOT NULL CHECK (length(telephone) IN (11)),
PRIMARY KEY (email)
);
if you need help this link will help you
https://dev.mysql.com/doc/refman/5.0/en/datetime.html

Related

Type date default sysdate in Mysql

I have seen this question before but it is not answered, so here it goes:
When creating a table, I have a column with the type Date. I want that the default value is the system date, (Sysdate), but for some reason it does not work and it gives an error (in syntax, which is strange because I am following the Mysql syntax).
create table students(
id integer(10),
name varchar (21) NOT NULL,
surname varchar(30),
grade integer check(grade in(1,2,3),
enrollment date default sysdate,
primary key(id) );
And it gives an error in syntax just at the "sysdate". I have tried with sys_date, sys-date, and it is the same.
Instead of sysdate, try CURRENT_TIMESTAMP like:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)

MySQL - add data into 2 tables and 1 has foreign key

I'm a totally MySQL newcomer. Sr if my question is quite obvious. I got 2 tables
CREATE TABLE tbl_addresses(
PK_ADDRESS_ID int NOT NULL AUTO_INCREMENT,
house_number int NOT NULL,
street varchar(35),
district varchar(35),
city varchar(35),
postcode varchar(8),
PRIMARY KEY (PK_ADDRESS_ID)
);
CREATE TABLE tbl_people(
PK_PERSON_ID int NOT NULL AUTO_INCREMENT,
title varchar(6) NOT NULL, # Master / Mister therefor 6 is max
forename varchar(35) NOT NULL,
surname varchar(35) NOT NULL,
date_of_birth DATE NOT NULL,
contact_number varchar(12) NOT NULL,
FK_ADDRESS_ID int NOT NULL,
PRIMARY KEY (PK_PERSON_ID),
FOREIGN KEY (FK_ADDRESS_ID) REFERENCES tbl_addresses (PK_ADDRESS_ID)
);
and I'm trying to import data into these tables from Java using below syntaxes
INSERT INTO tbl_addresses (house_number,street,district,city,postcode) VALUES ('1','abc','','abc','abc');
INSERT INTO tbl_people (title,forename,surname,date_of_birth,contact_number) VALUES ('Mr','Tri ','Nguyen','1991-1-1','0123456789');
I got an error Field 'FK_ADDRESS_ID'doesn't have a default value and data actually goes into tbl_addresses but not tbl_people. Am I missing anything? Thanks in advance!
This error is being caused by that you labelled the FK_ADDRESS_ID field in the tbl_people table as NOT NULL, yet you are trying to do an INSERT without specifying a value for this column.
So something like this would work without error:
INSERT INTO tbl_people (title, forename, surname, date_of_birth,
contact_number, FK_ADDRESS_ID)
VALUES ('Mr', 'Tri', 'Nguyen', '1991-1-1', '0123456789', 1);
You could also specify a default value for FK_ADDRESS_ID (the error message you got alluded to this). Here is how you could adda default value:
ALTER TABLE tbl_people MODIFY COLUMN FK_ADDRESS_ID int NOT NULL DEFAULT 1
But because FK_ADDRESS_ID is a key into another table, the value should really be based on the primary key in tbl_addresses.
The fact that you are using a foreign key isn't the reason that you are getting this error. Let's take a look at your column definition.
FK_ADDRESS_ID int NOT NULL,
This is not null but does not a default. Now a look at your insert statement
INSERT INTO tbl_people (title,forename,surname,date_of_birth,contact_number)
FK_ADDRESS_ID isn't in your column list but it cannot be null and doesn't have a default so what can mysql do? Produce an error of course.
The best bet is to define that column as nullable.
Let's revisit the foreign key constraint.
FOREIGN KEY (FK_ADDRESS_ID) REFERENCES tbl_addresses (PK_ADDRESS_ID)
What this really says is that if you asign a value to FK_ADDRESS_ID that value should be present in PK_ADDRESS_ID column in tbl_address
as a side note, it's customary to use lower case for table/column names.

What does this error mean? SQL Error: ORA-02270: no matching unique or primary key for this column-list

I keep getting the error code 'ORA-02270' and no matter what I try, I can't seem to fix it. Below are my Create Table statements:
CREATE TABLE student
(
studentID CHAR(8) PRIMARY KEY,
studentName VARCHAR(25) NOT NULL,
studentAddress VARCHAR(30) NOT NULL,
studentDOB DATE NOT NULL,
studentGender CHAR(1) NOT NULL CHECK ((studentGender = 'F') OR (studentGender = 'M')),
studentNationality VARCHAR(15) NOT NULL,
studentCourse VARCHAR(30) NOT NULL,
studentSemesterExcellent CHAR(1) NOT NULL CHECK ((studentSemesterExcellent = 'Y') OR (studentSemesterExcellent = 'N'))
);
CREATE TABLE leaseAgreement
(
leaseNo CHAR(6) PRIMARY KEY,
studentID CHAR(8) NOT NULL,
leaseAccommodationType VARCHAR2(10) NOT NULL,
leaseDuration NUMBER NOT NULL,
leaseStartDate DATE NOT NULL,
leaseEndDate DATE,
studentSemesterExcellent CHAR(1) NOT NULL CHECK ((studentSemesterExcellent = 'Y') OR (studentSemesterExcellent = 'N')),
FOREIGN KEY (studentID) REFERENCES student(studentID),
FOREIGN KEY (studentSemesterExcellent) REFERENCES student(studentSemesterExcellent)
);
Am I not allowed to have two foreign keys from the same table? Please can someone explain this error and point me in the right direction. Thank you.
First, the answer from mustaccio is correct.
The column 'studentSemesterExcellent' in table 'student' is no key column. You can not reference it in a foreign key constraint.
And if you make it unique you can only have two rows in the student table, not what you are intending.
Second, you have tagged the question both with MySQL and Oracle. Choose one!
Third, you only need one FK if it is a not null column. Don't make it harder on yourself.
Fourth, if this is Oracle database, the advice is to only use varchar2() for string data. The char and varchar datatypes exist for compatibility reasons.

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I'm new to PHP and MySQL and ran into a little trouble with a learning project I'm working on.
Whenever I try to create a table
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10) NOT NULL,
type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
)
I get the following error message:
#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 ') NOT NULL, type varchar(6) NOT NULL, notes varchar(512),
receipt int(10), ' at line 6**
Here is some info on what I'm working with
Server type: MySQL
Server version: 5.5.32 - MySQL Community Server(GPL)
phpMyAdmin: 4.0.4.1, latest stable version: 4.1.7
I've spent a day knocking my head against the wall over this and now I think its time to ask for help.I was wondering if anyone can tell me what I'm doing wrong?
Remove the comma
receipt int(10),
And also AUTO INCREMENT should be a KEY
double datatype also requires the precision of decimal places so right syntax is double(10,2)
One obvious thing is that you will have to remove the comma here
receipt int(10),
but the actual problem is because of the line
amount double(10) NOT NULL,
change it to
amount double NOT NULL,
In MySQL, the word 'type' is a Reserved Word.
I see two problems:
DOUBLE(10) precision definitions need a total number of digits, as well as a total number of digits after the decimal:
DOUBLE(10,8)
would make be ten total digits, with 8 allowed after the decimal.
Also, you'll need to specify your id column as a key :
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id) );
I've faced this problem before, the reason behind that for me was the last comma in the schema definition should be deleted if there's no extra columns would be added.
CREATE TABLE users
(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL, // this comma should be deleted
);
Rule 1: You can not add a new table without specifying the primary key constraint[not a good practice if you create it somehow].
So the code:
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id));
Rule 2: You are not allowed to use the keywords(words with predefined meaning) as a field name.
Here type is something like that is used(commonly used with Join Types).
So the code:
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
transaction_type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id));
Now you please try with this code.
First check it in your database user interface(I am running HeidiSQL, or you can try it in your xampp/wamp server also)and make sure this code works. Now delete the table from your db and execute the code in your program.
Thank You.

Inserting into a view with an auto increment primary key?

I have a table horse and a view view_horse that selects every column from the horse table except the primary key (primary key is auto-increment integer) and then presents it to the user, I want to insert data into that views underlying table and naturally expect the primary key to be automatically generated. But I keep getting an SQL exception stating "field of view view_horse underlying doesn't have a default value" when I try to insert any data into it.
EDIT -
CREATE TABLE IF NOT EXISTS `TRC`.`horse` (
`horse_id` INT NOT NULL AUTO_INCREMENT,
`registered_name` VARCHAR(20) NOT NULL,
`stable_name` VARCHAR(20) NOT NULL,
`horse_birth_year` DATE NOT NULL,
`horse_height` DECIMAL(3,1) NOT NULL,
`horse_location` VARCHAR(50) NOT NULL DEFAULT 'TRC',
`arrival_date` DATE NOT NULL,
`passport_no` MEDIUMTEXT NULL,
`is_deceased` TINYINT(1) NOT NULL,
`arrival_weight` DECIMAL NOT NULL,
`horse_sex` VARCHAR(8) NOT NULL,
`microchip_no` VARCHAR(15) NULL,
`date_of_death` DATE NULL,
PRIMARY KEY (`horse_id`),
INDEX `fk_Horses_SexLookup1_idx` (`horse_sex` ASC),
CONSTRAINT `fk_Horses_SexLookup1`
FOREIGN KEY (`horse_sex`)
REFERENCES `TRC`.`lookup_sex` (`sex`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
USE `TRC`;
CREATE OR REPLACE VIEW `TRC`.`view_horse` AS SELECT
registered_name AS 'Registered Name',
stable_name AS 'Stable Name',
horse_birth_year AS 'Age',
horse_height AS 'Height',
arrival_weight AS 'Weight on Arrival',
horse_sex AS 'Sex',
horse_location AS 'Location',
arrival_date AS 'Date of Arrival',
passport_no AS 'Passport no.',
microchip_no AS 'Microchip no.',
is_deceased AS 'Alive?'
FROM `horse`;
If I insert into the view without specifying the columns it actually completes ok. But not when I give the columns as specified in the view.
You're not trying to INSERT into the actual VIEW are you? Insert into the TABLE, and SELECT from the VIEW.
Edit. Forget it; thanks for the correction Strawberry.
Here's a fiddle that illustrates inserting into the view: http://sqlfiddle.com/#!2/280aa6/1/0