SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL GROUP BY SQL Having SQL In SQL INSERT INTO SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL Index

Example Table

We will create a table named employees to demonstrate SQL indexing:


        CREATE TABLE employees (
            employee_id INT PRIMARY KEY,
            first_name VARCHAR(50),
            last_name VARCHAR(50),
            department VARCHAR(50)
        );
        

Creating the Table

To create the table, use the following SQL command:


        CREATE TABLE employees (
            employee_id INT PRIMARY KEY,
            first_name VARCHAR(50),
            last_name VARCHAR(50),
            department VARCHAR(50)
        );
        

Result:

Command CREATE TABLE employees (employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), department VARCHAR(50));
Result
  • A table named employees is created.

Creating an Index

To create an index on the last_name column, use the following SQL command:


        CREATE INDEX idx_last_name ON employees (last_name);
        

Result:

Command CREATE INDEX idx_last_name ON employees (last_name);
Result
  • An index named idx_last_name is created on the last_name column of the employees table.

Querying Data with Index

To query data using the index, use the following SQL command:


        SELECT * FROM employees WHERE last_name = 'Smith';
        

Result:

Command SELECT * FROM employees WHERE last_name = 'Smith';
Result
  • Returns all rows from the employees table where the last_name is 'Smith'. The query performance is improved due to the index.

Important Considerations

When creating indexes, consider the following: