Translating MySQL CREATE TABLE syntax to Postgresql - mysql

I'm new to MySQL, and would like to understand the following CREATE TABLE code:
CREATE TABLE IF NOT EXISTS label_gtin (
LABEL_ID int NOT NULL,
GTIN_CD varchar(13) NOT NULL,
KEY LABEL_ID (LABEL_ID,GTIN_CD)
);
Specifically, I'd like to understand what "KEY LABEL_ID (LABEL_ID,GTIN_CD)" does, and translate this to Postgresql.
Would appreciate any help. Thanks a lot!

you can write given CREATE TABLE code in postgresql as shown :
CREATE TABLE IF NOT EXISTS label_gtin (
LABEL_ID integer NOT NULL,
GTIN_CD varchar(13) NOT NULL,
CONSTRAINT LABEL_ID PRIMARY KEY(LABEL_ID,GTIN_CD)
);
Key (PRIMARY KEY in postgresql) is a Primary Key constraint on one or more columns
whose combination is unic for records in table.
Syntax: CONSTRAINT <Constraint Name> PRIMARY KEY(<Column1>[,<Column2>,<Column3>,...])
IF NOT EXISTS: Do not throw an error if a relation with the same name already exists. A notice is issued in this case. Note that there is no guarantee that the existing relation is anything like the one that would have been created.
you can Refer this link for details : http://www.postgresql.org/docs/current/static/sql-createtable.html

Related

Converting MySQL code to PostgreSQL using foreign keys

I am trying to create tables with a primary key and foreign key in Postgresql. Originally was created in MySQL but I do not know how to convert can someone assist.
I converted the first table but the instructor table is giving me problems
CREATE TABLE instructor_detail (
id SERIAL PRIMARY KEY,
youtube_channel VARCHAR(128) NULL,
hobby VARCHAR(45) NULL
);
DROP TABLE IF EXISTS instructor;
`CREATE TABLE instructor (
id SERIAL PRIMARY KEY,
first_name VARCHAR(45) NULL,
last_name VARCHAR(45) NULL,
email VARCHAR(45) NULL,
instructor_detail_id INT NULL,
CREATE INDEX fk_detail_idx ON instructor (instructor_detail_id), CONSTRAINT fk_detail FOREIGN KEY (instructor_detail_id) REFERENCES instructor_detail (id) ON DELETE NO ACTION ON UPDATE NO ACTION
);`
ERROR: syntax error at or near "CREATE"
LINE 7: CREATE INDEX fk_detail_idx ON instructor (instructor_detai...
The foreign key constraint will work in PostgreSQL, no change is required.
The KEY clause is a MySQL extension to create an index within CREATE TABLE, which PostgreSQL does not support.
You'll have to convert the KEY clause to a separate CREATE INDEX statement in PostgresSQL.

Transferring from sql developer to mysql

So i have a few tables in my database in Sql developer which I still have the queries from. If I try to put it in mysql it comes out with some errors so i'm wondering what is different and why is it not working like what would I need to change.
These are some of the tables I created in sql which i'm trying to create now in mysql:
create table EspecialidadesMedicas(
IdEspecialidad number(4) constraint pk_EspecialidadesMedicas primary key,
DescripcionEspecialidad varchar2(30));
create table Doctores(
IdDoctor number(5) constraint pk_Doctores primary key,
NombreDoctor varchar2(30),
Salario number(12,2),
Especialidad constraint fk1_Doctores references EspecialidadesMedicas);
create table Consultorios(
IdConsultorio number(4) constraint pk_Consultorios primary key,
Tamano varchar2(30),
Construido date);
Your first statement will become this:
create table EspecialidadesMedicas(
IdEspecialidad int primary key,
DescripcionEspecialidad varchar(30)
);
Your second statement is likely to become this:
create table Doctores(
IdDoctor int primary key,
NombreDoctor varchar(30),
Salario decimal(12,2),
Especialidad int,
constraint fk1_Doctores foreign key (Especialidad) references EspecialidadesMedicas (IdEspecialidad)
);
Your third statement will turn out to be:
create table Consultorios(
IdConsultorio int primary key,
Tamano varchar(30),
Construido date
);
Try this out in MySQL.
Your first table would look like this in MySQL:
CREATE TABLE `de`.`EspecialidadesMedicas` (
`IdEspecialidad` INT NOT NULL AUTO_INCREMENT,
`DescripcionEspecialidad` VARCHAR(30) NULL,
PRIMARY KEY (`IdEspecialidad`));
As you see, there are quite some differences in syntax, data types and features which can not all be covered here. (e.g. AUTO INCREMENT)
The easiest way to get into this is to use a toollike MySQL Workbench. It allows you to use a GUI to create your tables and displays the executed SQL. This way you see the differences.
I also suggest to read some migration tutorials like these:
https://blog.toadworld.com/2017/03/17/migrating-from-oracle-to-mysql
http://www.sqlines.com/oracle-to-mysql

MySQL : Error Code 1215 : Cannot add foreign key constraint

I'm trying to make a simple SQL schema, but I'm having some problem with defining foreign keys. I really don't have that much MySQL knowledge, so I thought I'd ask her for some help. I get Error Code 1215 when I try to create the foreign key roomID and 'guestEmail' in the HotelManagement.Reservation table creation.
CREATE database HotelManagement;
CREATE TABLE HotelManagement.Room (
roomID INT not null auto_increment,
roomTaken TINYINT(1),
beds INT not null,
size INT not null,
roomRank INT not null,
PRIMARY KEY(roomID));
CREATE TABLE HotelManagement.HotelTask (
taskType INT not null,
taskStatus TINYINT(1) not null,
whichRoom INT not null,
note VARCHAR(255),
PRIMARY KEY (taskType),
FOREIGN KEY (whichRoom) REFERENCES HotelManagement.Room(roomID));
CREATE TABLE HotelManagement.Guest (
firstName varchar(25) not null,
lastName varchar(25) not null,
userPassword varchar(25) not null,
email varchar(25) not null,
reservation INT,
PRIMARY KEY (userPassword, email));
CREATE TABLE HotelManagement.Reservation (
reservationID INT not null,
id_room INT not null,
guestEmail varchar(25) not null,
fromDate DATE not null,
toDate DATE not null,
PRIMARY KEY (reservationID),
FOREIGN KEY (guestEmail)
REFERENCES HotelManagement.Guest(email),
FOREIGN KEY (id_room)
REFERENCES HotelManagement.Room(roomID)
);
ALTER TABLE HotelManagement.Guest
ADD CONSTRAINT res_constr FOREIGN KEY (reservation)
REFERENCES HotelManagement.Reservation(reservationID);
Updated the .sql
In the hoteltask table you have already defined a foreign key named roomid. Foreign key names also have to be unique, so just give a different name to the 2nd foreign key or omit the name completely:
If the CONSTRAINT symbol clause is given, the symbol value, if used,
must be unique in the database. A duplicate symbol will result in an
error similar to: ERROR 1022 (2300): Can't write; duplicate key in
table '#sql- 464_1'. If the clause is not given, or a symbol is not
included following the CONSTRAINT keyword, a name for the constraint
is created automatically.
UPDATE
The email field in the guest table is the rightmost column of the primary key, this way the pk cannot be used to independently look up email in that table. Either change the order or fields in the pk, or have a separate index on email field in the guest table. Quote from the same link as above:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Pls read through the entire documentation I linked before proceeding with creating the fks!
Side note 2 (1st is in the comments below): you should probably have a unique numeric guest id because that is lot more efficient than using email. Even if you decide to stick with email as id, I would restrict the pk in the guest table to email only. With the current pk I can register with the same email multiple times if I use different password.

Unable to create table in MySQL

I am unable to create these tables in MySQL. Everything looks complete to me but I keep getting errors.
Here is my SQL:
CREATE TABLE Movies(
title char PRIMARY KEY NOT NULL,
Years date NOT NULL,
length decimal not null,
genre char NOT NULL,
academy_award char not null,
FOREIGN KEY(the_name) REFERENCES Studio,
FOREIGN KEY(directorName) REFERENCES Director);
CREATE TABLE StarsIn(
FOREIGN KEY(title) REFERENCES Movies,
FOREIGN KEY(Years) REFERENCES Movies,
FOREIGN KEY(the_name) REFERENCES MovieStar);
CREATE TABLE Director(
the_name char PRIMARY KEY NOT NULL,
birthdate date NOT NULL,
nationality char NOT NULL);
CREATE TABLE MovieStar(
the_name char PRIMARY KEY NOT NULL,
birthdate date NOT NULL,
address char NOT NULL,
gender char NOT NULL);
CREATE TABLE Studio(
the_name char PRIMARY KEY NOT NULL,
address char NOT NULL);
This isn't working because your tables are not being created in the proper order.
The parent table must always be created first, because otherwise you will be trying to reference a column that does not exist.
For example, look at this part here:
CREATE TABLE Movies(title char PRIMARY KEY NOT NULL, Years date NOT NULL,
length decimal not null, genre char NOT NULL, academy_award char not null,
FOREIGN KEY(the_name) REFERENCES Studio, FOREIGN KEY(directorName) REFERENCES Director);
You can't reference tables studio or director because they don't even exist.
The proper order could be:
Studio
Movie Star
Director
Movies
StarsIn
In addition, you have a lot of other problems going on here.
You do not define any columns in the Stars IN table, you only declare foreign keys:
CREATE TABLE StarsIn(
FOREIGN KEY(title) REFERENCES Movies,
FOREIGN KEY(Years) REFERENCES Movies,
FOREIGN KEY(the_name) REFERENCES MovieStar);
Not only are you not defining any columns, you aren't referencing anything. This will also throw an error. Your foreign key title must reference some column in the movies table. And in addition to that, you can't create a foreign key reference for Years. Mostly because you cannot create a foreign key to a column that is not primary key in another table, and also why should you need two foreign keys to the same table?
Those problems exist in other create table statements as well, so given everything I've said please go back and look at each of your create table statements.
Here is a working SQL Fiddle you can use for reference though.
EDIT
I would like to also add that I do not recommend using the char datatype. Please look into using VARCHAR().
The problem you are having is that you are referencing columns in tables that do not exist.
Although you create these tables later, the DBMS engine does not know they will exist.
The solution - create the tables without the FK's that do not exist, and add these later using the "ALTER TABLE" command.
It seems like you know the syntax, so I'll let you inform me if you cannot find it.
your syntax should look like (All I did is re-order, and change char to be archer...):
CREATE TABLE Studio(the_name varchar(50) PRIMARY KEY NOT NULL, address varchar(50) NOT NULL);
CREATE TABLE Director(the_name varchar(50) PRIMARY KEY NOT NULL, birthdate date NOT NULL, nationality varchar(50) NOT NULL);
CREATE TABLE Movies(title varchar(50) PRIMARY KEY NOT NULL, Years date NOT NULL,
length decimal not null, genre varchar(50) NOT NULL, academy_award varchar(50) not null,
the_name REFERENCES Studio(the_name), directorname REFERENCES Director(the_name));
CREATE TABLE MovieStar(the_name char PRIMARY KEY NOT NULL, birthdate date NOT NULL, address char NOT NULL, gender char NOT NULL);
CREATE TABLE StarsIn(title REFERENCES Movies(title),movie REFERENCES Movies(title), moviestar REFERENCES MovieStar(the_name));
A little note, depends on the version - you'd might have to use the FOREIGN KEY(col_name) instead of col_name. I like more the syntax without it, but some versions force you to use FOREIGN KEY(title) instead of title in the last SQL for example.
The syntax you used - Foreign key NAME References TABLE (Column) -- you forgot the column-- Allows you to name the FK. If you don't use the "Foreign Key" the system will randomly assign a name. This is usually not important, unless you want the DB design to be "clean" and to be able to reference it by name.
P.S. - I did not run it, I trust you to inform if there's any other issue - I did not check the syntax, just fixed the error you reported- references that do not exist...
P.S. P.S. Always check syntax... http://dev.mysql.com/doc/refman/5.1/en/create-table.html

unwanted primary keys in a new sql table

I have bulid a new table in my SQL database with the following command :
Create Table if not exists Images (ImageID int (10) primary key NOT NULL AUTO_INCREMENT ,
UserID int (10) NOT NULL,
Translated tinyint Default 0,
DeleteImage tinyint Default 0,
DataPosted date,
TheImage blob,
Translation text,
FOREIGN KEY (UserID) REFERENCES Users(UserID) ON DELETE CASCADE)
the table is been created just fine, but what i'm checking what was build i've found out that in the table the columns ImageID, TheImage, and Translation are defined as primary keys.
as the query is showing I want only the ImageId to be the primary key.
what's happening here?
tnx
Seems quite unlikely. It seems far more likely that something is wrong with whatever tool you're using to find out which columns are primary keys.
Actually, from the documentation - here: http://dev.mysql.com/doc/refman/5.1/en/create-table.html - it would follow that a MySQL table can only have one primary key. But even if not, why would you worry about it?