The SQL Indexes
The SQL Indexes
SQL Indexes are special lookup tables that are used to speed up the process of
data retrieval. They hold pointers that refer to the data stored in a database,
which makes it easier to locate the required data records in a database table.
SQL Indexes need their own storage space within the database. Despite that, the
users cannot view them physically as they are just performance tools.
An index in SQL can be created using the CREATE INDEX statement. This
statement allows you to name the index, to specify the table and which column
or columns to index, and to indicate whether the index is in an ascending or
descending order.
Syntax
Types of Indexes
There are various types of indexes that can be created using the CREATE
INDEX statement. They are:
Unique Index
Single-Column Index
Composite Index
Implicit Index
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A
unique index does not allow any duplicate values to be inserted into the table. It
is automatically created by PRIMARY and UNIQUE constraints when they are
applied on a database table, in order to prevent the user from inserting duplicate
values into the indexed table column(s). The basic syntax is as follows.
on table_name (column_name);
Single-Column Indexes
ON table_name (column_name);
Composite Indexes
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database
server when an object is created. For example, indexes are automatically created
when primary key and unique constraints are created on a table in MySQL
database.
An index can be dropped using SQL DROP command. Dropping an index can
effect the query performance in a database. Thus, an index needs to be dropped
only when it is absolutely necessary.
Count()
Sum()
Avg()
Min()
Max()
1. COUNT() Example
Task: Count the total number of customers in the Customers table.
CustomerID INT,
Name VARCHAR(50),
City VARCHAR(50)
);
FROM Customers;
Output:
total_customers
---------------
3
2. SUM() Example
Task: Calculate the total sales (sum of price) from the Orders table.
OrderID INT,
Product VARCHAR(50),
Price DECIMAL(10, 2)
);
FROM Orders;
Output:
total_sales
------------
1800.00
3. AVG() Example
Task: Find the average salary from the Employees table.
EmployeeID INT,
Name VARCHAR(50),
Salary DECIMAL(10, 2)
);
FROM Employees;
Output:
average_salary
---------------
60000.00
4. MIN() Example
Task: Find the youngest employee (minimum age) from the Employees table.
EmployeeID INT,
Name VARCHAR(50),
Age INT
);
FROM Employees;
Output:
youngest_employee
-----------------
28
5. MAX() Example
Task: Find the highest salary from the Employees table.
EmployeeID INT,
Name VARCHAR(50),
Salary DECIMAL(10, 2)
);
FROM Employees;
Output:
highest_salary
--------------
75000.00