I tried to create a table named users by CREATE TABLE users (id INT, name CHAR);. Now, I can't start mysql from console, the error is as follows:
mysql: [ERROR] unknown option '--CREATE TABLE users (id INT, name CHAR);'.
The CREATE TABLE statement is used to create a table in MySQL.
NOT NULL - Each row must contain a value for that column, null values are not allowed
DEFAULT value - Set a default value that is added when no other value is passed
UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value must be unique for each record in the table.
CREATE TABLE users(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL
)
Related
I have a database table with several columns where some of them used to form the primary key together. Now the model changed and a single primary key column, called 'id', gets introduced.
When I alter the table and add the column, the column gets populated in every row with an default value, 0 or NULL, so that it can not be used as a candidate for a new primary key. To achieve that, I have to have a different (numerical) value for 'id' in every row. How can I achieve that, preferably as generic as possible (MySQL, Oracle, SQL Server).
Here is a sample of how to add an identity column that populates as a primary key.
create table #t (vals varchar(100))
insert into #t
values('a'),('b'),('c')
alter table #t
add ID int identity primary key
select * from #t
Results:
vals ID
a 1
b 2
c 3
This is a SQL Server answer. I don't know how the other databases work.
CREATE TABLE Persons (
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Might be this will be helpful.
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "ID" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):
I have been using AUTO_INCREMENT attribute to generate a primary key when a new row is inserted into a table in MySQL.
Could somebody help me understand what is the default primary key generation strategy for MySQL and how does it work?
EDIT
Hibernate has a identifier generation strategy native selects identity, sequence or hilo depending upon the capabilities of the underlying database. I used MySQL with hibernate.hbm2ddl.auto=update which generated id BIGINT(20) NOT NULL AUTO_INCREMENT for id property of Long Java data type.
I am trying to understand how did Hibernate choose AUTO_INCREMENT when it used SchemaExport tool. Is AUTO_INCREMENT the default primary key generation strategy for MySQL?
From here
The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows.
If no value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers. If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers.
The value will be incremented for each new row
The value is unique, duplicates are not possible
If a row is deleted, the auto_increment column of that row will not be re-assigned.
The auto_increment value of the last inserted row can be accessed using the mySQL function LAST_INSERT_ID() but it must be called right after the insert query, in the same database connection
Always not necessary to use auto increment to put it as primary key.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
You can use 'SERIAL' data type.
CREATE TABLE test(
"id" Serial NOT NULL,
);
ALTER TABLE "test" ADD CONSTRAINT "Key1" PRIMARY KEY ("id");
I have come across two ways to increment the ids in mysql automatically.
One is SERIAL and other is AUTOINCREMENT.
So Suppose i want to create a table myfriends.
I can create it in two ways like:
1)
mysql> create table myfriends(id int primary key auto_increment,frnd_name varchar(50) not null);
2)
mysql> create table myfriends(id serial primary key,frnd_name varchar(50) not null);
What is difference between the two ?
OR
Do anyone way has advantages over other ?
Please Help.
As per the docs
SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.
So, be careful when creating a reference to a SERIAL PK, since that reference column has to be of this exact type.
AUTO_INCREMENT is an attribute of a specific column of any numeric type (int or float), both signed and unsigned. When rows are inserted it automatically assigns sequential numbers, so you don't have to (e.g. by using LAST_INSERT_ID()). See http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
SERIAL is an alias that combines column type casting (BIGINT specifically), AUTO_INCREMENT, UNSIGNED and other attributes for a specific column (see quote from docs below). See https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.
SERIAL DEFAULT VALUE in the definition of an integer column is an alias for NOT NULL AUTO_INCREMENT UNIQUE.
From mysql doc
SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.
SERIAL DEFAULT VALUE in the definition of an integer column is an
alias for NOT NULL AUTO_INCREMENT UNIQUE.
If no value is specified for the AUTO_INCREMENT column, MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers. MySQL doesn't automatically decrease the autoincrement value when you delete a row. Reasons are:
Danger of broken data integrity (imagine multiple users perform
deletes or inserts...doubled entries may occur or worse)
Errors may occur when you use master slave replication or
transactions
Is it possible to create auto-increment based on a specific field? For example i have UserId and Status fields, so for each row with same UserId i need to auto-increment its Status, not global.
There is three thing that come to mind when I read your question. One was an auto incrementing field which acts as your ID number. Updating a table with data that has no unique ID number. Searching for fields with the same Userid to Status
Mt First example is of a creating a table and your AUTO_INCREMENTing number ID:
CREATE TABLE tableNameHere
(
UniqueID int NOT NULL AUTO_INCREMENT,
FirstName varchar(255) NOT NULL,
StatusOrYourColumn int(100) NOT NULL,
PRIMARY KEY (UniqueUD)
)
More on auto incrementation.
You may have already built your table and now want to 'add' additional and or modify your fields using ALTER:
ALTER TABLE tableNameHere StatusOrYourColumn INT AUTO_INCREMENT PRIMARY KEY
But be careful, you don't want to overwrite your settings that you have already set.
Another Thing that came to my mind when reading was where you said Status and Userid where the same. You can find these using the WHERE clause like so:
SELECT * FROM tableName WHERE tableName.Userid = anotherTableOrTableName.Status
Using these queries you can update, remake, alter and query your database table.
I am entering records in the MySQL DB. Now I want to have a "Serial_Number" field that increements automatically whenever a record is entered into the DB.
I don't want this "Serial_Number" field to be the primary key of the DB.
How can I create this field (with the attributes needed to be set).
I am using "SQL YOG" to access MySQL. If you are aware of the SQL YOG then tell me how to do that through SQL YOG.
The AUTO_INCREMENT column has to have a UNIQUE KEY constraint associated to it.
For instance, this will work just fine:
CREATE TABLE AutoNotId
(
Id INTEGER PRIMARY KEY,
Auto INTEGER AUTO_INCREMENT,
UNIQUE (Auto)
);
Edit:
The ALTER statement would look somewhat like this:
ALTER TABLE AutoNotId
MODIFY COLUMN Auto INTEGER AUTO_INCREMENT,
ADD UNIQUE (Auto);
I recommended, however the use of the long-hand syntax to specify the name of the UNIQUE constraint; But you can always refer to MySQL's Reference Manual for the exact specifications.
In MySQL tables can only have one auto increment field and they must be indexed.
There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value.
Is there a reason you don't want it to be the primary key?
If you want an incrementing value, you could fudge it by running updates after each insert:
SELECT MAX(serial) + 1 FROM myTable;
UPDATE myTable SET serial = <that number> WHERE id = ...
I don't think you can have an auto increment field:
CREATE TABLE `t` (`dd` int(11) NOT NULL)
ALTER TABLE `t` CHANGE `dd` `dd` INT( 11 ) NOT NULL AUTO_INCREMENT
MySQL said: Documentation
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
You cannot do this in MySQL. From the doc:
There can be only one AUTO_INCREMENT
column per table, it must be indexed,
and it cannot have a DEFAULT value. An
AUTO_INCREMENT column works properly
only if it contains only positive
values. Inserting a negative number is
regarded as inserting a very large
positive number. This is done to avoid
precision problems when numbers “wrap”
over from positive to negative and
also to ensure that you do not
accidentally get an AUTO_INCREMENT
column that contains 0.
For MyISAM and BDB tables, you can
specify an AUTO_INCREMENT secondary
column in a multiple-column key. See
Section 3.6.9, “Using AUTO_INCREMENT”.
create table mytable (
ID INT IDENTITY(1,1) PRIMARY KEY,
SN INT IDENTITY(1,1)
)