Your cart is currently empty!
Category: mysql
-
Khóa học miễn phí MySQL – VARCHAR nhận dự án làm có lương
MySQL – VARCHAR
Table of content
The MySQL Varchar Data Type
The MySQL VARCHAR data type is used to store variable-length character strings, having a length up to 65,535 bytes.
In MySQL, when you store text in a VARCHAR column, it needs a little extra space to keep track of how long the text is. This extra space can be either 1 or 2 bytes, depending on the length of the text. If the text is short (less than 255 characters), it uses 1 byte for length. For longer text, it uses 2 bytes.
The total size of data plus the length info cannot exceed 65,535 bytes for a row in a table.
Example
In the following query, we are creating a new table named test_table that has two columns column1 and column2.
As we can see in the below code block, the columns (column1 = 32765 and column2 = 32766) makes 65531 bytes. These columns will take 2 bytes each as a length prefix. Therefore, the columns totally make 32765+2+32766+2 = 65535 bytes −
CREATE TABLE test_table ( column1 VARCHAR(32765) NOT NULL, column2 VARCHAR(32766) NOT NULL )CHARACTER SET ''latin1'' COLLATE LATIN1_DANISH_CI;
Output
Following is the output of the above code −
Query OK, 0 rows affected (0.03 sec)
Example
Now, let us create another table test_table2 and provide 32766 and 32766 to both the columns (column1 and column2) −
CREATE TABLE test_table2 ( column1 VARCHAR(32766) NOT NULL, --error column2 VARCHAR(32766) NOT NULL )CHARACTER SET ''latin1'' COLLATE LATIN1_DANISH_CI;
Output
As we can see in the output below, an error is generated because the row size (32766 +2 +32766 +2 = 65536) exceeds the maximum limit (65,535) −
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
Example
Here, we are creating another table named CUSTOMERS using the following query −
CREATE TABLE CUSTOMERS ( ID int PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(3) );
Following is the output obtained −
Query OK, 0 rows affected (0.03 sec)
Now, we are inserting a string into NAME column where the length is greater than the length of VARCHAR column −
INSERT INTO CUSTOMERS (NAME) VALUES (''Rahul'');
Output
As a result, MySQL will generate an error given below −
ERROR 1406 (22001): Data too long for column ''NAME'' at row 1
Example
MySQL does not count the trailing spaces when inserting a value. Instead it truncates the trailing spaces.
Let us insert a value into the NAME column that has trailing spaces −
INSERT INTO CUSTOMERS (NAME) VALUES (''ABC '');
Output
As we can see in the output below, MySQL issued a warning −
Query OK, 1 row affected, 1 warning (0.02 sec)
Example
In the following query, we are trying to check the length of the values in NAME column −
SELECT ID, NAME, length(NAME) FROM CUSTOMERS;
The result produced is as follows −
ID NAME length(NAME) 1 ABC 3 Now, let us execute the below query to display the warnings that issued on the above insertion operation −
SHOW warnings;
The result produced is −
Level Code Message Note 1265 Data truncated for column ”NAME” at row 1 Varchar Datatypes Using a Client Program
In addition to performing datatypes using mysql query, we can also create column of the Varchar datatypes using the client program.
Syntax
To create a column of Varchar datatypes through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −
$sql ="CREATE TABLE customers (cust_Name VARCHAR(30), cust_Address varchar(50)) "; $mysqli->query($sql);
To create a column of Varchar datatypes through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −
sql = "CREATE TABLE customers (cust_Name VARCHAR(30), cust_Address varchar(50))"; con.query(sql);
To create a column of Varchar datatypes through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −
String sql = "CREATE TABLE customers (cust_Name VARCHAR(30), cust_Address varchar(50))"; statement.execute(sql);
To create a column of Varchar datatypes through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −
sql = ''CREATE TABLE test_table (column1 VARCHAR(32765) NOT NULL, column2 VARCHAR(32766) NOT NULL)CHARACTER SET ''latin1'' COLLATE LATIN1_DANISH_CI'' cursorObj.execute(sql)
Example
Following are the programs −
$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 a customer table and use varchar data type with differenet size $sql = "CREATE TABLE customers (cust_Name VARCHAR(30), cust_Address varchar(50)) "; if ($mysqli->query($sql)) { echo "Table created successfully with varchar data!n"; } if ($mysqli->errno) { printf("table could not create table: %s
", $mysqli->error); } $mysqli->close();Output
The output obtained is as follows −
Table created successfully with varchar data!
var mysql = require("mysql2"); var con = mysql.createConnection({ host: "localhost", user: "root", password: "password", }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; // console.log("Connected successfully...!"); // console.log("--------------------------"); sql = "USE TUTORIALS"; con.query(sql); //create a customer table and use varchar data type with differenet size sql = "CREATE TABLE customers (cust_Name VARCHAR(30), cust_Address varchar(50)) "; con.query(sql); sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''customers'' AND COLUMN_NAME = ''cust_Name''`; con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
[ { DATA_TYPE: ''varchar'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Varchar { 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...!"); //varchar data types...!; String sql = "CREATE TABLE customers (cust_Name VARCHAR(30), cust_Address varchar(50))"; statement.execute(sql); System.out.println("column of a varchar type created successfully...!"); ResultSet resultSet = statement.executeQuery("DESCRIBE customers"); while (resultSet.next()){ System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! column of a varchar type created successfully...! cust_Name varchar(30) cust_Address varchar(50)
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) # Creating a cursor object cursorObj = connection.cursor() # Create table with varchar column sql = '''''' CREATE TABLE test_table ( column1 VARCHAR(32765) NOT NULL, column2 VARCHAR(32766) NOT NULL ) CHARACTER SET ''latin1'' COLLATE LATIN1_DANISH_CI '''''' cursorObj.execute(sql) print("The table is created successfully!") # Insert data into the created table insert_query = "INSERT INTO test_table (column1, column2) VALUES (%s, %s)" data_to_insert = ("History", "Geography") cursorObj.execute(insert_query, data_to_insert) # Commit the changes after the insert operation connection.commit() print("Rows inserted successfully.") # Now display the table records select_query = "SELECT * FROM test_table" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Table Data:") for row in result: print(row) cursorObj.close() connection.close()
Output
Following is the output of the above code −
The table is created successfully! Rows inserted successfully. Table Data: (''History'', ''Geography'')
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 – ENUM nhận dự án làm có lương
MySQL – ENUM
ENUM (Enumerator) is a user defined datatype which stores a list of values as strings. These values are specified when you define the ENUM column. The user can choose values from this predefined list while inserting values into this column.
Each string value defined in an ENUM column is implicitly assigned a numerical value starting from 1. These numerical values are used internally by MySQL to represent the ENUM values.
The MySQL ENUM Data Type
The MySQL ENUM data type allow you to select one or more values from a predefined list during insertion or update operations. The selected values are stored as strings in the table, and when you retrieve data from the ENUM column, the values are presented in a human-readable format.
ENUM columns can accept values of various data types, including integers, floating-point numbers, decimals, and strings. However, internally, MySQL will convert these values to the closest matching ENUM value based on its predefined list.
Syntax
Following is the syntax to define the ENUM data type on a column −
CREATE TABLE table_name ( Column1, Column2 ENUM (''value1'',''value2'',''value3'', ...), Column3... );
Note: An enum column can have maximum 65,535 values.
Attributes of ENUM
The ENUM datatype in MySQL has three attributes. The same is described below −
-
Default − The default value of enum data type is NULL. If no value is provided for the enum field at the time of insertion, Null value will be inserted.
-
NULL − It works the same as the DEFAULT value if this attribute is set for the enum field. If it is set, the index value is always NULL.
-
NOT NULL − MySQL will generate a warning message if this attribute is set for the enum field and no value is provided at the insertion time.
Example
First of all, let us create a table named STUDENTS. In this table, we are specifying ENUM string object in the BRANCH column using the following query −
CREATE TABLE STUDENTS ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM (''CSE'', ''ECE'', ''MECH''), FEES int NOT NULL, PRIMARY KEY (ID) );
Following is the output obtained −
Query OK, 0 rows affected (0.04 sec)
Now, we retrieve the structure of the STUDENTS table, revealing that the “BRANCH” field has an enum data type −
DESCRIBE STUDENTS;
The output indicates that the BRANCH field”s data type is ENUM, which stores the values (”CSE”, ”ECE”, ”MECH”) −
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int | NO | PRI | NULL | auto_increment |
NAME | varchar(30) | NO | NULL | ||
BRANCH | enum(”CSE”,”ECE”,”MECH”) | YES | NULL | ||
FEES | int | NO | NULL |
Now, let us insert records into the STUDENTS table using the following INSERT query −
INSERT INTO STUDENTS (NAME, BRANCH, FEES) VALUES (''Anirudh'', ''CSE'', 500000), (''Yuvan'', ''ECE'', 350000), (''Harris'', ''MECH'', 400000);
In these insertion queries, we have used values (”CSE”, ”ECE”, and ”MECH”) for the “BRANCH” field, which are valid enum values. Hence, the queries executed without any errors −
Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0
Using the below query, we can display all the values in the table −
SELECT * FROM STUDENTS;
Following are the records of STUDENTS table −
ID | NAME | BRANCH | FEES |
---|---|---|---|
1 | Anirudh | CSE | 500000 |
2 | Yuvan | ECE | 350000 |
3 | Harris | MECH | 400000 |
Inserting Records with Numerical ENUM Values
We can insert the enum list values to the ENUM column of table using the respective numeric index. The numeric index starts from 1 but not from 0.
Example
In the query below, we are inserting the value ”CSE” from the ENUM list into the ”BRANCH” column using its numeric index. Since ”CSE” is located at position 1 in the ENUM list, we use 1 as the numeric index in the query.
INSERT INTO STUDENTS (NAME, BRANCH, FEES) VALUES (''Devi'', 1, 380000);
Output
The insertion query executes without any errors −
Query OK, 1 row affected (0.01 sec)
Verification
Let us verify whether the above insertion is successful or not by retrieving all the records of the table using the below query −
SELECT * FROM STUDENTS;
The STUDENTS table displayed is as follows −
ID | NAME | BRANCH | FEES |
---|---|---|---|
1 | Anirudh | CSE | 500000 |
2 | Yuvan | ECE | 350000 |
3 | Harris | MECH | 400000 |
4 | Devi | CSE | 380000 |
Inserting Invalid Records
In MySQL, if we try to insert a value into a column with an ENUM data type that does not match any of the specified enum values, it will result in an error.
Example
In the following query, we are referring to the 6th value in enum list, which does not exist. So, the following query will generate an error −
INSERT INTO STUDENTS (NAME, BRANCH, FEES) VALUES (''Thaman'', 6, 200000);
Output
As we can see the output, an error is generated, and no new record has been inserted −
ERROR 1265 (01000): Data truncated for column ''BRANCH'' at row 1
Filtering Records by Numeric ENUM Value
In MySQL, you can retrieve records from an ENUM column based on either the string value or the numeric index. The numeric index starts from 1, not 0.
Example
The numeric index of 1 in enum list is ”CSE”. So, the following query will fetch the records where the BRANCH column contains the value as ”CSE”.
SELECT * FROM STUDENTS WHERE BRANCH = 1;
Output
The resulting output displays records where the ”BRANCH” column contains the value ”CSE” −
ID | NAME | BRANCH | FEES |
---|---|---|---|
1 | Anirudh | CSE | 500000 |
4 | Devi | CSE | 380000 |
Filtering Records by Human-Readable ENUM Value
There can be some instances where the enum list will have large number of values. It can be difficult to remember the numeric index for every value in the list. In such cases, it is more convenient to use the human-readable string value of the ENUM item in your query to retrieve records based on the ENUM field”s value.
Example
In the following query, we are filtering the records where the BRANCH column contains the value “Mech”.
SELECT * FROM STUDENTS WHERE BRANCH = "MECH";
Output
Following is the output obtained −
ID | NAME | BRANCH | FEES |
---|---|---|---|
3 | Harris | MECH | 400000 |
Disadvantages of ENUM Data Type
Following are the disadvantages of ENUM data type in MySQL −
-
If we wish to modify the values in enum list, we need to re-create the complete table using the ALTER TABLE command, which is quite expensive in terms of used resources and time.
-
It is very complex to get the complete enum list because we need to access the inform_schema database.
-
Expressions cannot be used with enumeration values. For instance, the following CREATE statement will return an error because it used the CONCAT() function for creating enumeration value −
CREATE TABLE Students ( ID int PRIMARY KEY AUTO_INCREMENT, NAME varchar(30), BRANCH ENUM(''CSE'', CONCAT(''ME'',''CH'')) );
User variables cannot be used for an enumeration value. For instance, look at the following query −
mysql> SET @mybranch = ''EEE mysql> CREATE TABLE Students ( ID int PRIMARY KEY AUTO_INCREMENT, NAME varchar(30), BRANCH ENUM(''CSE'', ''MECH'', @mybranch) );
It is recommended to not use the numeric values as enum values.
Enum Datatypes Using a Client Program
We can also create column of the Enum datatypes using the client program.
Syntax
To create a column of Enum datatypes through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −
$sql = ''CREATE TABLE STUDENTS (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM ("CSE", "ECE", "MECH"), FEES int NOT NULL, PRIMARY KEY (ID)) $mysqli->query($sql);
To create a column of Enum datatypes through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −
sql = "CREATE TABLE STUDENTS (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM (''CSE'', ''ECE'', ''MECH''), FEES int NOT NULL, PRIMARY KEY (ID) )"; con.query(sql);
To create a column of Enum datatypes through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −
String sql = "CREATE TABLE STUDENTS (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM ("CSE", "ECE", "MECH"), FEES int NOT NULL, PRIMARY KEY (ID))"; statement.execute(sql);
To create a column of Enum datatypes through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −
sql = ''CREATE TABLE STUDENTS( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM (''CSE'', ''ECE'', ''MECH''), FEES int NOT NULL, PRIMARY KEY (ID) )'' cursorObj.execute(sql)
Example
Following are the programs −
$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 table with boolean column $sql = ''CREATE TABLE STUDENTS (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM ("CSE", "ECE", "MECH"), FEES int NOT NULL, PRIMARY KEY (ID)) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } //insert data into created table $q = "INSERT INTO STUDENTS (NAME, BRANCH, FEES) VALUES (''Anirudh'', ''CSE'', 500000), (''Yuvan'', ''ECE'', 350000)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT BRANCH FROM STUDENTS"; if ($r = $mysqli->query($s)) { printf("Select query executed successfully...!n"); printf("following records belongs to Enum datatypes: n"); while ($row = $r->fetch_assoc()) { printf(" Branch Name: %s", $row["BRANCH"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();
Output
The output obtained is as follows −
Table created successfully...! Data inserted successfully...! Select query executed successfully...! following records belongs to Enum datatypes: Branch Name: CSE Branch Name: ECE
var mysql = require("mysql2"); var con = mysql.createConnection({ host: "localhost", user: "root", password: "password", }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; // console.log("Connected successfully...!"); // console.log("--------------------------"); sql = "USE TUTORIALS"; con.query(sql); //create a customers that accepts one column enum type. sql = "CREATE TABLE STUDENTS (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM (''CSE'', ''ECE'', ''MECH''), FEES int NOT NULL, PRIMARY KEY (ID) )"; con.query(sql); //insert data into created table sql ="INSERT INTO STUDENTS (NAME, BRANCH, FEES) VALUES (''Anirudh'', ''CSE'', 500000), (''Yuvan'', ''ECE'', 350000)"; con.query(sql); //select datatypes of branch sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''STUDENTS'' AND COLUMN_NAME = ''BRANCH''`; con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
[ { DATA_TYPE: ''enum'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Enum { 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...!"); //ENUM data types...!; String sql = "CREATE TABLE STUDENTS (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM ("CSE", "ECE", "MECH"), FEES int NOT NULL, PRIMARY KEY (ID))"; statement.execute(sql); System.out.println("column of a ENUM type created successfully...!"); ResultSet resultSet = statement.executeQuery("DESCRIBE STUDENTS"); while (resultSet.next()){ System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! column of a ENUM type created successfully...! ID int NAME varchar(30) BRANCH enum(''CSE'',''ECE'',''MECH'') FEES int
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) # Creating a cursor object cursorObj = connection.cursor() # Create table with enum column sql = '''''' CREATE TABLE STUDENTS ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM (''CSE'', ''ECE'', ''MECH''), FEES int NOT NULL, PRIMARY KEY (ID) ); '''''' cursorObj.execute(sql) print("The table is created successfully!") # Data to be inserted data_to_insert = [ (''Anirudh'', ''CSE'', 500000), (''Yuvan'', ''ECE'', 350000), (''Harris'', ''MECH'', 400000) ] # Insert data into the created table insert_query = "INSERT INTO STUDENTS (NAME, BRANCH, FEES) VALUES (%s, %s, %s)" cursorObj.executemany(insert_query, data_to_insert) # Commit the changes after the insert operation connection.commit() print("Rows inserted successfully.") # Now display the table records select_query = "SELECT * FROM STUDENTS" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Table Data:") for row in result: print(row) cursorObj.close() connection.close()
Output
Following is the output of the above code −
The table is created successfully! Rows inserted successfully. Table Data: (1, ''Anirudh'', ''CSE'', 500000) (2, ''Yuvan'', ''ECE'', 350000) (3, ''Harris'', ''MECH'', 400000)
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