Your cart is currently empty!
Category: mysql
-
Khóa học miễn phí MySQL – Drop Index nhận dự án làm có lương
MySQL – Drop Index
Table of content
The DROP statement in MySQL database 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, like indexes, it will remove them permanently along with their associated data.
Therefore, we can drop any index from a database table using two different SQL DROP queries.
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.
The MySQL DROP INDEX Statement
The DROP INDEX statement in MySQL is used to delete an index from a table.
Syntax
Following is the syntax to drop an index using DROP INDEX statement −
DROP INDEX index_name ON table_name;
Example
In this example, we first create a new table CUSTOMERS and adding an index to one of its columns (AGE) using the following CREATE TABLE 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), INDEX(AGE) );
Now, create another index on CUSTOMERS table. We are using CREATE INDEX statement here −
CREATE INDEX NAME_INDEX ON CUSTOMERS (Name);
DROP INDEX Query −
Then, use the following query to drop the index created above.
DROP INDEX NAME_INDEX ON CUSTOMERS;
Verification
To verify if the index has been dropped, display the table definition using DESC query below −
DESC CUSTOMERS;
As we can see in the following table, the index on NAME column is dropped.
Field Type Null Key Default Extra ID int NO PRI NULL NAME varchar(20) NO NULL AGE int NO MUL NULL ADDRESS char(25) YES NULL SALARY decimal(18, 2) YES NULL The MySQL ALTER… DROP Statement
The ALTER DROP statement can also be used to drop an index in a MySQL table. This is just an alternative to the DROP INDEX statement, so it only works with the index that exists on a table.
Syntax
Following is the syntax of the DROP INDEX IF EXISTS in SQL −
ALTER TABLE table_name DROP INDEX index_name;
Example
Let us see another example to drop the index from the CUSTOMERS table using the ALTER… DROP command as shown below −
ALTER TABLE CUSTOMERS DROP INDEX AGE;
Verification
To verify if the index on AGE column has been dropped, display the table definition using DESC query below −
DESC CUSTOMERS;
As we can see in the following table, the index on NAME column is dropped.
Field Type Null Key Default Extra ID int NO PRI NULL NAME varchar(20) NO NULL AGE int NO NULL ADDRESS char(25) YES NULL SALARY decimal(18, 2) YES NULL Dropping PRIMARY KEY or UNIQUE Constraint
The DROP INDEX statement in MySQL does not usually drop indexes like PRIMARY KEY or UNIQUE constraints. To drop indexes associated with these constraints, we need to use the ALTER TABLE DROP command.
Syntax
Following is the syntax −
ALTER TABLE table_name DROP constraint_name;
Example
In this example, we are using the following query to drop the PRIMARY KEY constraint present on the ID column of CUSTOMERS table −
ALTER TABLE CUSTOMERS DROP PRIMARY KEY;
Verification
To verify whether the primary key constraint is dropped from the table, describe the ”temp” table using DESC command as follows −
DESC CUSTOMERS;
The PRIMARY KEY constraint is finally dropped! Look at the table below −
Field Type Null Key Default Extra ID int NO NULL NAME varchar(20) NO NULL AGE int NO NULL ADDRESS char(25) YES NULL SALARY decimal(18, 2) YES NULL Dropping an Index Using a Client Program
We have seen how to drop an index from a MySQL database using SQL queries. In addition to it, we can also use other client programs to perform the drop index operation in the MySQL database.
Syntax
Following are the syntaxes to drop an index from a MySQL database using various programming languages −
The MySQL PHP connector mysqli provides a function named query() to execute the DROP INDEX query in the MySQL database.
$sql = "DROP INDEX index_name ON tbl_name"; $mysqli->query($sql);
The MySQL NodeJS connector mysql2 provides a function named query() to execute the DROP INDEX query in the MySQL database.
sql= "DROP INDEX index_name ON tbl_name"; con.query(sql);
We can use the JDBC type 4 driver to communicate to MySQL using Java. It provides a function named executeUpdate() to execute the DROP INDEX query in the MySQL database.
String sql = "DROP INDEX index_name ON table_name"; statement.executeQuery(sql);
The MySQL Connector/Python provides a function named execute() to execute the DROP INDEX query in the MySQL database.
drop_index_query = "DROP INDEX index_name ON tbl_name" cursorObj.execute(drop_index_query);
Example
Following are the implementations of this operation in various programming languages −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $dbname = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } // printf(''Connected successfully.
''); // CREATE INDEX $sql = "DROP INDEX tid ON tutorials_table"; if ($mysqli->query($sql)) { printf("Index droped successfully!.
"); } if ($mysqli->errno) { printf("Index could not be droped!.
", $mysqli->error); } $mysqli->close();Output
The output obtained is as follows −
Index droped successfully!.
var mysql = require(''mysql2''); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); sql = "create database TUTORIALS" con.query(sql); sql = "USE TUTORIALS" con.query(sql); sql = "CREATE TABLE temp(ID INT, Name VARCHAR(255), age INT, Location VARCHAR(255));" con.query(sql); sql = "INSERT INTO temp values(1, ''Radha'', 29, ''Vishakhapatnam''),(2, ''Dev'', 30, ''Hyderabad'');" con.query(sql); //Creating Indexes sql = "CREATE INDEX sample_index ON temp (name) USING BTREE;" con.query(sql); sql = "CREATE INDEX composite_index on temp (ID, Name);" con.query(sql); //Displaying Indexes sql = "SHOW INDEXES FROM temp;" con.query(sql, function(err, result){ if (err) throw err console.log(result); console.log("--------------------------"); }); //Dropping Indexes sql = "DROP INDEX sample_index ON temp;" con.query(sql); sql = "DROP INDEX composite_index ON temp;" con.query(sql); //Displaying Indexes after deleting sql = "SHOW INDEXES FROM temp;" con.query(sql, function(err, result){ if (err) throw err console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- [ { Table: ''temp'', Non_unique: 1, Key_name: ''sample_index'', Seq_in_index: 1, Column_name: ''Name'', Collation: ''A'', Cardinality: 2, Sub_part: null, Packed: null, Null: ''YES'', Index_type: ''BTREE'', Comment: '''', Index_comment: '''', Visible: ''YES'', Expression: null }, { Table: ''temp'', Non_unique: 1, Key_name: ''composite_index'', Seq_in_index: 1, Column_name: ''ID'', Collation: ''A'', Cardinality: 2, Sub_part: null, Packed: null, Null: ''YES'', Index_type: ''BTREE'', Comment: '''', Index_comment: '''', Visible: ''YES'', Expression: null }, { Table: ''temp'', Non_unique: 1, Key_name: ''composite_index'', Seq_in_index: 2, Column_name: ''Name'', Collation: ''A'', Cardinality: 2, Sub_part: null, Packed: null, Null: ''YES'', Index_type: ''BTREE'', Comment: '''', Index_comment: '''', Visible: ''YES'', Expression: null } ] -------------------------- []
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class DropIndex { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String username = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println("Connected successfully...!"); //Drop index; String sql = "DROP INDEX tid ON tutorials_tbl"; statement.executeUpdate(sql); System.out.println("Index has been dropped Successfully...!"); connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! Index has been dropped Successfully...!
import mysql.connector #establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) cursorObj = connection.cursor() drop_index_query = "DROP INDEX idx_submission_date ON tutorials_tbl" cursorObj.execute(drop_index_query) connection.commit() print("Index dropped successfully.") cursorObj.close() connection.close()
Output
Following is the output of the above code −
Index dropped successfully.
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í MySQL – Constraints nhận dự án làm có lương
MySQL − Constraints
MySQL Constraints
The MySQL constraints can be used to set certain rules to the column(s) in a table. These constraints can restrict the type of data that can be inserted or updated in a particular column. This helps you to maintain the data accuracy and reliability in a table.
There are two types of MySQL constraints.
- Column level constraints: These type of constraints will only apply to a column in a table.
- Table level constraints: These constraints will apply to the complete table.
The commonly used constraints in MySQL are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, CREATE INDEX, AUTO_INCREMENT, etc.
Syntax
Following is the basic syntax to add a constraint for the column(s) in a table −
CREATE TABLE table_name ( Column_name1 datatype constraint, Column_name2 datatype constraint, Column_name3 datatype constraint, ......... );
MySQL NOT NULL Constraint
By default, a column in a MySQL table can contain NULL values. In some scenarios, we may want a particular column to not accept or contain NULL values. To do so, we can use the MySQL NOT NULL constraint.
This constraint enforces a specific field to always contain a value, which means that we cannot insert or update a record without adding a value to this field.
Example
In the following query, we are adding the NOT NULL constraint on the ID and NAME columns of the CUSTOMERS table. As a result, the ID and NAME columns will not accept NULL values at the time of record insertion.
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int );
Let”s try inserting records into this table. The following statement will insert a record into the CUSTOMERS table −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18);
But, if we try to insert records with NULL values as ID as −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(Null, ''Varun'', 26);
An error will be generated saying “Column ”ID” cannot be null”.
ERROR 1048 (23000): Column ''ID'' cannot be null
In the same way if we try to pass NULLs as values to the NAME column, similar error will be generated.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(3, Null, 19);
This will generate the following error −
ERROR 1048 (23000): Column ''NAME'' cannot be null
As we can see in the above queries, the first record is successfully inserted because it does not have null values in the ID and Name columns. Whereas, the second and third records are not inserted because we are trying to insert NULL values in the columns which shouldn”t be NULL.
MySQL UNIQUE Constraint
The UNIQUE constraint in MySQL ensures that every value in a column must be distinct. This means the column with the UNIQUE constraint cannot have the same value repeated; each value must be unique.
Note: We can have one or more UNIQUE constraints on a single table.
Example
The following query creates a UNIQUE constraint on the ID column of the CUSTOMERS table −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, UNIQUE (ID) );
Now, let us insert the following records into the above-created table −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18); INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Varun'', 26);
In the above code block, the second insert statement returned an error saying “Duplicate entry ”1” for key ”customers.ID” because the ID value we are inserting already exists in the table. Therefore, it is a duplicate and the query generates the following error −
ERROR 1062 (23000): Duplicate entry ''1'' for key ''customers.ID''
MySQL PRIMARY KEY Constraint
The PRIMARY KEY constraint in MySQL is used to uniquely identify each record in a table. This means that, if we define primary key on a particular column in a table, it must contain UNIQUE values, and cannot contain NULL values.
Note: We can have only a single primary key on a table.
Example
The following query creates a PRIMARY KEY on the ID column of the CUSTOMERS table −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, PRIMARY KEY (ID) );
Once the table is created, insert the following record into the above-created table −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES (1, ''Nikhil'', 18); Query OK, 1 row affected (0.01 sec)
Since we added the PRIMARY KEY constraint on the ID column, if you try to insert a record with duplicate ID value or NULL value, it will generate an error.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES (1, ''Varun'', 26); ERROR 1062 (23000): Duplicate entry ''1'' for key ''customers.PRIMARY'' INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES (NULL, ''Datta'', 19); ERROR 1048 (23000): Column ''ID'' cannot be null
As we can see in the above queries, the first insert statement is successfully inserted into the table. Whereas the second and third statements returned an error because they contain a duplicate and a NULL value in the primary key column i.e. (ID).
MySQL FOREIGN KEY Constraint
The FOREIGN KEY constraint in MySQL is used to link a field or collection of fields in one table to the primary key of another table.
A table with the foreign key is called a child table and the table with the primary key is called the parent table or referenced table.
Example
The following query creates a FOREIGN KEY on the CUST_ID column when the ORDERS table is created −
Table: Customers
CREATE TABLE CUSTOMERS ( CUST_ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, PRIMARY KEY (CUST_ID) );
Table: Orders
CREATE TABLE ORDERS ( ORDER_ID int NOT NULL, ORDER_NUMBER int NOT NULL, CUST_ID int, FOREIGN KEY (CUST_ID) REFERENCES CUSTOMERS (CUST_ID) );
MySQL CHECK Constraint
The CHECK constraint in MySQL restricts the range of values that can be inserted into a column. This constraint ensures that the inserted value in a column must be satisfied with the provided condition.
Example
The following query creates a CHECK constraint on the AGE column of the CUSTOMERS table, where it ensures that the age of the student must be 18 or older −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, CHECK (AGE >= 18) );
Once the table is created, we can insert the records into the above created table as shown below −
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18); INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(3, ''Datta'', 19);
Since we added the CHECK constraint on the AGE column such that the age of the student should be equal or greater than 18. If you try to insert a record with age value less than 18, an error will be generated.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(2, ''Varun'', 16); ERROR 3819 (HY000): Check constraint ''customers_chk_1'' is violated. INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(4, ''Karthik'', 15); ERROR 3819 (HY000): Check constraint ''customers_chk_1'' is violated.
Example
Here, the following query creates a CHECK constraint on multiple columns (AGE and ADDRESS) −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, ADDRESS varchar(40), CONSTRAINT CHECK_AGE CHECK (AGE >= 18 AND ADDRESS = "Mumbai") );
Now, let us insert the following records into the above-created table −
INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS) VALUES(1, ''Nikhil'', 18, ''Mumbai''); Query OK, 1 row affected (0.01 sec) INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS) VALUES(3, ''Datta'', 19, ''Delhi''); ERROR 3819 (HY000): Check constraint ''CHECK_AGE_AND_ADDRESS'' is violated.
The second insert statement returned an error because it is violating the condition of the check constraint i.e. (AGE >= 18 AND ADDRESS = “Mumbai”).
MySQL DEFAULT Constraint
The DEFAULT constraint in MySQL is used to assign a default value to a specific column in a table. This default value gets applied to any new records in the DEFAULT specified column when no other value is provided during insertion.
Example
In the following query, we are defining the DEFAULT constraint on the ADDRESS column of the CUSTOMERS table. We assigned “Mumbai” as default value when no value is inserted. −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, ADDRESS varchar(40) DEFAULT "Mumbai" );
Here, we are inserting the first two records without any value in the ADDRESS column. In the third record, we are inserting the ADDRESS value as ”Delhi”.
INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(1, ''Nikhil'', 18); INSERT INTO CUSTOMERS(ID, NAME, AGE) VALUES(2, ''Varun'', 16); INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS) VALUES(3, ''Datta'', 19, ''Delhi'');
Exeucte the following query to display the records inserted in the above-created table −
Select * from CUSTOMERS;
In the following output, we can see that the value in the ADDRESS column for the first two rows is by default “Mumbai”.
ID | NAME | AGE | ADDRESS |
---|---|---|---|
1 | Nikhil | 18 | Mumbai |
2 | Varun | 16 | Mumbai |
3 | Datta | 19 | Delhi |
MySQL CREATE INDEX Constraint
The CREATE INDEX constraint in MySQL is used to create indexes for one more columns in a table.
The indexes are used to fetch the data from the database much quicker. However, the users cannot see the indexes in action, instead, they are just used to speed up the searches and queries.
Example
Here, we are creating a table named CUSTOMERS using the query below −
CREATE TABLE CUSTOMERS ( ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int, ADDRESS varchar(40), PRIMARY KEY (ID) );
The following query creates an index named “index_address” on the ADDRESS column of the CUSTOMERS table −
CREATE INDEX index_address ON CUSTOMERS (ADDRESS);
MySQL AUTO_INCREMENT Constraint
When a AUTO_INCREMENT constraint is defined on a particular column of a table, it will automatically generate a unique number when a new record is inserted into that column.
By default, the starting value is 1, and it will automatically increment its value by 1 for each new record.
Example
The following query adds an AUTO_INCREMENT constraint on the ID column of the CUSTOMERS table −
CREATE TABLE CUSTOMERS ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(20) NOT NULL, AGE int, PRIMARY KEY (ID) );
In the insert statements below, we are not inserting ID values.
INSERT INTO STUDENTS(NAME, AGE) VALUES(''Nikhil'', 18); INSERT INTO STUDENTS(NAME, AGE) VALUES(''Varun'', 16); INSERT INTO STUDENTS(NAME, AGE) VALUES(''Datta'', 19);
Now, execute the following query to display the records of the above-created table −
Select * from CUSTOMERS;
As we can see in the STUDENTS table below, the values in the ID column are automatically incremented because of the AUTO_INCREMENT constraint on the ID column.
ID | NAME | AGE |
---|---|---|
1 | Nikhil | 18 |
2 | Varun | 16 |
3 | Datta | 19 |
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