Languages
[Edit]
EN

Mysql - create new column with index on existing database table with data

0 points
Created by:
Trenton-McKinney
618

We can achieve it by executing below query.

ALTER TABLE "posts"
	ADD COLUMN "category_id" BIGINT(20) UNSIGNED NOT NULL DEFAULT '1';

CREATE INDEX index_category_id ON posts ( category_id );

Just change:

  • database table - posts
  • column name - category_id
  • index name - index_category_id

Example

Create database, table and insert data.

CREATE DATABASE "post_tests";
USE "post_tests";

CREATE TABLE "posts" (
	"post_id" BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	"post_content" LONGTEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
	PRIMARY KEY ("post_id")
)
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
;

INSERT INTO "posts" ("post_id", "post_content") VALUES (1, 'post 1');
INSERT INTO "posts" ("post_id", "post_content") VALUES (2, 'post 2');
INSERT INTO "posts" ("post_id", "post_content") VALUES (3, 'post 3');

Screenshot 1:

Screenshot from Heidi SQL after execution above query - database schema
Screenshot from Heidi SQL after execution above query - database schema

Screenshot 2:

Screenshot from Heidi SQL after execution above query - inserted data
Screenshot from Heidi SQL after execution above query - inserted data

Query - create new column with index

ALTER TABLE "posts"
	ADD COLUMN "category_id" BIGINT(20) UNSIGNED NOT NULL DEFAULT '1';

CREATE INDEX index_category_id ON posts ( category_id );

Our database after execution

Screenshot 3:

database schema with new column and index
database schema with new column and index

Screenshot 4:

database data with new column and index and default value 1
database data with new column and index and default value 1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join