Category: sql

  • Khóa học miễn phí SQL – Create Index nhận dự án làm có lương

    SQL – Create Index

    Table of content


    An index is an effective way to quickly retrieve data from an SQL database. It is a database object that references the data stored in a table, which significantly improves query and application performance of a database.

    The process of indexing in SQL is similar to that of an index in a book: it is a database object in the form of a table, contains details of data location, and holds a separate storage space.

    Even though indexes help accelerate search queries, users are not able to directly see these indexes in action.

    What is SQL Index?

    An SQL index is a special lookup table that helps in efficiently searching or querying database tables to retrieve required data. For example, when we try to retrieve data from multiple tables using joins, indexes improve the query performance.

    Indexes are used to optimize the query performance of any Relational Database Management System (RDBMS) as data volumes grow. Hence, they are preferred to be used on frequently queried large database tables.

    Creating an SQL Index

    An index can be created on one or more columns of a table in an SQL database using the CREATE INDEX statement.

    Syntax

    Following is the syntax of CREATE INDEX statement in SQL −

    CREATE INDEX index_name
    ON table_name (column_name1, column_name2,... column_nameN);
    

    Here,

    • index_name This specifies the name of the index that you want to create.
    • table_name This specifies the name of the table on which you want to create the index.
    • (column_name1, column_name2…column_nameN) are the names of one or more columns on which the index is being created.

    Example

    To create an index on a database table, we first need to create a table. So, in this example, we are creating a table named CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS(
       ID INT NOT NULL,
       NAME VARCHAR(15) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS VARCHAR(25),
       SALARY DECIMAL(10, 4),
       PRIMARY KEY(ID));
    );
    

    Then, insert some values into the CUSTOMERS table using the following query −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', ''32'', ''Ahmedabad'', 2000),
    (2, ''Khilan'', ''25'', ''Delhi'', 1500),
    (3, ''Kaushik'', ''23'', ''Kota'', 2000),
    (4, ''Chaitali'', ''25'', ''Mumbai'', 6500),
    (5, ''Hardik'',''27'', ''Bhopal'', 8500),
    (6, ''Komal'', ''22'', ''Hyderabad'', 9000),
    (7, ''Muffy'', ''24'', ''Indore'', 5500);
    

    Once the table is created, create an index for the column named NAME in the CUSTOMERS table using the following query −

    CREATE INDEX index_name ON CUSTOMERS(NAME);
    

    Output

    When we execute the above query, the output is obtained as follows −

    Query OK, 0 rows affected (0.06 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    The following SHOW INDEX query is used to display all the indexes created on an existing table.

    SHOW INDEX FROM CUSTOMERS;
    

    In the list obtained, you can find the column name NAME, along with the ID in the list of indexes.

    Table Non_unique Key_name Seq_in_index Column_name
    customers 0 PRIMARY 1 ID
    customers 1 index_name 1 NAME

    Creating an Index on Multiple Fields

    We can also create an index on multiple fields (or columns) of a table using the CREATE INDEX statement. To do so, you just need to pass the name of the columns (you need to create the index on).

    Example

    Instead of creating a new table, let us consider the previously created CUSTOMERS table. Here, we are creating an index on the columns NAME and AGE using the following query −

    CREATE INDEX mult_index_data on CUSTOMERS(NAME, AGE);
    

    Output

    When we execute the above query, the output is obtained as follows −

    Query OK, 0 rows affected (0.04 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us list all the indexes that are created on the CUSTOMERS table using the following SHOW INDEX query −

    SHOW INDEX FROM CUSTOMERS;
    

    As you observe, you can find the column names NAME, and AGE along with ID (PRIMARY KEY), in the list of indexes.

    Table Non_unique Key_name Seq_in_index Column_name
    customers 0 PRIMARY 1 ID
    customers 1 index_name 1 NAME
    customers 1 mult_index_data 1 NAME
    customers 1 mult_index_data 2 AGE

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Drop Index nhận dự án làm có lương

    SQL – Drop Index

    Table of content


    The DROP statement in SQL is used to remove or delete an existing database object such as a table, index, view, or procedure. Whenever we use DROP statement with any of the database objects, it will remove them permanently along with their associated data.

    And when that database object is an index, the DROP INDEX statement in SQL is used.

    Dropping an SQL Index

    An SQL Index can be dropped from a database table using the DROP INDEX statement.

    It is important to understand that dropping an index can have a significant impact on the performance of your database queries. Therefore, only try to remove an index if you are sure that it is no longer required.

    Note − We cannot delete the indexes created by PRIMARY KEY or UNIQUE constraints. In order to delete them, you need to drop the constraints entirely using ALTER TABLE statement.

    Syntax

    Following is the syntax of the DROP INDEX command in SQL −

    DROP INDEX index_name ON table_name;
    

    Here,

    • index_name is the name of the index that you want to drop.
    • table_name is the name of the table that the index is associated with.

    Example

    In this example, we will learn how to drop an index on a table named CUSTOMERS, which can be created using the following query −

    CREATE TABLE CUSTOMERS(
       ID INT NOT NULL,
       NAME VARCHAR(15) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS VARCHAR(25),
       SALARY DECIMAL(10, 4),
       PRIMARY KEY(ID));
    );
    

    Now, insert some values into the above created table using the following query −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', ''32'', ''Ahmedabad'', 2000),
    (2, ''Khilan'', ''25'', ''Delhi'', 1500),
    (3, ''Kaushik'', ''23'', ''Kota'', 2000),
    (4, ''Chaitali'', ''25'', ''Mumbai'', 6500),
    (5, ''Hardik'',''27'', ''Bhopal'', 8500),
    (6, ''Komal'', ''22'', ''Hyderabad'', 9000),
    (7, ''Muffy'', ''24'', ''Indore'', 5500);
    

    Once the table is created, create an index on the column NAME in the CUSTOMERS table using the following query −

    CREATE INDEX INDEX_NAME on CUSTOMERS(NAME);
    

    Now, verify if the index is created on the CUSTOMERS table using the following SHOW INDEX query −

    SHOW INDEX FROM CUSTOMERS;
    

    On executing the above query, the index list is displayed as follows −

    Table Non_unique Key_name Seq_in_index Column_name
    customers 0 PRIMARY 1 ID
    customers 1 index_name 1 NAME

    Then, drop the same index INDEX_NAME in the CUSTOMERS table using the following DROP INDEX statement −

    DROP INDEX INDEX_NAME ON CUSTOMERS;
    

    Output

    If we compile and run the above query, the result is produced as follows −

    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Verify if the index for the column NAME is dropped using the following query −

    SHOW INDEX FROM CUSTOMERS;
    

    In the following list of indexes, you can observe that name of the column Name is missing.

    Table Non_unique Key_name Seq_in_index Column_name
    customers 0 PRIMARY 1 ID

    DROP INDEX with IF EXISTS

    The DROP INDEX IF EXISTS statement in SQL is used to drop an index only if it exists in the table. This statement is specifically useful when you want to drop an index, but you are not sure if the index exists. This clause is not supported by MySQL.

    The IF EXISTS clause ensures that the statement only removes the index if it exists. If the index does not exist, it simply terminates the execution.

    Syntax

    Following is the syntax of the DROP INDEX IF EXISTS in SQL −

    DROP INDEX IF EXISTS index_name
    ON table_name;
    

    Here,

    • index_name is the name of the index that you want to drop.
    • table_name is the name of the table that the index is associated with.

    Example

    In this example, let us try to drop an index in the SQL Server database.

    Let us consider the previously created table CUSTOMERS and let us create an index for the NAME column in the table using the following query −

    CREATE INDEX INDEX_NAME on CUSTOMERS(NAME);
    

    Then, let us drop it using the following query −

    DROP INDEX IF EXISTS INDEX_NAME ON CUSTOMERS;
    

    Output

    When we execute the above query, the output is obtained as follows −

    Commands completed successfully.
    

    Verification

    Let”s verify whether the index for the NAME is dropped or not using the following query −

    EXEC sys.sp_helpindex @objname = N''CUSTOMERS
    

    As you observe, the column NAME is deleted from the list of indexes.

    index_name index_description index_keys
    PK__CUSTOMER__3214EC27CB063BB7 clustered, unique, primary key locatedPRIMARY on PRIMARY ID

    Example

    Now, let us delete an index that doesn”t exist in the CUSTOMERS table using the following query −

    DROP INDEX IF EXISTS INDEX_NAME ON CUSTOMERS;
    

    Output

    Since no indexes with the specified name exist in the database, so the above query simply terminates the execution without giving any error.

    Commands completed successfully.
    

    Removing indexes created by PRIMARY KEY or UNIQUE

    The DROP INDEX statement does not drop indexes created by PRIMARY KEY or UNIQUE constraints. To drop indexes associated with them, we need to drop these constraints entirely. And it is done using the ALTER TABLE… DROP CONSTRAINT statement.

    Syntax

    Following is the syntax of the ALTER TABLE… DROP CONSTRAINT statement in SQL −

    ALTER TABLE table_name
    DROP CONSTRAINT constraint_name;
    

    Here,

    • table_name is the name of the table that contains the PRIMARY KEY constraint.
    • constraint_name is the name of the PRIMARY KEY constraint that you want to drop.

    Example

    Assume the previously created table (CUSTOMERS) and let us first list all the indexes that are created on the table using the following query −

    EXEC sys.sp_helpindex @objname = N''CUSTOMERS
    

    The list is displayed as follows −

    index_name index_description index_keys
    PK__CUSTOMER__3214EC27CB063BB7 nonclustered located on PRIMARYID ID

    Here, the PK__CUSTOMER__3214EC27CB063BB7 is the name of the PRIMARY KEY constraint that was created on the ID column of the CUSTOMERS table.

    Now, let us drop the index created by the PRIMARY KEY constraint.

    ALTER TABLE customers
    DROP CONSTRAINT PK__CUSTOMER__3214EC27CB063BB7;
    

    Output

    When we execute the above query, the output is obtained as follows −

    Commands completed successfully.
    

    Verification

    Verify whether it is dropped or not by listing the existing indexes using the following query −

    EXEC sys.sp_helpindex @objname = N''CUSTOMERS
    

    The following error is displayed because the list of indexes is empty.

    The object ''CUSTOMERS'' does not have any indexes, or you do not have permissions.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Show Indexes nhận dự án làm có lương

    SQL – Show Indexes

    Table of content


    The SQL Show Index Statement

    The SHOW INDEX is the basic SQL statement to retrieve the information about the indexes that have been defined on a table. However, the SHOW INDEX statement only works on MySQL RDBMS and is not a valid statement in the SQL Server.

    To list the indexes created on a table in SQL Server, a system stored procedure sp_helpindex is used.

    The result-set obtained from querying the SHOW INDEX statement on a MySQL table contains the index information.

    Syntax

    Following is the syntax of the SHOW INDEX statement in MySQL −

    SHOW INDEX FROM table_name;
    

    Example

    Following example demonstrates the working of SHOW INDEX statement in MySQL. First, create a table with the name CUSTOMERS in the MySQL database using the CREATE query below −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (20, 2),
       PRIMARY KEY (ID)
     );
    

    Let us now insert some values into the above created table using the following query −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', ''32'', ''Ahmedabad'', 2000),
    (2, ''Khilan'', ''25'', ''Delhi'', 1500),
    (3, ''Kaushik'', ''23'', ''Kota'', 2000),
    (4, ''Chaitali'', ''25'', ''Mumbai'', 6500),
    (5, ''Hardik'',''27'', ''Bhopal'', 8500),
    (6, ''Komal'', ''22'', ''Hyderabad'', 9000),
    (7, ''Muffy'', ''24'', ''Indore'', 5500);
    

    Once the data is inserted, create an index for the column NAME in the CUSTOMERS table using the following query −

    CREATE INDEX INDEX_NAME ON CUSTOMERS(NAME);
    

    Now, you can list all the indexes that are defined on the CUSTOMERS table using the following query −

    SHOW INDEX FROM CUSTOMERS;
    

    Output

    On executing the above query, the output is displayed as follows −

    Table Non_unique Key_name Seq_in_index Column_name
    customers 0 PRIMARY 1 ID
    customers 1 index_name 1 NAME

    Showing Indexes in SQL Server

    In SQL server, the system stored procedure sp_helpindex is used to retrieve the information about the indexes that have been defined on a table. It returns the result as a table that contains detailed information about each index, including the name, type, and columns.

    Syntax

    Following is the basic syntax to list indexes defined on a table in SQL Server −

    sp_helpindex [ @objname = ] ''name''
    

    Here, [ @objname = ] ”name” specifies the name of the table for which the index information is being retrieved. The index information includes −

    • index_name is the names of the columns that are included in index.
    • index_description is the brief description of the index such as the type of index (like clustered or non-clustered).
    • index_keys is the keys that are included in the index.

    Example

    CREATE INDEX INDEX_NAME on CUSTOMERS(NAME);
    

    Now, let us list all the indexes that are created on the CUSTOMERS table using the system stored procedure sp_helpindex as shown below −

    EXEC sys.sp_helpindex @objname = N''CUSTOMERS
    

    Output

    On executing the above query, the output is displayed as follows −

    index_name index_description index_keys
    INDEX_NAME

    nonclustered located on PRIMARY

    NAME
    PK__CUSTOMER__ 3214EC27755869D9

    clustered, unique, primary key located on PRIMARY

    ID

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Clustered Index nhận dự án làm có lương

    SQL – Clustered Index

    Table of content


    An index in a database is a data structure that helps to improve the speed of retrieving specific data from tables and views.

    Data in a table is stored in the form of an unordered data structure called a “Heap”, where rows are placed without any specific order. Thus, when retrieving data from a table, the query optimizer must scan the entire table to locate the requested rows. This process can be time-consuming, especially when we are dealing with large tables. To speed up the data retrieval, SQL provides a data object called index that stores and organizes table data in a specific way, allowing faster data access.

    SQL Clustered Indexes

    A clustered index in SQL is a type of index that determines the physical order in which the data values will be stored in a table.

    When a clustered index is defined on a specific column, during the creation of a new table, the data is inserted into that column in a sorted order. This helps in faster retrieval of data since it is stored in a specific order.

    • It is recommended to have only one clustered index on a table. If we create multiple clustered indexes on the same table, the table will have to store the same data in multiple orders which is not possible.
    • When we try to create a primary key constraint on a table, a unique clustered index is automatically created on the table. However, the clustered index is not the same as a primary key. A primary key is a constraint that imposes uniqueness on a column or set of columns, while a clustered index determines the physical order of the data in the table.
    MySQL database does not have a separate provisions for Clustered and Non-Clustered indexes. Clustered indexes are automatically created when PRIMARY KEY is defined on a table. And when the PRIMARY KEY is not defined, the first UNIQUE NOT NULL key is treated as a Clustered index.

    Syntax

    Following is the syntax to create a clustered index with SQL Server −

    CREATE INDEX index_name ON table_name(column_name [asc|desc])
    

    Where,

    • index_name: specifies the name you want to give to the index being created.
    • column_name: specifies the column(s) that will be indexed in the order specified.
    • asc|desc: specifies the order (asc – ascending, desc – descending) in which the data should be sorted. The default sorting order is ascending order.

    Example

    In this example, let us create a clustered index on a table in SQL Server. For that, we need to first create a table named CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS(
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE  INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (20, 2)
    );
    

    Now, insert some values into the CUSTOMERS table using the following query −

    INSERT INTO CUSTOMERS VALUES
    (7, ''Muffy'', ''24'', ''Indore'', 5500),
    (1, ''Ramesh'', ''32'', ''Ahmedabad'', 2000),
    (6, ''Komal'', ''22'', ''Hyderabad'', 9000),
    (2, ''Khilan'', ''25'', ''Delhi'', 1500),
    (4, ''Chaitali'', ''25'', ''Mumbai'', 6500),
    (5, ''Hardik'',''27'', ''Bhopal'', 8500),
    (3, ''Kaushik'', ''23'', ''Kota'', 2000);
    

    The table is successfully created in the SQL Server database.

    ID NAME AGE ADDRESS SALARY
    7 Muffy 24 Indore 5500.00
    1 Ramesh 32 Ahmedabad 2000.00
    6 Komal 22 Hyderabad 9000.00
    2 Khilan 25 Delhi 1500.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    3 Kaushik 23 Kota 2500.00

    Now, let us create a clustered index on the column named ID using the following query −

    CREATE CLUSTERED INDEX CLU_ID ON CUSTOMERS(ID ASC);
    

    Output

    On executing the above query, the output is displayed as follows −

    Commands Completed Successfully.
    

    Verification

    To verify if the clustered index is defined on ID column, check whether the records of CUSTOMERS table are sorted by retrieving them using the following query −

    SELECT * FROM CUSTOMERS;
    

    The records of the table are sorted in ascending order based on values in the column named ID.

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2500.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 9000.00
    7 Muffy 24 Indore 5500.00

    Creating Clustered Index on Multiple Columns

    With the following example, let us understand how clustered index works when it is created on multiple columns of a table.

    Instead of creating a new table, consider the previously created CUSTOMERS table and define a clustered index on multiple columns of this table, such as AGE and SALARY, using the following query −

    CREATE CLUSTERED INDEX MUL_CLUS_ID
    ON CUSTOMERS (AGE, SALARY ASC);
    

    Output

    When we execute the above query, the output is obtained as follows −

    Commands Completed Successfully.
    

    Verification

    Now, let us verify whether the values in the columns AGE and SALARY is sorted or not −

    SELECT * FROM CUSTOMERS;
    

    As we can observe in the table below, the records are sorted only based on the values in AGE column and not with the values in SALARY column. So, it is recommended to have only one clustered index on a table.

    ID NAME AGE ADDRESS SALARY
    6 Komal 22 Hyderabad 9000.00
    3 Kaushik 23 Kota 2500.00
    7 Muffy 24 Indore 5500.00
    2 Khilan 25 Delhi 1500.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    1 Ramesh 32 Ahmedabad 2000.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Unique Index nhận dự án làm có lương

    SQL – Unique Indexes

    Table of content


    SQL Unique Indexes

    The SQL Unique Index ensures that no two rows in the indexed columns of a table have the same values (no duplicate values allowed).

    A unique index can be created on one or more columns of a table using the CREATE UNIQUE INDEX statement in SQL.

    Following are the points to be noted before creating a Unique Index on a table −

    • If the unique index is only created on a single column, the rows in that column will be unique.
    • If a single column contains NULL in multiple rows, we cannot create a unique index on that column.
    • If the unique index is created on multiple columns, the combination of rows in these columns will be unique.
    • We cannot create a unique index on multiple columns if the combination of columns contains NULL in more than one row.

    Syntax

    Following is the syntax for creating a UNIQUE INDEX in SQL −

    CREATE UNIQUE INDEX index_name
    ON table_name (column1, column2, ..., columnN);
    

    Here,

    • index_name is the name of the index that you want to create.
    • table_name is the name of the table on which you want to create the index.
    • (column1, column2, …., columnN) are the names of one or more columns on which the unique index is being created.

    Example

    First of all, let us create a table named CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR(15) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS VARCHAR(25),
       SALARY DECIMAL(10, 4),
       PRIMARY KEY(ID)
    );
    

    Insert some values into the above-created table using the following query −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', ''32'', ''Ahmedabad'', 2000),
    (2, ''Khilan'', ''25'', ''Delhi'', 1500),
    (3, ''kaushik'', ''23'', ''Kota'', 2000),
    (4, ''Chaitali'', ''26'', ''Mumbai'', 6500),
    (5, ''Hardik'',''27'', ''Bhopal'', 8500),
    (6, ''Komal'', ''22'', ''Hyderabad'', 9000),
    (7, ''Muffy'', ''24'', ''Indore'', 5500);
    

    Once the table is created, let us create a unique index for the column named SALARY in the CUSTOMERS table using the following query −

    CREATE UNIQUE INDEX UNIQUE_ID ON CUSTOMERS (SALARY);
    

    But, when we execute the above query, the output is obtained as follows −

    ERROR 1062 (23000): Duplicate entry ''2000.00'' for key ''customers.UNIQUE_ID''
    

    Since a unique index could not be created on SALARY column (due to duplicate values), let us create Unique Index on the NAME column of the same table, using the following query −

    CREATE UNIQUE INDEX UNIQUE_ID ON CUSTOMERS (NAME);
    

    Output

    When we execute the above query, the output is obtained as follows −

    Query OK, 0 rows affected (0.03 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Let”s verify whether the unique index for the column NAME is created or not using the following query −

    SHOW INDEX FROM CUSTOMERS;
    

    As you observe the output below, you can find the column NAME along with the ID (PRIMARY KEY) in the list of indexes.

    Table Non_unique Key_name Seq_in_index Column_name
    customers 0 PRIMARY 1 ID
    customers 0 UNIQUE_ID 1 NAME

    Updating with Duplicate Values

    If we try to update the columns that have unique index with duplicate values, the database engine generates an error.

    Example

    Assume the previously created CUSTOMERS table and create a unique index on the column named ADDRESS using the following query −

    CREATE UNIQUE INDEX ADD_UNIQUE_INDEX ON CUSTOMERS(ADDRESS);
    

    Now, let us update the value in the column named ADDRESS with a duplicate (already existing data) value using the following query −

    UPDATE CUSTOMERS SET ADDRESS = ''Mumbai'' WHERE ADDRESS = ''Delhi
    

    Output

    On executing the above query, the output is displayed as follows −

    ERROR 1062 (23000): Duplicate entry ''Mumbai'' for key ''customers.ADD_UNIQUE_INDEX''
    

    Creating a unique index on Multiple Fields

    We can also create a unique index on multiple fields or columns of a table using the CREATE UNIQUE INDEX statement. To do so, you just need to pass the name of the columns (you need to create the index on) to the query.

    Example

    Instead of creating a new table, let us consider the previously created CUSTOMERS table. We will create a unique index on the columns NAME and AGE using the following query −

    CREATE UNIQUE INDEX MUL_UNIQUE_INDEX ON CUSTOMERS(NAME, AGE);
    

    Output

    When we execute the above query, the output is obtained as follows −

    Query OK, 0 rows affected (0.04 sec)
    Records: 0  Duplicates: 0  Warnings: 0.
    

    Verification

    Now, let us list all the indexes that are created on the CUSTOMERS table using the following query −

    SHOW INDEX FROM CUSTOMERS;
    

    As you observe you can find the column names NAME, and AGE along with the ID (PRIMARY KEY) in the list of indexes.

    Table Non_unique Key_name Seq_in_index Column_name
    customers 0 PRIMARY 1 ID
    customers 0 MUL_UNIQUE_INDEX 1 NAME
    customers 0 MUL_UNIQUE_INDEX 2 AGE

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Non-Clustered Index nhận dự án làm có lương

    SQL – Non-Clustered Index

    Table of content


    SQL Non-Clustered Indexes

    The SQL Non-Clustered index is similar to the Clustered index. When defined on a column, it creates a special table which contains the copy of indexed columns along with a pointer that refers to the location of the actual data in the table. However, unlike Clustered indexes, a Non-Clustered index cannot physically sort the indexed columns.

    Following are some of the key points of the Non-clustered index in SQL −

    • The non-clustered indexes are a type of index used in databases to speed up the execution time of database queries.
    • These indexes require less storage space than clustered indexes because they do not store the actual data rows.
    • We can create multiple non-clustered indexes on a single table.
    MySQL does not have the concept of Non-Clustered indexes. The PRIMARY KEY (if exists) and the first NOT NULL UNIQUE KEY(if PRIMARY KEY does not exist) are considered clustered indexes in MySQL; all the other indexes are called Secondary Indexes and are implicitly defined.

    To get a better understanding, look at the following figure illustrating the working of non-clustered indexes −

    Non-Clustered

    Assume we have a sample database table with two columns named ID and NAME. If we create a non-clustered index on a column named ID in the above table, it will store a copy of the ID column with a pointer that points to the specific location of the actual data in the table.

    Syntax

    Following is the syntax to create a non-clustered index in SQL Server −

    CREATE NONCLUSTERED INDEX index_name
    ON table_name (column_name)
    

    Here,

    • index_name: holds the name of non-clustered index.
    • table_name: holds the name of the table where you want to create the non-clustered index.
    • column_name: holds the name of the column that you want to define the non-clustered index on.

    Example

    Let us create a table named CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS(
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE  INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (20, 2),
    );
    

    Let us insert some values into the above-created table using the following query −

    INSERT INTO CUSTOMERS VALUES
    (7, ''Muffy'', ''24'', ''Indore'', 5500),
    (1, ''Ramesh'', ''32'', ''Ahmedabad'', 2000),
    (6, ''Komal'', ''22'', ''Hyderabad'', 9000),
    (2, ''Khilan'', ''25'', ''Delhi'', 1500),
    (4, ''Chaitali'', ''25'', ''Mumbai'', 6500),
    (5, ''Hardik'',''27'', ''Bhopal'', 8500),
    (3, ''Kaushik'', ''23'', ''Kota'', 2000);
    

    The table is successfully created in the SQL database.

    ID NAME AGE ADDRESS SALARY
    7 Muffy 24 Indore 5500.00
    1 Ramesh 32 Ahmedabad 2000.00
    6 Komal 22 Hyderabad 9000.00
    2 Khilan 25 Delhi 1500.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    3 Kaushik 23 Kota 2500.00

    Now, let us create a non-clustered index on a single column named ID using the following query −

    CREATE NONCLUSTERED INDEX NON_CLU_ID
    ON customers (ID ASC);
    

    Output

    On executing the above query, the output is displayed as follows −

    Commands Completed Successfully.
    

    Verification

    Let us retrieve all the indexes that are created on the CUSTOMERS table using the following query −

    EXEC sys.sp_helpindex @objname = N''CUSTOMERS
    

    As we observe, we can find the column named ID in the list of indexes.

    index_name index_description index_keys
    1 NON_CLU_ID nonclustered located on PRIMARY ID

    Now, retrieve the CUSTOMERS table again using the following query to check whether the table is sorted or not −

    SELECT * FROM CUSTOMERS;
    

    As we observe, the non-clustered index does not sort the rows physically instead, it creates a separate key-value structure from the table data.

    ID NAME AGE ADDRESS SALARY
    7 Muffy 24 Indore 5500.00
    1 Ramesh 32 Ahmedabad 2000.00
    6 Komal 22 Hyderabad 9000.00
    2 Khilan 25 Delhi 1500.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    3 Kaushik 23 Kota 2500.00

    Creating Non-Clustered Index on Multiple Columns

    Instead of creating a new table, let us consider the previously created CUSTOMERS table. Now, try to create a non-clustered index on multiple columns of the table such as ID, AGE and SALARY using the following query −

    CREATE NONCLUSTERED INDEX NON_CLUSTERED_ID
    ON CUSTOMERS (ID, AGE, SALARY);
    

    Output

    The below query will create three separate non-clustered indexes for ID, AGE, and SALARY.

    Commands Completed Successfully.
    

    Verification

    Let us retrieve all the indexes that are created on the CUSTOMERS table using the following query −

    EXEC sys.sp_helpindex @objname = N''CUSTOMERS
    

    As we observe, we can find the column names ID, AGE and SALARY columns in the list of indexes.

    index_name index_description index_keys
    1 NON_CLU_ID nonclustered located on PRIMARY ID, AGE, SALARY

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Injection nhận dự án làm có lương

    SQL – Injection

    Table of content


    If you take a user input through a webpage and insert it into an SQL database, there is a chance that you have left yourself wide open for a security issue known as the SQL Injection. This chapter will teach you how to help prevent this from happening and help you secure your scripts and SQL statements in your server side scripts such as a PERL Script.

    SQL Injection

    SQL Injection is a type of security attack that exploits a vulnerability in a database by executing malicious queries. This will allow attackers to access sensitive data, tamper it and also delete it permanently.

    Injection usually occurs when you ask a user for input, like their name and instead of a name they give you a SQL statement that you will unknowingly run on your database. Never trust user provided data, process this data only after validation; as a rule, this is done by Pattern Matching.

    Example

    In the example below, the name is restricted to the alphanumerical characters plus underscore and to a length between 8 and 20 characters (you can modify these rules as needed).

    if (preg_match("/^w{8,20}$/", $_GET[''username''], $matches)) {
       $result = mysqli_query("SELECT * FROM CUSTOMERS
          WHERE name = $matches[0]");
    } else {
       echo "user name not accepted";
    }
    

    To demonstrate the problem, consider this excerpt −

    // supposed input
    $name = "Qadir DELETE FROM CUSTOMERS;";
    mysqli_query("SELECT * FROM CUSTOMSRS WHERE name=''{$name}''");
    

    The function call is supposed to retrieve a record from the CUSTOMERS table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces. But here, by appending an entirely new query to $name, the call to the database turns into disaster; the injected DELETE query removes all records from the CUSTOMERS table.

    Fortunately, if you use MySQL, the mysqli_query() function does not permit query stacking or executing multiple SQL queries in a single function call. If you try to stack queries, the call fails.

    However, other PHP database extensions, such as SQLite and PostgreSQL happily perform stacked queries, executing all the queries provided in one string and creating a serious security problem.

    Preventing SQL Injection

    You can handle all escape characters smartly in scripting languages like PERL and PHP. The MySQL extension for PHP provides the function mysql_real_escape_string() to escape input characters that are special to MySQL.

    if (get_magic_quotes_gpc()) {
       $name = stripslashes($name);
    }
    $name = mysql_real_escape_string($name);
    mysqli_query("SELECT * FROM CUSTOMERS WHERE name=''{$name}''");
    

    The LIKE Quandary

    To address the LIKE quandary, a custom escaping mechanism must convert user-supplied ”%” and ”_” characters to literals. Use addcslashes(), a function that lets you specify a character range to escape.

    $sub = addcslashes(mysql_real_escape_string("%str"), "%_");
    // $sub == %str_
    mysqli_query("SELECT * FROM messages
       WHERE subject LIKE ''{$sub}%''");
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Comments nhận dự án làm có lương

    SQL – Comments

    Table of content


    A comment is a piece of text that is used in programming languages to provide additional information. These comments are ignored by the compiler and do not affect the program”s functionality. They are not visible in the output after the execution of code. Their purpose is to make the source code easier for human to understand more clearly.

    SQL Comments

    In SQL, comments can be used to explain a particular section of a query; or to skip the execution of statement. So, whenever a line of code is marked as a comment in a program, it is not executed.

    There are two types of comments used in MySQL database, they are as follows −

    • Single-line comments
    • Multi-line comments

    Single Line Comments

    The SQL single line comments starts with two consecutive hyphens (i.e. –) and extends to the end of the line. The text after the hyphens will not be executed.

    Syntax

    Following is the syntax of SQL single line comment −

    -- This is a single-line comment
    

    Example

    In the following query, we are using a single line comment to write a text −

    -- Will fetch all the table records
    SELECT * from table;
    

    Example

    Here, we have a SELECT statement that retrieves data from a table named CUSTOMERS. Though we have an ORDER BY clause in this statement, since we have commented that part, this query just retrieves the records in the CUSTOMERS table without sorting the result −

    SELECT * FROM CUSTOMERS -- ORDER BY NAME ASC;
    

    Example

    Now, we are using the single line comment to ignore the last statement −

    SELECT * FROM CUSTOMERS;
    SELECT * FROM EMPLOYEES;
    -- SELECT * FROM ORDERS WHERE ID = 6;
    

    Multi-Line Comments

    The SQL multi line comments are used to comment out multiple lines or a block of SQL code. It starts with /* and ends with */. Entire text between these delimiters (/*…*/) will be ignored and considered as a comment.

    Syntax

    Following is the syntax of SQL multi line comments −

    /* This is a
       multi-line
       comment */
    

    Example

    The following example uses multi-line comment as an explanation of the query −

    /*following query
    will fetch all the
    table records./*
    SELECT * from CUSTOMERS;
    

    Example

    Here, we are using the multi-line comments (/*….*/) to ignore a part of the query, making it as a comment −

    SELECT ID /*AGE, SALARY*/
    FROM CUSTOMERS WHERE SALARY = 1500.00;
    

    Example

    In the following query, we are ignoring multiple statements using a multi-line comment −

    /*SELECT * FROM CUSTOMERS;
    SELECT * FROM EMPLOYEE;*/
    SELECT * FROM ORDERS WHERE ID = 6;
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Wildcards nhận dự án làm có lương

    SQL – Wildcards



    SQL Wildcards

    SQL Wildcards are special characters used as substitutes for one or more characters in a string. They are used with the LIKE operator in SQL, to search for specific patterns in character strings or compare various strings.

    The LIKE operator in SQL is case-sensitive, so it will only match strings that have the exact same case as the specified pattern.

    Following are the most commonly used wildcards in SQL −

    S.No. Wildcard & Description
    1

    The percent sign (%)

    Matches one or more characters.

    Note − MS Access uses the asterisk (*) wildcard character instead of the percent sign (%) wildcard character.

    2

    The underscore (_)

    Matches one character.

    Note − MS Access uses a question mark (?) instead of the underscore (_) to match any one character.

    The percent sign (%) represents zero, one, or multiple characters within a string. The underscore (_) represents a single character or number. These symbols can also be used in combination to perform complex pattern searching and matching in SQL queries.

    Syntax

    Following is the basic syntax to use wildcard characters −

    SELECT * FROM table_name
    WHERE column_name LIKE [wildcard_pattern];
    

    We can combine N number of conditions using the AND or the OR operators. Here, the [wildcard_pattern] can represent any numeric or string value.

    The following table demonstrates various ways of using wildcards in conjunction with the LIKE operator within a WHERE clause:

    S.No. Statement & Description
    1

    WHERE SALARY LIKE ”200%”

    Finds any values that start with 200.

    2

    WHERE SALARY LIKE ”%200%”

    Finds any values that have 200 in any position.

    3

    WHERE SALARY LIKE ”_00%”

    Finds any values that have 00 in the second and third positions.

    4

    WHERE SALARY LIKE ”2_%_%”

    Finds any values that start with 2 and are at least 3 characters in length.

    5

    WHERE SALARY LIKE ”%2”

    Finds any values that end with 2.

    6

    WHERE SALARY LIKE ”_2%3”

    Finds any values that have a 2 in the second position and end with a 3.

    7

    WHERE SALARY LIKE ”2___3”

    Finds any values in a five-digit number that start with 2 and end with 3.

    Example

    Firstly, let us create a table named CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    The following INSERT query adds records into the CUSTOMERS table −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00),
    (7, ''Muffy'', 24, ''Indore'', 10000.00);
    

    The table will be created as −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Here, we are displaying all the records from the CUSTOMERS table where the SALARY starts with 200.

    SELECT * FROM CUSTOMERS WHERE SALARY LIKE ''200%
    

    Output

    This would produce the following result.

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    3 Kaushik 23 Kota 2000.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Min & Max nhận dự án làm có lương

    SQL – MIN() – MAX() function

    Table of content


    The MIN() and MAX() functions in SQL are aggregate functions. They are used to compare values in a set and, retrieve the maximum and minimum values respectively.

    An aggregate function is a mathematical computation that takes a range of values as input and yields a single value expression, representing the significance of the provided data.

    MAX() and MIN() aggregate functions are generally used in two ways:

    • As functions, they are used with the GROUP BY clause of the SELECT statement.

    • As expressions, they are used with a subquery and HAVING clause of SELECT statement.

    The SQL MAX() Function

    The MAX() function compares the values in a column and returns the largest value among them.

    Syntax

    Following is the syntax of SQL MAX() function −

    MAX(column_name);
    

    Example

    In the following example, we are running a query for MAX() function on a table named CUSTOMERS. The objective is to retrieve the maximum salary value from this table. First of all, let us create the CUSTOMERS table using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now, insert values into this table using the INSERT statement as follows −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00),
    (7, ''Muffy'', 24, ''Indore'', 10000.00);
    

    The CUSTOMERS table will be created as −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Here, we are comparing the salaries of CUSTOMERS and retrieving the maximum salary using the following query −

    SELECT MAX(SALARY) FROM CUSTOMERS;
    

    When the above query is executed, the result is displayed as −

    MAX(SALARY)
    10000.0000

    HAVING with MAX() Function

    In the following query, we are fetching the ID, NAME, and SALARY of the CUSTOMERS using the MAX() function along with HAVING clause.

    SELECT ID, NAME, SALARY
    FROM CUSTOMERS
    GROUP BY NAME, ID
    HAVING MAX(SALARY) < 8000;
    

    When the above query is executed, we get the details of the employees whose maximum salary is less than 8000 −

    ID NAME SALARY
    1 Ramesh 2000.00
    2 Khilan 1500.00
    3 Kaushik 2000.00
    4 Chaitali 6500.00
    6 Komal 4500.00

    MAX() Function in Subqueries

    In the following example, we are using the MAX() function in a subquery to retrieve the record with maximum salary, from the CUSTOMERS table.

    SELECT * FROM CUSTOMERS
    WHERE SALARY = (SELECT MAX(SALARY) FROM CUSTOMERS);
    

    When we execute the above query, we will get the following result −

    ID NAME AGE ADDRESS SALARY
    7 Muffy 24 Indore 10000.00

    MAX() Function with Strings

    This query retrieves the maximum value (alphabetically) among the names of customers in the CUSTOMERS table using the MAX() function −

    SELECT MAX(NAME) AS max_name FROM CUSTOMERS;
    

    Following is the result of the above query −

    max_name
    Ramesh

    Aliases with MAX() Function

    In the following example, we use the MAX() function to retrieve the record containing maximum age from the CUSTOMERS table. We are displaying the results as a new column with the alias “max_age”.

    SELECT MAX(age) AS ''max_age'' FROM CUSTOMERS;
    

    Following is the output of the above query −

    max_age
    32

    The SQL MIN() Function

    The MIN() function compares values in a column and returns the smallest value among them.

    Syntax

    Following is the syntax of SQL MIN() function −

    MIN(column_name);
    

    Example

    In this example, we are comparing values in the SALARY column of CUSTOMERS table and displaying the minimum salary using the following query −

    SELECT MIN(SALARY) FROM CUSTOMERS;
    

    When the above query is executed, the result is displayed as −

    MIN(SALARY)
    1500.0000

    HAVING with MIN() Function

    In the following query, we are fetching the ID, NAME, and SALARY of the CUSTOMERS using the MIN() function along with HAVING clause.

    SELECT ID, NAME, SALARY
    FROM CUSTOMERS
    GROUP BY NAME, ID
    HAVING MIN(SALARY) > 5000;
    

    When the above query is executed, we get the details of the maximum salary for employees whose minimum salary is more than 5000, as we can see in the table that follows −

    ID NAME MAX_Salary
    4 Chaitali 6500.0000
    5 Hardik 8500.0000
    7 Muffy 10000.0000

    MIN() Function in Subqueries

    In the following example, we are using the MIN() function in a subquery to retrieve the record with minimum salary, from the CUSTOMERS table.

    SELECT * FROM CUSTOMERS
    WHERE SALARY = (SELECT MIN(SALARY) FROM CUSTOMERS);
    

    When we execute the above query, we will get the following result −

    ID NAME AGE ADDRESS SALARY
    2 Khilan 25 Delhi 1500.00

    MIN() Function with Strings

    Following is the query to retrieve the minimum value (alphabetically) among the names of customers in the CUSTOMERS table using the MIN() function −

    SELECT MIN(NAME) AS min_first_name FROM CUSTOMERS;
    

    Following is the result of the above query −

    min_first_name
    Chaitali

    Aliases with MIN() Function

    Following is the SQL query that will fetch the minimum age from the CUSTOMERS table using the MIN() function −

    SELECT MIN(age) AS ''min_age'' FROM CUSTOMERS;
    

    When we execute the above query, the minimum value in the age field is displayed as shown below.

    min_age
    22

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc