EN
MS SQL Server - add index to existing table
0 points
TODO: indexy na koniec
In this article, we would like to show you how to add index to an existing table in MS SQL Server.
Quick solution:
xxxxxxxxxx
1
CREATE INDEX [index_name]
2
ON [table_name] ([column1], [column2], [columnN]);
or
xxxxxxxxxx
1
ALTER TABLE [table_name]
2
ADD INDEX [index_name] ([column2], [column2], [columnN]);
To show how to add index to existing table, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will create an index for the salary
column in users
table.
Query:
xxxxxxxxxx
1
CREATE INDEX [salary_index]
2
ON [users] ([salary]);
Result:
1. Using query
xxxxxxxxxx
1
SHOW INDEX FROM [users] FROM [dirask]; -- where users-table_name, dirask-database_name

2. Using HeidiSQL

In this example, we will create an index on the name
and surname
columns in users
table.
Query:
xxxxxxxxxx
1
CREATE INDEX [full_name_index]
2
ON [users] ([name], [surname]);
Result:
1. Using query
xxxxxxxxxx
1
SHOW INDEX FROM [users] FROM [dirask]; -- where users-table_name, dirask-database_name

2. Using HeidiSQL

In this example, we will create an index on two columns using ALTER TABLE
statement.
Query:
xxxxxxxxxx
1
ALTER TABLE [users]
2
ADD INDEX [index_full_name] ([name], [surname]);
Result:
1. Using query
xxxxxxxxxx
1
SHOW INDEX FROM [users] FROM [dirask]; -- where users-table_name, dirask-database_name

2. Using HeidiSQL

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE [users] (
2
[id] INT IDENTITY(1,1),
3
[name] VARCHAR(50) NOT NULL,
4
[surname] VARCHAR(50) NOT NULL,
5
[salary] DECIMAL(15,2) NOT NULL,
6
PRIMARY KEY ([id])
7
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO [users]
2
( [name], [surname], [salary])
3
VALUES
4
('John', 'Stewart', '3512.00'),
5
('Chris', 'Brown', '1344.00'),
6
('Kate', 'Lewis', '6574.00'),
7
('Ailisa', 'Gomez', '6500.00'),
8
('Gwendolyn', 'James', '4200.00'),
9
('Simon', 'Collins', '3320.00'),
10
('Taylor', 'Martin', '1500.00'),
11
('Andrew', 'Thompson', '2100.00');