MySQL Create Table with Unique Constraints - mysql

I am just starting with SQL syntax, and am trying to create a table.
Here is my error:
#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 'CONSTRAINT uc_people_2nd UNIQUE (lastName,firstName), ) ENGINE = INNODB' at line 7
And here is my SQL:
CREATE TABLE `people` (
`_id` INT NOT NULL AUTO_INCREMENT,
`lastName` TEXT NOT NULL,
`firstName` TEXT NOT NULL,
`JSON` TEXT NOT NULL,
PRIMARY KEY(_id)
CONSTRAINT uc_people_2nd UNIQUE (lastName,firstName),
) ENGINE = INNODB;
I tried this in NodeDB (which I am developing in), and then PHPMyAdmin.

Fix the comma and make the names varchar():
CREATE TABLE `people` (
`_id` INT NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) NOT NULL,
`firstName` varchar(255) NOT NULL,
`JSON` TEXT NOT NULL,
PRIMARY KEY(_id),
CONSTRAINT uc_people_2nd UNIQUE (lastName, firstName)
) ENGINE = INNODB;
This works on SQL Fiddle.
Note that you don't have to give a unique constraint a name. You can also drop the constraint keyword, so the following works just fine:
UNIQUE (lastName, firstName)
EDIT:
The text data type is described here on the page with other "large-objects". These are special types that are arbitrarily long (think megabytes). They have limits when used in indexes. In particular, they need a length prefix. So, you cannot declare that a text column is unique. Only that they are unique in the first N characters (up to about 1000).
For names, that is way overkill. MySQL supports string types of various sorts. The most useful is varchar(). These are appropriate for a name field. They can be used with indexes easily. And MySQL supports a plethora of functions on them.
In other words, if you do not know what text is, you do not need it. Learn about and use varchar() and char() (or nvarchar() and nchar() if you need national character set support). Forget about text. One day if you need it, you'll rediscover it.

Related

SQL query syntax error while creating a table

I am getting a SQL query syntax error while creating a table. Here is the SQL query:
CREATE TABLE ACCOUNT (
ACCNO NUMBER(5) NOT NULL,
NAME VARCHAR(20) NOT NULL,
BA L NUMBER(8,2) NOT NULL,
CREATION-DT DATE NOT NULL,
PRIMARY KEY ( ACCNO )
);
Here is the error:
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 'NUMBER(5) NOT NULL.
What is wrong with my syntax?
Using SQLfiddle you can see this is not valid.
You have multiple problems with your syntax; invalid data types, invalid column names, etc. You can encapsulate the invalid names in backticks but then you will have to remember to encapsulate them later.
Instead of Number you probably meant numeric but i would suggest trying Integer instead.
Or just try this:
CREATE TABLE ACCOUNT (
ACCNO INTEGER(5) NOT NULL,
NAME VARCHAR(20) NOT NULL,
BAL INTEGER(8) NOT NULL,
CREATIONDT DATE NOT NULL,
PRIMARY KEY ( ACCNO )
);
NUMBER is not a valid datatype in MySQL, you should choose the one from the list (maybe you've meant NUMERIC).
You should also escape some identifiers (in your case, column names BA L, which includes a space within it, and CREATION-DT, which includes a dash) with backticks ` in MySQL:
CREATE TABLE `ACCOUNT` (
`ACCNO` NUMERIC(5) NOT NULL,
`NAME` VARCHAR(20) NOT NULL,
`BA L` NUMERIC(8,2) NOT NULL,
`CREATION-DT` DATE NOT NULL,
PRIMARY KEY ( `ACCNO` )
);
SQLFiddle

Issue Converting varchar to nvarchar mysql

Sorry if this is an easy question, I am coming to MySQL from SQL Server.
When I execute my create statement it contains nvarchar but commits to the database as varchar. Even in my alter statement afterwards the column does not change at all. Does the collation or DB engine make a difference?
During execution I am not encountering any issues in results, other than the fact the column changes datatype. I attached a screencast of my activity http://screencast.com/t/wc94oei2
I have not been able to find anyone with similar issues through my Google searches
Did you mean, this..
CREATE TABLE stars (
idstars int(11) NOT NULL AUTO_INCREMENT,
Name nvarchar(200) DEFAULT NULL,
PRIMARY KEY (idstars),
UNIQUE KEY Name_UNIQUE (Name)
)
----turns to---
CREATE TABLE stars (
idstars int(11) NOT NULL AUTO_INCREMENT,
Name varchar(200) DEFAULT NULL,
PRIMARY KEY (idstars),
UNIQUE KEY Name_UNIQUE (Name)
)

mysql query about create table ddl format

I am a mysql newbie. I have a question about the right thing to do for create table ddl. Up until now I have just been writing create table ddl like this...
CREATE TABLE file (
file_id mediumint(10) unsigned NOT NULL AUTO_INCREMENT,
filename varchar(100) NOT NULL,
file_notes varchar(100) DEFAULT NULL,
file_size mediumint(10) DEFAULT NULL,
file_type varchar(40) DEFAULT NULL,
file longblob DEFAULT NULL,
CONSTRAINT pk_file PRIMARY KEY (file_id)
);
But I often see people doing their create table ddl like this...
CREATE TABLE IF NOT EXISTS `etags` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`item_code` varchar(100) NOT NULL,
`item_description` varchar(500) NOT NULL,
`btn_type` enum('primary','important','success','default','warning') NOT NULL DEFAULT 'default',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
A few questions...
What difference do the quotes around the table name and column names make?
Is it good practice to explicitly declare the engine and character set? What engine and character sets are used by default?
thanks
There's no difference. Identifiers (table names, column names, et al.) must be enclosed in the backticks if they contain special characters or are reserved words. Otherwise, the backticks are optional.
Yes, it's good practice, for portability to other systems. If you re-create the table, having the storage engine and character set specified explicitly in the CREATE TABLE statement means that your statement won't be dependent on the settings of the default_character_set and default-storage-engine variables (these may get changed, or be set differently on another database.)
You can get your table DDL definition in that same format using the SHOW CREATE TABLE statement, e.g.
SHOW CREATE TABLE `file`
The CREATE TABLE DDL syntax you are seeing posted by other users is typically in the format produced as output of this statement. Note that MySQL doesn't bother with checking whether an identifier contains special characters or reserved words (to see if backticks are required or not), it just goes ahead and wraps all of the identifiers in backticks.
With backticks, reserved words and some special characters can be used in names.
It's simply a safety measure and many tools automatically add these.
The default engine and charset can be set in the servers configuration.
They are often (but not always) set to MyISAM and latin1.
Personally, I would consider it good practice to define engine and charset, just so you can be certain what you end up with.

MYSQL allowing me to insert nulls in PK and FK

I have been testing a database i am doing right now and i am noticing that it is letting me insert null values into fields that are part of a primary key, despite stating in the script that the value of the field should be NOT NULL. I am using MAC's MySQL Workbench, and I have been googling around and can't figure out why this is happening. (Maybe I am too brain-fried right now... I am even starting to doubt myself)
Part of the script of the database creation (these are the tables I have tested..):
DROP DATABASE IF EXISTS solytierra ;
CREATE DATABASE IF NOT EXISTS solytierra DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE solytierra ;
DROP TABLE IF EXISTS solytierra.Cliente ;
CREATE TABLE IF NOT EXISTS solytierra.Cliente (
CIF VARCHAR(25) NOT NULL,
Nombre VARCHAR(100) NULL,
EmailGeneral VARCHAR(45) NULL,
Web VARCHAR(45) NULL,
Notas VARCHAR(150) NULL,
insertado Timestamp,
CONSTRAINT pk_Cliente PRIMARY KEY (CIF)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS solytierra.PersonaContacto ;
CREATE TABLE IF NOT EXISTS solytierra.PersonaContacto (
Cliente_CIF VARCHAR(25) NOT NULL,
Nombre VARCHAR(50) NOT NULL,
Apellidos VARCHAR(100) NOT NULL,
Notas VARCHAR(150) NULL,
CONSTRAINT pk_PersonaContacto PRIMARY KEY (Cliente_CIF , Nombre , Apellidos),
CONSTRAINT fk_PersonaContacto_Cliente FOREIGN KEY (Cliente_CIF)
REFERENCES solytierra.Cliente (CIF)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
...
It will let me create Clients without CIF, "PersonaContacto" without Cliente_CIF or without "Nombre"....
I have also tested other databases that i already had that used to work and it is happening the same in an all them.
Got it!!
I don't know what sql mode i was running on by default, but with this:
SET sql_mode = TRADITIONAL;
It is now running perfectly! I didn't know that there were different sql modes! Thanks a lot to everyone for your time and efforts! It really helped me to see that the problem was in my workbench, not the code and look for the answer accordingly! I hope this thread will be useful for future beginners like me!
If the value being stored in the column CIF is actually a NULL, then the expression LENGTH(CIF) should also return NULL. (If it's a zero length string, then LENGTH(CIF) will return 0.
To verify:
SELECT c.CIF, LENGTH(c.CIF) FROM solytierra.Cliente c ;
SELECT c.CIF FROM solytierra.Cliente c WHERE c.CIF IS NULL;
If you are running an INSERT statement, I can't explain the behavior you are observing, either MySQL allowing a NULL value to be stored or MySQL providing an implicit default value.)
If it's a zero length string being stored, that's the behavior we would expect if the columns were not explicitly declared to be NOT NULL but were later declared to part of the primary key. It's also the behavior we'd expect if the column were defined NOT NULL DEFAULT ''.
When the NOT NULL is omitted from the column declaration and the column is later declared to be part of the PRIMARY KEY, MySQL will use an an implicit default value based on the datatype of the column (zero length string for VARCHAR, zero for an integer, etc.)
But I'm not able to reproduce the problem you report, with the table definitions you've posted.
I recommend you check the table definition by getting the output from:
SHOW CREATE TABLE solytierra.Cliente;

Error while creating simple table

I don't see why this fails :o
CREATE TABLE "Permission" (
"id" INTEGER NOT NULL,
"name" VARCHAR(255) NOT NULL,
PRIMARY KEY ("id")
);
The message
Error : 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 '"Permission" (
"id" INT NOT NULL,
"name" VARCHAR(255) NOT NULL,
PRIMARY KEY ("id' at line 1
Thanks for any ideas!
You are using the wrong quoting character. You should use ` marks not " marks for table names and columns.
CREATE TABLE `Permission` (
`id` INTEGER NOT NULL,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
);
quickshiftin's answer is good.And you should also change:
`id` INTEGER NOT NULL,
to:
`id` INT NOT NULL,
MySQL normally uses the backtick character to enclose object references, as quickshiftin's answer says.
But it's not really "wrong" to use double quotes, it's just that the MySQL default behavior is to not permit double quotes to be used in that way.
It is possible to have MySQL allow the double quote character to be used around object references by enabling the ANSI_QUOTES sql mode for your session. I would recommend you do this only temporarily, just to get your tables defined, and then set it back.
SHOW VARIABLES LIKE 'sql_mode'
SET sql_mode = 'ANSI_QUOTES'
Before you set the sql_mode variable, you want to note the current setting, so you can set it back after you have your tables created.
SET sql_mode = ''
It's also possible to set this variable at the database level, but I've never seen that done before. I've only ever (temporarily) overridden the default at the session level, for importing SQL table definitions that use double quotes.