SQL: Create table with two indexes - mysql

I previously created a table using the following SQL code:
CREATE TABLE myTable (
id_A BIGINT NOT NULL,
id_B INT NOT NULL,
some_info varchar(255),
some_info2 varchar(255),
PRIMARY KEY (id_A)
)
In the previous table created, both id_A and id_B would be unique values. I understand that id_A is forced to be unique by the
PRIMARY KEY (id_A) code, which is perfect (which also indexes it), however id_B isn't
Here is where I am confused. id_B will also be unique, however I am not sure how to force it to be unique in the table,and how to make the database create an index for it so that future queries that use SELECT on this table will have good preformance. I know I can't have two PRIMARY KEYS:
PRIMARY KEY (id_A)
PRIMARY KEY (id_B)
How might I go about making an index for id_B as well so that future queries happen efficiently?

You can add a UNIQUE INDEX on the column. While a table can only have one PRIMARY KEY, it can have as many UNIQUE INDEXes as you might need.
ALTER TABLE myTable
ADD UNIQUE INDEX `UI_myTable_idB` (`id_B` );

You can use the MySQL UNIQUE KEY for the column. This will force the values in the id_B column to be unique, but not use it as the primary key column. You can achieve it with this statement:
CREATE TABLE myTable (
id_A BIGINT NOT NULL,
id_B INT NOT NULL,
some_info varchar(255),
some_info2 varchar(255),
PRIMARY KEY (id_A),
UNIQUE KEY (id_b))
This will automatically index the column like you want it to. Primary keys and unique keys in a MySQL table are essentially the same, except a primary key cannot be NULL, and there can be only one primary key column (or combination of primary key columns). There can be any number of unique key columns.

Related

When to use an auto-increment key?

I've recently started to work on MySQL and while I've read some documentation on database structure, I cannot get my head around auto-increment keys and why using them.
I have been told:
it's best to use a number instead of text as a primary key,
it's best to use a key that doesn't have any business signification
Let's look at the situation below:
tStores tSales tCustomers
---------- ----------- --------------
store_id sale_id customer_id
storeCode store_id
customer_id
First, I load some data in tStores for all the stores products can be sold. In our business, all stores have a 4 letters code to identify them. I could use this as a primary key, but based on the recommendations above I should use a store_id field that auto-increments?
The problem is, each time I insert something in tSales, I have to go back to tStores and do something like:
SELECT store_id from tStores WHERE storeCode = #myStoreCode;
Assuming I am loading hundreds of thousands rows in tSales for each store, would it not be more efficient to use the storeCode as primary key?
What would be the most efficient way to deal with this?
Yes you can use storeCode as the primary key, it will work if you can ensure it is unique. Then you will add a foreign key on your other tables to establish the relationship.
The benefit of auto increment index are:
It is usually faster than any index on other column type
It is usually recommended by some framework (such as Laravel in PHP)
Related to you structure I would comment on some points:
You have mixed casing columns/tables. When working on MySQL, especially when used on different OS (Windows/Linux), I would always recommend to use lowercase names for both schemas, tables and columns.
You added a prefix in front of store_id and store_code. This prefix is not necessary. Why not simply naming the columns id and code.
The relationship on tSales should be named tStores_id instead to clearly indicate from which table and which column you are referring to.
Here the SQL code for this example:
CREATE SCHEMA `myshop` ;
CREATE TABLE `store`.`stores` (
`code` VARCHAR(10) NOT NULL,
PRIMARY KEY (`code`));
CREATE TABLE `store`.`sales` (
`id` INT NOT NULL AUTO_INCREMENT,
`store_code` VARCHAR(10) NOT NULL,
`customer_id` INT NOT NULL,
PRIMARY KEY (`id`));
CREATE TABLE `store`.`customers` (
`id` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`));
ALTER TABLE `store`.`sales`
ADD INDEX `fk_sales_customers_id_idx` (`customer_id` ASC) VISIBLE;
ALTER TABLE `store`.`sales`
ADD CONSTRAINT `fk_sales_customers_id`
FOREIGN KEY (`customer_id`)
REFERENCES `store`.`customers` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE `store`.`sales`
ADD INDEX `fk_sales_stores_code_idx` (`store_code` ASC) VISIBLE;
ALTER TABLE `store`.`sales`
ADD CONSTRAINT `fk_sales_stores_code_id`
FOREIGN KEY (`store_code`)
REFERENCES `store`.`stores` (`code`)
ON DELETE CASCADE
ON UPDATE CASCADE;

How to create a MySQL with Primary Key not an auto increment

Am trying to create the following table:
create table Cust (Name varchar(50) UNIQUE, Cat1 varchar(50), RowID int NOT NULL AUTO_INCREMENT, PRIMARY KEY (Name));
the error I get is
Incorrect table definition; there can be only one auto column and it
must be defined as a key
I want to index by the "Name", not the RowID. So even if I end it with:
...PRIMARY KEY (Name, RowID));
It fails. Of course ...PRIMARY KEY (RowID, Name)); works but is not what I want.
Can someone help me see the light please?
Thanks
You just need to make a KEY (aka index) for the auto-inc column. It doesn't have to be the primary key, but it must be the left-most column in some index.
create table Cust (
Name varchar(50),
Cat1 varchar(50),
RowID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (Name),
KEY (RowId)
);
Don't add the UNIQUE option to the name column. That creates an extra superfluous unique index, which you don't need. Any PRIMARY KEY is already unique.
I'll comment that auto-inc is not the same thing as rowid. Don't expect auto-inc to have consecutive values.

creating primary keys with constraints or not in mysql

In mysql, say I have:
create table users(
id not null
)
Let's say I need to make id as a primary key. What is the difference between:
create table users(
id primary key not null
)
and
create table users(
id not null
primary key (id))
and
create table users(
id not null
constraint pk primary key (id))
I've been searching a lot for the meaning of constraints in this context, but I only find how to use them, not what it actually is.
A primary key is both not null and unique. So, this is very, very similar to a primary key:
create table users (
id int not null unique
)
The one additional feature of a primary key is that it is usually also the clustered index for the table.
A primary key declaration is a constraint. It has the following properties:
The columns are not null.
The columns are unique.
Only one primary key declaration is allowed per table (although multiple columns can be in the primary key).
In addition, the primary key columns often form a clustered index.
Except for the third condition, it is possible to declare these using multiple constraint declarations.

MySql: Composite Unique Key

I want to make composite key of 2 column id & code,the both columns altogether should act like Unique key for the table. while I have browsed and tried to create a table as follows,
Create table test (
`test_no` int not null AUTO_INCREMENT,
`code` varchar(5) NOT NULL,
`name` varchar(255),
`UPDBy` varchar(255),
PRIMARY KEY (`test_no`),
FOREIGN KEY (code) REFERENCES other_table(code)
// CONSTRAINT `K_test_1` Unique KEY (`test_no`,`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Just a second thought, can i make both the column as PK ? I think it will serve my purpose, RIght?
CONSTRAINT `K_test_1` Primary KEY (`test_no`,`code`) OR Primary KEY (`test_no`,`code`)
You seem to be on the wrong track somehow. Your table has an ID which is auto incremented. This is not supposed to be the primary key? Why do you call it ID then?
There are two ways to build a database: Either use the natural values a user is used to, such as an employee number a department number and so on. Or use IDs (which are usually hidden from the user). Than you would have an employee table with primary key "id" or "employee_id" or whatever, and the employee number just as a field. But as it must be unique, you would have an additional unique index on that field.
Having said that; you have a table "other_table" with primary key "code" it seems. So you are not using an ID concept here. Then why do you use it on table test? If this is a detail table on other_table, then I'd expect the composite key to be something like code + test_no (thus showing numbered tests per code) for isntance.
So the essence is: 1. Think about what your table contains. 2. Think about wether to use IDs or natural keys. The answer to these questions should help you find the correct key for your table. (And sometimes a table even doesn't have a primary key and needs none.)
You sure can make them both as PRIMARY KEY. If you don't want to, just use UNIQUE instead of UNIQUE KEY.
To set both as PRIMARY KEY, do as it follows:
...
PRIMARY KEY (`id`, `code`);
...
To set a UNIQUE CONSTRAINT, do as it follows:
...
CONSTRAINT `K_test_1` UNIQUE (`id`,`code`);
...

Is it possible to make two primary keys in one table?

Hi I want to know if it is possible to make two primary keys in one table in MySQL. If so, please explain the concept behind this. I am asking because I have seen a table in which two primary keys are there with no auto increment set.
you can only have 1 primary key, but:
you can combine more than one column to be the primary key (maybe it's this what you have seen)
the primary key don't needs to be an auto-increment, it just has to be unique
you can add more than one index to one or more colums to speed up SELECT-statements (but slow down INSERT / UPDATE)
those indexes can be marked as unique, wich means they don't let you insert a second row with the same content in the index-fields (just like a primary key)
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
[...] A table can have only one PRIMARY KEY. [...]
No, but you can have other UNIQUE indexes on the table, in addition to the PRIMARY KEY. UNIQUE + NOT NULL is basically the same as a primary key.
What you have seen is probably a composite primary key (more than one column making up the unique key).
Use a Composite Primary Key...
e.g.
CREATE TABLE table1 (
first_id int unsigned not null,
second_id int unsigned not null auto_increment,
user_id int unsigned not null,
desc text not null,
PRIMARY KEY(first_id, second_id));
Also, check out the example here
You can use multiple columns for your primary key in this way:
CREATE TABLE
newTable
( field1 INT(11)
, field2 INT(11)
, field3 VARCHAR(5)
, field4 BLOB
, PRIMARY KEY (field2, field1, field3) <====
)
A table can have a single PRIMARY key, which may consist of one or more columns. A table can also have a number of additional keys defined on it, as UNIQUE KEY constraints.
It's not clear from your description whether you were looking at a table with multiple keys defined, or a table with a multi-column PRIMARY KEY.