MySQL INDEX() syntax equivalent in SQL Server - mysql

I am following a PHP workbook and one of the exercises asks me to create a table with columns using the following MySQL code
CREATE TABLE messages (
message_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INT UNSIGNED NOT NULL DEFAULT 0,
forum_id TINYINT UNSIGNED NOT NULL,
user_id MEDIUMINT UNSIGNED NOT NULL,
subject VARCHAR(100) NOT NULL,
body LONGTEXT NOT NULL,
date_entered DATETIME NOT NULL,
PRIMARY KEY (message_id),
INDEX (parent_id),
INDEX (forum_id),
INDEX (user_id),
INDEX (date_entered)
);
The problem is at the place I work they use Microsoft SQL Server so the syntax is different.
What is the equivalent SQL Server syntax I can use for
INDEX (parent_id),
INDEX (forum_id),
INDEX (user_id),
INDEX (date_entered)

What is the equivalent SQL Server syntax I can use for
INDEX (parent_id),
INDEX (forum_id),
INDEX (user_id),
INDEX (date_entered)
Looking in the manual i notice the BNF form.
<column_index> ::=
INDEX index_name [ CLUSTERED | NONCLUSTERED ]
[ WITH ( <index_option> [ ,... n ] ) ]
[ ON { partition_scheme_name (column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
So SQL Server 2008+ should also support INDEX keyword in the CREATE TABLE statement..
But the valid syntax for the INDEX keyword is using
CREATE TABLE test (
id INT
, INDEX index_name (id)
);
But there are other things wrong like datatypes or keywords..
The correct SQL code for SQL server is
CREATE TABLE messages (
message_id INT identity(1, 1),
parent_id INT NOT NULL DEFAULT 0,
forum_id TINYINT NOT NULL,
user_id INT NOT NULL,
subject VARCHAR(100) NOT NULL,
body TEXT NOT NULL,
date_entered DATETIME NOT NULL,
PRIMARY KEY (message_id),
INDEX parent_id (parent_id),
INDEX forum_id (forum_id),
INDEX user_id (user_id),
INDEX date_entered (date_entered)
);

You can use syntax that should work in any SQL engine, e.g.
CREATE TABLE messages (
message_id INT,
parent_id INT NOT NULL DEFAULT 0,
forum_id TINYINT NOT NULL,
user_id INT NOT NULL,
subject VARCHAR(100) NOT NULL,
body TEXT NOT NULL,
date_entered DATETIME NOT NULL,
PRIMARY KEY (message_id)
)
Then create other indexes individually:
CREATE INDEX parent_id_idx ON messages (parent_id))
And so on.
This syntax should be supported by all SQL engines.

Related

MySQL/POSTGRES how to force foreign key to be NULL

I have the following SQLite3 database
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
email VARCHAR(75) NOT NULL,
password VARCHAR(128) NOT NULL
);
CREATE TABLE IF NOT EXISTS pads (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id)
);
CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
pad_id INTEGER REFERENCES pads(id),
user_id INTEGER NOT NULL REFERENCES users(id),
name VARCHAR(100) NOT NULL,
text text NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
~
I have tried to migrate this sql schema to mysql and postgres, everything seems to be working fine except for one detail.
The table notes should accept pad_id as NULL, if there is no pad a note should be saved but when I try to save a note without a pad I get an error
sqlalchemy.exc.IntegrityError
IntegrityError: (psycopg2.errors.ForeignKeyViolation) insert or update
on table "note" violates foreign key constraint "note_pad_id_fkey"
DETAIL: Key (pad_id)=(0) is not present in table "pad".
But I should be able to save it as NULL, it works fine on SQLite3.
What should I change to be able to accomplish this?
Thank you.
Neither MySQL nor Postgres has a problem, with NULL as padod see examples
Therefore the error messahe comes from postgres, but it is because of the migration
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
email VARCHAR(75) NOT NULL,
password VARCHAR(128) NOT NULL
);
CREATE TABLE IF NOT EXISTS pads (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id)
);
CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
pad_id INTEGER REFERENCES pads(id),
user_id INTEGER NOT NULL REFERENCES users(id),
name VARCHAR(100) NOT NULL,
`text` text NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
INSERT INTO users VALUES(NULL,'test','pass')
✓
INSERT INTO notes VALUES (NULL,NULL,1,'test','text',NOW(),NOW())
✓
db<>fiddle here
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY NOT NULL,
email VARCHAR(75) NOT NULL,
password VARCHAR(128) NOT NULL
);
CREATE TABLE IF NOT EXISTS pads (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id)
);
CREATE TABLE notes (
id SERIAL PRIMARY KEY NOT NULL,
pad_id INTEGER REFERENCES pads(id),
user_id INTEGER NOT NULL REFERENCES users(id),
name VARCHAR(100) NOT NULL,
"text" text NOT NULL,
created_at timestamp NOT NULL,
updated_at timestamp NOT NULL
);
INSERT INTO users VALUES(DEFAULT,'test','pass')
1 rows affected
INSERT INTO notes VALUES (DEFAULT,NULL,1,'test','text',NOW(),NOW())
1 rows affected
db<>fiddle here

Why this error in mysql making a table?

I just want a make table like below.
create table android_data (
index int unsigned primary key AUTO_INCREMENT,
phone int not null,
sensorID int not null,
press int not null,
temp int not null,
accel int not null,
gps_lat double not null,
gps_lng double not null,
time timestamp default current_timestamp on update current_timestamp
)engine=innodb;
But I got an error in
index int unsigned primary key AUTO_INCREMENT,
phone int not null,
I cant understand Why this is wrong with manual....
What should I do to make right table??
Index is a reserved keyword in MySQL. If you must name your primary key index you should put it in backticks:
create table android_data (
`index` int unsigned primary key AUTO_INCREMENT,
...
)
But ideally you should avoid naming tables and columns using MySQL keywords for the very reason you have already seen.
MySQL keywords

Having Trouble with MySQL Primary Key and adding Index (Error #1064)

CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL INDEX,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL)
I get this 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 'INDEX,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL)' at line 3
To define inline indexes in a CREATE TABLE statement, you will need to place it on a separate 'create definition' line:
CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL,
INDEX(IP),
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL
);
SqlFiddle
You can also place the index definition outside of the table definition, like so:
CREATE INDEX IX_registers_ip ON registers(IP);
It is regarded as good practice to name the index, so that it can be referenced exactly.
Your synatx must be:
CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL ,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL,
INDEX (IP )
)
For more information about the create table statement see the official mysql documentation
Try this instead - in MySQL syntax the INDEX definition cannot be included in the field definition:
CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL,
INDEX `ip_1` (`ip`)
)
Alternatively - sometimes preferred for readability you can create the index in a separate statement after you create the table:
CREATE TABLE registers(
User_ID INT UNSIGNED NOT NULL PRIMARY KEY,
IP INT UNSIGNED NOT NULL,
Success TINYINT UNSIGNED NOT NULL,
Time_Created DATETIME NOT NULL
);
CREATE INDEX ip_1 ON registers (ip);

Error creating table: You have an error in your SQL syntax near 'order( order_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id ' at line 1 [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to create 2 tables in the same MySQL database with a PHP-script:
table 'user' with primary key 'user_id' and table 'order' with primary key 'order_id' and foreign key 'user_id' from the 'user' table (1 to many relationship).
Table user creates successfully without problems:
$sql="CREATE TABLE user(
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
type ENUM('member','admin') NOT NULL,
username VARCHAR(30) NOT NULL,
email VARCHAR(80) NOT NULL,
pass VARBINARY(32) NOT NULL,
first_name VARCHAR(40) NOT NULL,
last_name VARCHAR(40) NOT NULL,
date_expires DATE NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
date_modified TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (user_id),
UNIQUE (username),
UNIQUE (email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
However, I am not able to create table order:
$sql="CREATE TABLE order(
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
I get the following error:
Error creating table: 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 'order( order_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id ' at line 1
Already checked the syntax and cannot find the mistake. Could you please advise what went wrong? Thanks a lot.
You need to escape reserved words like order with backticks
CREATE TABLE `order` ( ...
or better use another name instead.
order is keyword used by mysql like (select from tbl_name order by id ASC) so for escaping from using keywords you have to use quotes `` to avoid my sql error
so your query should by
$sql="CREATE TABLE `order` (
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
enjoy :D

How do I declare a multi-column PK in MySQL

I'm trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax. I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns.
CREATE TABLE table_name
(
c1 INT NOT NULL,
c2 INT NOT NULL,
PRIMARY KEY (c1, c2)
)
Try:
create table .....
primary key (`id1`, `id2`)
)
Example:
CREATE TABLE `synthesis`.`INV_MasterItemList` (
`MasterItemList_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`Customer_ID` INTEGER UNSIGNED NOT NULL,
`Model_ID` INTEGER UNSIGNED NOT NULL,
`Serial` VARCHAR(45) NOT NULL,
PRIMARY KEY (`MasterItemList_ID`),
UNIQUE INDEX `INDEX_UNIQUE`(`Customer_ID`, `Model_ID`, `Serial`)
)
An example (from osCommerce) :
CREATE TABLE categories_description (
categories_id int DEFAULT '0' NOT NULL,
language_id int DEFAULT '1' NOT NULL,
categories_name varchar(32) NOT NULL,
PRIMARY KEY (categories_id, language_id),
KEY idx_categories_name (categories_name)
);