Why does MySQL take unique index over primary index? - mysql

I have 2 very simple tables created as below:
create table company(
company_id int auto_increment,
company_no varchar(20),
company_name varchar(20),
primary key(company_id),
unique index uni_company_no(company_no)
);
create table department(
department_id int auto_increment,
department_no varchar(20),
department_name varchar(20),
company_id int not null,
primary key(department_id),
unique index uni_department_no(department_no),
index idx_company_id(company_id)
);
And if I query with the follwing SQL(I know it's an odd query), the result of EXPLAIN statenment shows that MySQL takes unique index(uni_company_no) instead of primary key:
explain select dept.* from department dept right join company com on dept.company_id = com.company_id;
EXPLAIN result
My questions are:
Why didn't MySQL use full table scan for table company?
Why didn't MySQL take primary key of table company if it decides to use index?
I'm very new to MySQL, so any input could be helpful. Thanks in advance.

Related

Use FROM clause when creating a table that references the same table

I am using MySQL Workbench and i am trying to create a table with a primary key constraint without using PRIMARY KEY keyword.
create table employee
(
e_name varchar(20),
e_surname varchar(20),
depart varchar(20),
salary int,
check (e_name is not null and 1 = (select count(*)
from employee E
where e_name=E.e_name and e_surname=E.e_surname))
);
This query causes this error: Error Code: 1146. Table 'test.employee' doesn't exist
Can i use FROM referring to the table that i am creating? Is it allowed in MySQL?
There is no such thing as a primary key constraint that doesn't use the primary key keyword. A primary key has three properties:
It is unique.
It is not NULL.
There is only one per table.
It is the third that you cannot guarantee. However, you can easily impose the first two conditions:
create table employee (
e_name varchar(20) NOT NULL UNIQUE,
e_surname varchar(20),
depart varchar(20),
salary int
);
There is no use of a check constraint for this purpose.

How we can use the primary key in another table

I have Two table
customer table which has contained the information of the customer. But it has an account number we make a primary key of the account number.
And now the second Table is Bill Table.I've use the account number of the customer table when we update some information about the Bill table then will update is automatically of the particular account number
so, please tell me how we can resolve this problem, and how we can use
the foreign key of Bill table
I think what you are asking is how to update the Customer table at the same time when you are updating Bill table.
You can easily use a stored procedure to achieve this task. Within the stored procedure you can use transactions to make sure the 2nd update happens only if the first update is succeded. Otherwise, you can rollback.
So imagine that this is your customer table:
CREATE TABLE customer (
AccountNum int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (AccountNum)
);
PRIMARY KEY (AccountNum) > so you have a primary key in that table. Kudos!
CREATE TABLE BillTable (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
AccountNum int NOT NULL,
PRIMARY KEY (OrderID),
FOREIGN KEY (AccountNum) REFERENCES customer(AccountNum)
);
Now you linked customer and BillTable.

Issue in mysql table creation

I need to create a table called benificiaries where I have three columns
customerid
accountno
bank
The condition should be one customerid can have only one unique accountno. But another customerid can have the same accountno and same unique (only once). So I cant give primary key to accountno. Even for customerid I can't give primary key, since one customerid can have multiple records with unique accountno.
How can we create table in this case? Any ideas?
You can use multiple-column unique index.
CREATE TABLE YOUR_TABLE (
id INT NOT NULL AUTO_INCREMENT,
customerid INT NOT NULL,
accountno INT NOT NULL,
bank INT NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX name (customerid,accountno)
);
Documentation here.
https://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html
If one customerid can have only 1 unique account number then how can you expect duplicates in terms of customer id in that table?
You can simply set a primary key to another column and make the customerid unique. I think this is what you want to have. Now every customerid is unique, but many costomerids can have the same accountno.
CREATE TABLE benificiaries(
id INT PRIMARY KEY,
customerid INT NOT NULL UNIQUE,
accountno INT NOT NULL,
bank INT NOT NULL
);
database can't manage all the business constraints within the data model. For the case, you might address elementary constraints with indexes (multiple column index for customerid, accountno and simple column index for accountno to perform search on the other way), add an auto-increment id and deal the business constraints in your code.
Just set your customer_id as a primary key then regarding the concept that a only two customer_id can have same account number once, will depend on the process of your App or System.
CREATE TABLE `tmpr_map`.`tbl_example`
(`customer_id` INT(11) NOT NULL AUTO_INCREMENT,
`account_number` VARCHAR NOT NULL , `bank_amount` DECIMAL(11,2) NOT NULL ,
PRIMARY KEY (`customer_id`)) ENGINE = InnoDB;

Auto increment with composite primary key

I am not entirely sure what to search so I apologize if this is in fact a duplicate.
I have a table (or at least would like to) as follows:
ID
Company Name
SomeOtherInfo
The primary key would be ID and Company name (composite primary key). What I would like is so that the ID auto increments on each company.
Ex:
1-google
2-google
3-google
1-yahoo
4-google
2-yahoo
This way they are always unique, but each one increments for each company individually.
Is this possible from simple SQL create commands, would rather not have 2 tables and join them using a secondary ID.
Let me know, thanks.
If I follow the question. Create a single table with an identity on the ID column. Then create a unique index on the Company Name.
MySql Version
CREATE TABLE Company (
CompanyID int NOT NULL AUTO_INCREMENT,
CompanyName varchar(255) NOT NULL,
OtherData varchar(255),
PRIMARY KEY (CompanyID)
);
CREATE UNIQUE INDEX CompanyUniqueComposite
ON Company (CompanyID , CompanyName );

What's the difference between using INDEX vs KEY in MySQL?

I know how to use INDEX as in the following code. And I know how to use foreign key and primary key.
CREATE TABLE tasks (
task_id int unsigned NOT NULL AUTO_INCREMENT,
parent_id int unsigned NOT NULL DEFAULT 0,
task varchar(100) NOT NULL,
date_added timestamp NOT NULL,
date_completed timestamp NULL,
PRIMARY KEY ( task_id ),
INDEX parent ( parent_id )
)
However I found a code using KEY instead of INDEX as following.
CREATE TABLE orders (
order_id int unsigned NOT NULL AUTO_INCREMENT,
-- etc
KEY order_date ( order_date )
)
I could not find any explanation on the official MySQL page. Could anyone tell me what is the differences between KEY and INDEX?
The only difference I see is that when I use KEY ..., I need to repeat the word, e.g. KEY order_date ( order_date ).
There's no difference. They are synonyms, though INDEX should be preferred (as INDEX is ISO SQL compliant, while KEY is a MySQL-specific, non-portable, extension).
From the CREATE TABLE manual entry:
KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.
By "The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition.", it means that these three CREATE TABLE statements below are equivalent and generate identical TABLE objects in the database:
CREATE TABLE orders1 (
order_id int PRIMARY KEY
);
CREATE TABLE orders2 (
order_id int KEY
);
CREATE TABLE orders3 (
order_id int NOT NULL,
PRIMARY KEY ( order_id )
);
...while these 2 statements below (for orders4, orders5) are equivalent with each other, but not with the 3 statements above, as here KEY and INDEX are synonyms for INDEX, not a PRIMARY KEY:
CREATE TABLE orders4 (
order_id int NOT NULL,
KEY ( order_id )
);
CREATE TABLE orders5 (
order_id int NOT NULL,
INDEX ( order_id )
);
...as the KEY ( order_id ) and INDEX ( order_id ) members do not define a PRIMARY KEY, they only define a generic INDEX object, which is nothing like a KEY at all (as it does not uniquely identify a row).
As can be seen by running SHOW CREATE TABLE orders1...5:
Table
SHOW CREATE TABLE...
orders1
CREATE TABLE orders1 ( order_id int NOT NULL, PRIMARY KEY ( order_id ))
orders2
CREATE TABLE orders2 ( order_id int NOT NULL, PRIMARY KEY ( order_id ))
orders3
CREATE TABLE orders3 ( order_id int NOT NULL, PRIMARY KEY ( order_id ))
orders4
CREATE TABLE orders4 ( order_id int NOT NULL, KEY ( order_id ))
orders5
CREATE TABLE orders5 ( order_id int NOT NULL, KEY ( order_id ))
Here is a nice description about the "difference":
"MySQL requires every Key also be indexed, that's an implementation
detail specific to MySQL to improve performance."
Keys are special fields that play very specific roles within a table, and the type of key determines its purpose within the table.
An index is a structure that RDBMS(database management system) provides to improve data processing. An index has nothing to do with a logical database structure.
SO...
Keys are logical structures you use to identify records within a table and indexes are physical structures you use to optimize data processing.
Source: Database Design for Mere Mortals
Author: Michael Hernandez
It is mentioned as a synonym for INDEX in the 'create table' docs:
MySQL 5.5 Reference Manual :: 13 SQL Statement Syntax :: 13.1 Data Definition Statements :: 13.1.17 CREATE TABLE Syntax
#Nos already cited the section and linked the help for 5.1.
Like PRIMARY KEY creates a primary key and an index for you,
KEY creates an index only.
A key is a set of columns or expressions on which we build an index.
While an index is a structure that is stored in database, keys are strictly a logical concept.
Index help us in fast accessing a record, whereas keys just identify the records uniquely.
Every table will necessarily have a key, but having an index is not mandatory.
Check on https://docs.oracle.com/cd/E11882_01/server.112/e40540/indexiot.htm#CNCPT721