The Wayback Machine - https://web.archive.org/web/20241127034525/https://www.geeksforgeeks.org/sql-indexes/
Open In App

SQL Indexes

Last Updated : 06 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An index is a schema object. It is used by the server to speed up the retrieval of rows by using a pointer. It can reduce disk I/O(input/output) by using a rapid path access method to locate data quickly.

An index helps to speed up select queries and where clauses, but it slows down data input, with the update and the insert statements. Indexes can be created or dropped with no effect on the data. In this article, we will see how to create, delete, and use the INDEX in the database.  

Creating an Index

Syntax

CREATE INDEX index

ON TABLE column;

where the index is the name given to that index TABLE is the name of the table on which that index is created and column is the name of that column for which it is applied. 

For Multiple Columns

Syntax:

CREATE INDEX index

ON TABLE (column1, column2,…..);

For Unique Indexes

Unique indexes are used for the maintenance of the integrity of the data present in the table as well as for fast performance, it does not allow multiple values to enter into the table.

Syntax:

CREATE UNIQUE INDEX index

ON TABLE column;

When Should Indexes be Created?

  • A column contains a wide range of values.
  • A column does not contain a large number of null values.
  • One or more columns are frequently used together in a where clause or a join condition.

When Should Indexes be Avoided?

  • The table is small
  • The columns are not often used as a condition in the query
  • The column is updated frequently

Removing an Index

Remove an index from the data dictionary by using the DROP INDEX command. 

Syntax

DROP INDEX index;

To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege. 

Altering an Index

To modify an existing table’s index by rebuilding, or reorganizing the index.

ALTER INDEX IndexName

ON TableName REBUILD;

Confirming Indexes

You can check the different indexes present in a particular table given by the user or the server itself and their uniqueness. 

Syntax:

SELECT * from USER_INDEXES;

It will show you all the indexes present in the server, in which you can locate your own tables too.

Renaming an Index

You can use the system-stored procedure sp_rename to rename any index in the database.

Syntax:

EXEC sp_rename

index_name,

new_index_name,

N’INDEX’;

SQL Server Database

Syntax:

DROP INDEX TableName.IndexName;  

Why SQL Indexing is Important?

Indexing is an important topic when considering advanced MySQL, although most people know about its definition and usage they don’t understand when and where to use it to change the efficiency of our queries or stored procedures by a huge margin.

Here are some scenarios along with their explanation related to Indexing:

  • When executing a query on a table having huge data ( > 100000 rows ), MySQL performs a full table scan which takes much time and the server usually gets timed out. To avoid this always check the explain option for the query within MySQL which tells us about the state of execution. It shows which columns are being used and whether it will be a threat to huge data. On basis of the columns repeated in a similar order in condition.
  • The order of the index is of huge importance as we can use the saitions, we can create an index for them in the same order to maximize the speed of the query. me index in many scenarios. Using only one index we can utilize it in more than one query which different conditions. like for example, in a query, we make a join with a table based on customer_id wards we also join another join based on customer_id and order_date. Then we can simply create a single index by the order of customer_id, order_date which would be used in both cases. This also saves storage.
  • We should also be careful to not make an index for each query as creating indexes also take storage and when the amount of data is huge it will create a problem. Therefore, it’s important to carefully consider which columns to index based on the needs of your application. In general, it’s a good practice to only create indexes on columns that are frequently used in queries and to avoid creating indexes on columns that are rarely used. It’s also a good idea to periodically review the indexes in your database and remove any that are no longer needed.
  • Indexes can also improve performance when used in conjunction with sorting and grouping operations. For example, if you frequently sort or group data based on a particular column, creating an index on that column can greatly improve performance. The index allows MySQL to quickly access and sort or group the data, rather than having to perform a full table scan.
  • In some cases, MySQL may not use an index even if one exists. This can happen if the query optimizer determines that a full table scan is faster than using the index.

Conclusion

  • Data retrieval is speed up by the usage of indexes.
  • They function as a database row’s table of contents.
  • Enhance query speed, however, inserts and updates might take longer.
  • Bitmap, Hash, and B-tree indexes are examples of typical types.
  • Indexes must be carefully selected and kept up-to-date in order for database operations to go smoothly.


Previous Article
Next Article

Similar Reads

Multiple Indexes vs Multi-Column Indexes
A database index is a data structure, typically organized as a B-tree, that is used to quickly locate and access data in a database table. Indexes are used to speed up the query process by allowing the database to quickly locate records without having to search through every row of the table. An index is a data structure in a database that is used
4 min read
SQL Show Indexes
In databases, indexes are set up to make finding and organizing data in tables faster. They help make searches better by giving faster access to rows in a table. An index is like a data structure linked to a table in the database. It helps the system quickly find and get rows based on columns that are part of it. Indexes play a critical role in opt
5 min read
SQL Queries on Clustered and Non-Clustered Indexes
Indexes in SQL improve query performance by simply locating data without scanning the entire table. There are two types which are clustered and non-clustered and each serves different purposes for optimizing data retrieval and performance. In this article, we will learn about the Clustered and Non-Clustered Indexes by understanding various perspect
6 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
Secondary Indexes on SET Collection in Cassandra
In this article, we will discuss the overview of Secondary Indexes on SET Collection in Cassandra and then will implement the exercise and will see how it actually works, and then finally will conclude the importance of Secondary Indexes on SET Collection. Let's discuss it one by one. Pre-requisite - Concept of indexing in Apache CassandraCollectio
2 min read
How to Compare Indexes of Tables From Two Different Databases in Oracle?
Structured Query Language supported by RDBMS(Relation Database Management Systems) such as Oracle, Mysql, PostgreSQL, and SQL Server. All relational database system support objects such as databases, tables, schema, indexes, views, functions, procedures, and many more. RDBMS system performs best when the schema is on write. To make these systems pe
3 min read
Secondary Indexes on MAP Collection in Cassandra
In this article, we will discuss the overview of Secondary Indexes on MAP Collection in Cassandra and then will implement the exercise and will see how it actually works, and then finally will conclude the importance of Secondary Indexes on MAP Collection. Let's discuss it one by one. Pre-requisite - Concept of indexing in Apache CassandraCollectio
4 min read
Secondary Indexes on LIST Collection in Cassandra
In this article, we will discuss the overview of Secondary Indexes on LIST Collection in Cassandra and then will implement the exercise and will see how it actually works, and then finally will conclude the importance of Secondary Indexes on LIST Collection. Let's discuss it one by one. Pre-requisite - Concept of indexing in Apache CassandraCollect
2 min read
SQL | Difference between functions and stored procedures in PL/SQL
Prerequisite: Procedures in PL/SQLFunctions in PL/SQL.Difference between functions and stored procedures in PL/SQL Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)): 1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and ret
3 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
Difference between SQL and T-SQL
SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, enabling operations like querying, updating, and deleting data. T-SQL (Transact-SQL), an extension of SQL developed by Microsoft, adds advanced features and procedural capabilities specifically for SQL Server. In this article, We will learn
4 min read
SQL Server | Convert Tables in T-SQL into XML
XML (Extensible Markup Language) is a widely-used markup language designed to store and transfer structured data between different systems and platforms. While HTML focuses on the visual representation of data OverviewXML is similar to HTML which is designed to structure and store data for sharing across different systems and platforms.Unlike HTML,
3 min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks. So, in
15+ min read
SQL Query to Convert DateTime to Date in SQL Server
In SQL Server, working with DateTime data types can be a bit complex for beginners. This is because DateTime includes both the date and time components, while many scenarios only require the date. Whether you're working with large datasets, performing data analysis, or generating reports, it's common to need the date portion only. In this article,
4 min read
NULL values in SQL
In SQL there may be some records in a table that do not have values or data for every field and those fields are termed as a NULL value. NULL values could be possible because at the time of data entry information is not available. So SQL supports a special value known as NULL which is used to represent the values of attributes that may be unknown o
4 min read
DBMS | SQL | Question 1
The statement that is executed automatically by the system as a side effect of the modification of the database is (A) backup (B) assertion (C) recovery (D) trigger Answer: (D) Explanation: Triggers are the SQL codes that are automatically executed in response to certain events on a particular table. These are used to maintain the integrity of the
1 min read
DBMS | SQL | Question 2
Which of the following command is used to delete a table in SQL? (A) delete (B) truncate (C) remove (D) drop Answer: (D) Explanation: drop is used to delete a table completelyQuiz of this Question
1 min read
SQL Query to Find Number of Employees According to Gender Whose DOB is Between a Given Range
Query in SQL is like a statement that performs a task. Here, we need to write a query that will find the number of employees according to gender whose DOB is in the given range. We will first create a database named “geeks” then we will create a table “department” in that database. Creating a Database : Use the below SQL statement to create a datab
2 min read
Working With JSON in SQL
JSON stands for Javascript Object Notation. It is mainly used in storing and transporting data. Mostly all NoSQL databases like MongoDB, CouchDB, etc., use JSON format data. Whenever your data from one server has to be transferred to a web page, JSON format is the preferred format as front-end applications like Android, iOS, React or Angular, etc.,
7 min read
Article Tags :
three90RightbarBannerImg