Author: alien

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

    MySQL – NOT REGEXP Operator

    Table of content


    MySQL NOT REGEXP Operator

    Technically, a regular expression is defined as a sequence of characters that represent a pattern in an input text. It is used to locate or replace text strings using some patterns; this pattern can either be a single character, multiple characters or words, etc.

    In MySQL, the REGEXP operator is a powerful tool to perform complex search operations in a database to retrieve required data using regular expressions. And unlike the LIKE operator, the REGEXP operator is not restricted on search patterns (like % and _), as it uses several other meta characters to expand the flexibility and control during pattern matching.

    NOT REGEXP Operator is a negation to this REGEXP operator. It is used to retrieve all the records present in a database that do not satisfy the specified pattern. Let us learn about this operator in detail further in this chapter.

    Syntax

    Following is the basic syntax of the MySQL NOT REGEXP operator −

    expression NOT REGEXP pattern
    

    Note − Since this is just a negation, the functionality of a NOT REGEXP operator will be the same as a REGEXP operator.

    Examples

    Let us start by creating a table named CUSTOMERS using the following query −

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

    The below INSERT statement inserts 7 records into the above created table −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 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 );
    

    Execute the following query to display all the records present in CUSTOMERS table −

    Select * from CUSTOMERS;
    

    Following is the CUSTOMERS table −

    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

    Now, let us show the usage of NOT REGEXPM operator using several queries on this table.

    Query to find all the names not starting with ”ra”

    SELECT * FROM CUSTOMERS WHERE NAME NOT REGEXP ''^ra
    

    Following is the output −

    ID NAME AGE ADDRESS SALARY
    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

    Query to retrieve all the records whose names not ending with ”ik”

    SELECT * FROM CUSTOMERS WHERE NAME NOT REGEXP ''ik$
    

    Following is the output −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    4 Chaitali 25 Mumbai 6500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Following is the query to find all the names that do not contain ”an”

    SELECT * FROM CUSTOMERS WHERE NAME NOT REGEXP ''an
    

    Following is the output −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.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

    Example

    The NOT RLIKE is alternative syntax to the NOT REGEXP in MySQL. Both the operators have same result. If either of the first two operands is NULL, this operator returns NULL.

    In the below query, the string value is NULL. Thus it gives output as NULL.

    SELECT NULL NOT RLIKE ''value
    

    Following is the output −

    NULL NOT RLIKE ”value”
    NULL

    Here, the specified pattern is NULL. So, the output will be retrieved as NULL.

    SELECT ''Tutorialspoint'' NOT REGEXP NULL;
    

    Following is the output −

    NULL NOT RLIKE ”value”
    NULL

    NOT REGEXP Operator Using a Client Program

    Besides using MySQL queries to perform the NOT REGEXP operator, we can also use client programs such as PHP, Node.js, Java, and Python to achieve the same result.

    Syntax

    Following are the syntaxes of this operation in various programming languages −

    To retrieve all the records present in a database that do not satisfy the specified pattern using MySQL Query through PHP program, we need to execute the “SELECT” statement using the mysqli function query() as follows −

    $sql = "SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''";
    $mysqli->query($sql);
    

    To retrieve all the records present in a database that do not satisfy the specified pattern using MySQL Query through Node.js program, we need to execute the “SELECT” statement using the query() function of the mysql2 library as follows −

    sql = "SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''";
    con.query(sql);
    

    To retrieve all the records present in a database that do not satisfy the specified pattern using MySQL Query through Java program, we need to execute the “SELECT” statement using the JDBC function executeUpdate() as −

    String sql = "SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''";
    statement.executeQuery(sql);
    

    To retrieve all the records present in a database that do not satisfy the specified pattern using MySQL Query through Python program, we need to execute the “SELECT” statement using the execute() function of the MySQL Connector/Python as −

    sql = "SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''"
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = "SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''"; if($result = $mysqli->query($sql)){ printf("Table records(where the name does not start with ''sa''): n"); while($row = mysqli_fetch_array($result)){ printf("ID %d, Name %s, Age %d, Address %s", $row[''ID''], $row[''NAME''], $row[''AGE''], $row[''ADDRESS''],); printf("n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table records(where the name does not start with ''sa''):
    ID 1, Name John, Age 33, Address New York
    ID 2, Name Ram, Age 29, Address Pune
    ID 4, Name Tanya, Age 26, Address Paris
    ID 5, Name Anmol, Age 28, Address Surat
    ID 6, Name Ramesh, Age 40, Address Mumbai
    
    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);
     sql = "SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''";
     console.log("Select query executed successfully..!");
     console.log("Table records: ");
     con.query(sql);
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    Select query executed successfully..!
    Table records:
    [
      { ID: 1, NAME: ''John'', AGE: 33, ADDRESS: ''New York'' },
      { ID: 2, NAME: ''Ram'', AGE: 29, ADDRESS: ''Pune'' },
      { ID: 4, NAME: ''Tanya'', AGE: 26, ADDRESS: ''Paris'' },
      { ID: 5, NAME: ''Anmol'', AGE: 28, ADDRESS: ''Surat'' },
      { ID: 6, NAME: ''Ramesh'', AGE: 40, ADDRESS: ''Mumbai'' }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class regexp_not {
        public static void main(String[] args) {
            String url = "jdbc:mysql://localhost:3306/TUTORIALS";
            String user = "root";
            String password = "password";
            ResultSet rs;
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''";
                rs = st.executeQuery(sql);
                System.out.println("Table records: ");
                while(rs.next()) {
                    String id = rs.getString("id");
                    String name = rs.getString("Name");
                    String age = rs.getString("AGE");
                    String address = rs.getString("ADDRESS");
                    System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address);
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Table records:
    Id: 1, Name: John, Age: 33, Address: New York
    Id: 2, Name: Ram, Age: 29, Address: Pune
    Id: 4, Name: Tanya, Age: 26, Address: Paris
    Id: 5, Name: Anmol, Age: 28, Address: Surat
    Id: 6, Name: Ramesh, Age: 40, Address: Mumbai
    
    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()
    notregexp_operator_query = f"SELECT * FROM person_tbl WHERE NAME NOT REGEXP ''^sa''"
    cursorObj.execute(notregexp_operator_query)
    # Fetching all the results
    results = cursorObj.fetchall()
    # display the results
    print("Persons whose name does not start with ''sa'' using NOT REGEXP:")
    for row in results:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Persons whose name does not start with ''sa'' using NOT REGEXP:
    (1, ''John'', 33, ''New York'')
    (2, ''Ram'', 29, ''Pune'')
    (4, ''Tanya'', 26, ''Paris'')
    (5, ''Anmol'', 28, ''Surat'')
    (6, ''Ramesh'', 40, ''Mumbai'')
    

    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 – NOT LIKE Operator nhận dự án làm có lương

    MySQL – NOT LIKE Operator

    Table of content


    MySQL NOT LIKE Operator

    We have previously learned that the LIKE Operator in MySQL database is a logical operator used to perform pattern matching operation on a database table. And NOT LIKE Operator is defined as opposite of this LIKE operator.

    Both LIKE and NOT LIKE operators perform pattern matching in a database table. Thus, they both need wildcards and patterns to function. However, if the LIKE operator is used to find the similar patterns mentioned using the wildcards, NOT LIKE operator is used to find all the records that do not contain the specified pattern.

    • The NOT LIKE operator is nothing but the amalgamation of two SQL operators, NOT and LIKE operators. Thus, having the combination of their functionalities.

    • It is used to match a particular pattern in the given string and returns 0 in case of a match and returns 1 otherwise. If either of the two operands of this function is NULL, it returns NULL as result.

    • This operator is useful for finding strings that do not match a specific pattern or do not have certain characteristics.

    Syntax

    Following is the basic syntax of MySQL NOT LIKE operator with a SELECT statement −

    SELECT column_name(s) FROM table_name
    WHERE column_name NOT LIKE [condition];
    

    Using NOT LIKE Operator with Wildcards

    Wildcards are special characters used in SQL queries to match patterns in the data. Following wildcards can be used in conjunction with the NOT LIKE operator −

    S.No WildCard & Definition

    1

    %

    The percent sign represents zero, one or multiple characters.

    2

    _

    The underscore represents a single number or character.

    3

    []

    This matches any single character within the given range in the [].

    4

    [^]

    This matches any single character excluding the given range in the [^].

    Note: In the NOT LIKE operator, the above wildcard characters can be used individually as well as in combinations with each other. The two mainly used wildcard characters are ”%” and ”_”.

    Example

    Let us begin by creating a table named CUSTOMERS using the following query −

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

    Using the below INSERT statements, we are inserting records into the above created table −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 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 );
    

    Execute the below query to display all the records present in the CUSTOMERS table −

    Select * from CUSTOMERS;
    

    Following is the CUSTOMERS table −

    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

    Now, let us use the MySQL NOTLIKE operator to displays the all the records in CUSTOMERS table whose name doesn”t starts with ”k”.

    SELECT * FROM CUSTOMERS where NAME NOT LIKE ''k%
    

    Following are the records whose name doesn”t starts with ”k” −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    7 Muffy 24 Indore 10000.00

    The following query displays the records of customers whose NAME doesn”t end with ”ik”.

    SELECT * FROM CUSTOMERS where NAME NOT LIKE ''%ik
    

    Following are the records whose name doesn”t ends with ”ik” −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    4 Chaitali 25 Mumbai 6500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Here, we are displaying all the records whose name does not contains the substring ”al”.

    SELECT * FROM CUSTOMERS where NAME NOT LIKE ''%al%
    

    Following are the records whose name doesn”t contains the substring ”al” −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    5 Hardik 27 Bhopal 8500.00
    7 Muffy 24 Indore 10000.00

    The following query displays all the records whose name does not starts with ”m” and ends with ”y”.

    SELECT * FROM CUSTOMERS WHERE NAME NOT LIKE ''m___y
    

    As we can see in the output table, the seventh record is eliminated because the name starts with ”m” and ends with ”y”.

    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

    The below query displays all customer names that does not start with ”k” and have exactly 6 characters.

    SELECT * FROM CUSTOMERS WHERE name NOT LIKE ''k_____
    

    Following is the output −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.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 the records of CUSTOMERS table, where the second character of the records in ADDRESS column is not “h”.

    SELECT * FROM CUSTOMERS where ADDRESS NOT LIKE ''_h%
    

    Following is the output −

    ID NAME AGE ADDRESS SALARY
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Using NOT LIKE Operator with AND/OR Operators

    We can use the MySQL NOT LIKE operator with different string patterns to choose rows, combining them with the AND or OR operators.

    Syntax

    Following is the syntax of using NOT LIKE operator with AND/OR operator −

    SELECT column_name(s)
    FROM table_name
    WHERE column1 NOT LIKE pattern1 [AND|OR] column2 NOT LIKE pattern2 [AND|OR] ...;
    

    Example

    In the following example, we are displaying all records from the CUSTOMERS table where name does not start with ”k” and the address should not start with ”m” using AND operator −

    SELECT * FROM CUSTOMERS
    WHERE name NOT LIKE ''k%'' AND address NOT LIKE ''m%
    

    Output

    Executing the query above will produce the following output −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    5 Hardik 27 Bhopal 8500.00
    7 Muffy 24 Indore 10000.00

    NOT LIKE Operator on Strings

    The MySQL NOT LIKE operator can perform pattern matching not only on database tables but also on individual strings. Here, the result will obtain as 0 if the pattern exists in the given string, or 1 if it doesn”t. The result is retrieved as a result-set using the SQL SELECT statement.

    Syntax

    Following is the syntax of NOT LIKE operator in MySQL −

    SELECT expression NOT LIKE pattern;
    

    Example

    In the following query, the pattern ”Tutorix” is not present in the specified string. So, this operator will return 1.

    SELECT ''Tutorialspoint'' NOT LIKE ''Tutorix
    

    Executing the query above will produce the following output −

    ”Tutorialspoint” NOT LIKE ”Tutorix”
    1

    Here, the pattern ”Tutorialspoint” is present in the specified string. Thus, it returns 0 as output.

    SELECT ''Tutorialspoint'' NOT LIKE ''Tutorialspoint
    

    Following is the output −

    ”Tutorialspoint” NOT LIKE ”Tutorialspoint”
    0

    Example

    If either (string or pattern operands) is NULL, this operator returns NULL. In the following query, the string is NULL, so that the output will be returned as NULL.

    SELECT NULL NOT LIKE ''value
    

    Executing the query above will produce the following output −

    NULL NOT LIKE ”value”
    NULL

    Here, the search pattern is NULL. So, the output will be returned as NULL.

    SELECT ''Tutorialspoint'' NOT LIKE NULL;
    

    Following is the output −

    ”Tutorialspoint” NOT LIKE NULL
    NULL

    NOT LIKE Operator Using a Client Program

    Besides using MySQL queries to perform the Not Like operator, we can also use client programs like Node.js, PHP, Java, and Python to achieve the same result.

    Syntax

    Following are the syntaxes of this operation in various programming languages −

    To find data in a MySQL database that doesn”t match a specific pattern using a PHP program, you can use the Not Like operator. To do this, we need to execute the ”SELECT” statement using the mysqli function query() as −

    $sql = "SELECT * FROM EMP where Name NOT LIKE ''Su%''";
    $mysqli->query($sql);
    

    To find data in a MySQL database that doesn”t match a specific pattern using a Node.js program, you can use the Not Like operator. To do this, we need to execute the ”SELECT” statement using the query() function of the mysql2 library as −

    sql = "SELECT * FROM tutorials_tbl where tutorial_author Not like ''Jo%''";
    con.query(sql);
    

    To find data in a MySQL database that doesn”t match a specific pattern using a Java program, you can use the Not Like operator. To do this, we need to execute the ”SELECT” statement using the JDBC function executeUpdate() as −

    String sql = "SELECT * FROM EMP where Name NOT LIKE ''Su%''";
    statement.executeQuery(sql);
    

    To find data in a MySQL database that doesn”t match a specific pattern using a Python program, you can use the Not Like operator. To do this, we need to execute the ”SELECT” statement using the execute() function of the MySQL Connector/Python as −

    sql = "SELECT * FROM EMP where Name NOT LIKE ''Su%''"
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = "SELECT * FROM EMP where Name NOT LIKE ''Su%''"; if($result = $mysqli->query($sql)){ printf("Table records: n"); while($row = mysqli_fetch_array($result)){ printf("ID %d, Name %s, DOB %s, Location %s", $row[''ID''], $row[''Name''], $row[''DOB''], $row[''Location''],); printf("n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table records:
    ID 101, Name Amit, DOB 1970-01-08, Location Hyderabad
    ID 0, Name Raja, DOB 1980-11-06, Location Goa
    ID 109, Name Javed, DOB 1980-11-06, Location pune
    ID 120, Name Vani, DOB 1980-11-06, Location Delhi
    ID 0, Name Devi, DOB 1980-11-06, Location Goa
    
    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);
     sql = "SELECT * FROM tutorials_tbl where tutorial_author Not like ''Jo%''";
     console.log("Select query executed successfully..!");
     console.log("Table records: ");
     con.query(sql);
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    Select query executed successfully..!
    Table records:
    [
      {
        tutorial_id: 2,
        tutorial_title: ''Angular Java'',
        tutorial_author: ''Abdul S'',
        submission_date: 2023-08-07T18:30:00.000Z
      },
      {
        tutorial_id: 3,
        tutorial_title: ''Learning Java'',
        tutorial_author: ''Sanjay'',
        submission_date: 2007-05-05T18:30:00.000Z
      },
      {
        tutorial_id: 4,
        tutorial_title: ''Python Tutorial'',
        tutorial_author: ''Sasha Lee'',
        submission_date: 2016-09-03T18:30:00.000Z
      },
      {
        tutorial_id: 5,
        tutorial_title: ''Hadoop Tutorial'',
        tutorial_author: ''Chris Welsh'',
        submission_date: 2023-08-07T18:30:00.000Z
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class NotLikeOperator {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String user = "root";
          String password = "password";
          ResultSet rs;
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "SELECT * FROM EMP where Name NOT LIKE ''Su%''";
                rs = st.executeQuery(sql);
                System.out.println("Table records: ");
                while(rs.next()) {
                   String id = rs.getString("id");
                   String name = rs.getString("Name");
                   String dob = rs.getString("dob");
                   String location = rs.getString("location");
                   System.out.println("Id: " + id + ", Name: " + name + ", Dob: " + dob + ", Location: " + location);
                }
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Table records:
    Id: 101, Name: Amit, Dob: 1970-01-08, Location: Hyderabad
    Id: MyID2, Name: Raja, Dob: 1980-11-06, Location: Goa
    Id: MyID2, Name: Raja, Dob: 1980-11-06, Location: Goa
    Id: 109, Name: Javed, Dob: 1980-11-06, Location: pune
    Id: 120, Name: Vani, Dob: 1980-11-06, Location: Delhi
    Id: oo1, Name: Devi, Dob: 1980-11-06, Location: Goa
    
    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()
    notlike_operator_query = f"SELECT * FROM EMP where Name NOT LIKE ''Su%''"
    cursorObj.execute(notlike_operator_query)
    # Fetching all the results
    results = cursorObj.fetchall()
    # display the results
    print("Employees whose name does not start with ''Su'':")
    for row in results:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Employees whose name does not start with ''Su'':
    (''101'', ''Amit'', datetime.date(1970, 1, 8), ''Hyderabad'')
    (''MyID2'', ''Raja'', datetime.date(1980, 11, 6), ''Goa'')
    (''109'', ''Javed'', datetime.date(1980, 11, 6), ''pune'')
    (''120'', ''Vani'', datetime.date(1980, 11, 6), ''Delhi'')
    (''oo1'', ''Devi'', datetime.date(1980, 11, 6), ''Goa'')
    

    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 – RLIKE Operator nhận dự án làm có lương

    MySQL – RLIKE Operator

    Table of content


    MySQL RLIKE Operator

    The RLIKE operator in MySQL is used to search data in a database using patterns (or regular expressions), also known as pattern matching. In other words, the RLIKE operator is used to determine whether a given regular expression matches a record in a table or not. It returns 1 if the record is matched and 0, otherwise.

    A regular expression is defined as a sequence of characters that represent a pattern in an input text. It is used to locate or replace text strings using some patterns; this pattern can either be a single/multiple characters or words, etc.

    The functionally of this operator is equivalent to the MySQL REGEXP operator and is commonly used to search for specific patterns that meets certain criteria.

    Syntax

    Following is the basic syntax of the RLIKE operator in MySQL −

    expression RLIKE pattern
    

    Patterns used with RLIKE

    RLIKE operator is used with several patterns or regular expressions. Following is the table of patterns that can be used along with the this operator.

    Pattern What the pattern matches
    ^ Beginning of string
    $ End of string
    * Zero or more instances of preceding element
    + One or more instances of preceding element
    {n} n instances of preceding element
    {m,n} m through n instances of preceding element
    . Any single character
    […] Any character listed between the square brackets
    [^…] Any character not listed between the square brackets
    [A-Z] Any uppercase letter
    [a-z] Any lowercase letter
    [0-9] Any digit (from 0 to 9)
    [[:<:]] Beginning of words
    [[:>:]] Ending of words
    [:class:] A character class, i.e. use [:alpha:] to match letters from the alphabet
    p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3

    Example

    The following example uses the RLIKE operator to retrieve records with the help of regular expressions. To do so, we are first creating a table named CUSTOMERS using the following query −

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

    Now, insert some values into the above created table using the INSERT statements given below −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 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 );
    

    Execute the following query to display all the records present in the CUSTOMERS table −

    SELECT * FROM CUSTOMERS;
    

    Following are the records present in CUSTOMERS table −

    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

    RLIKE with Patterns

    In the following query, we are finding all the records from CUSTOMERS table whose name starts with ”ch”

    SELECT * FROM CUSTOMERS WHERE NAME RLIKE ''^ch
    

    Executing the query above will produce the following output −

    ID NAME AGE ADDRESS SALARY
    4 Chaitali 25 Mumbai 6500.00

    The following query displays all the records whose names ends with ”sh”

    SELECT NAME FROM CUSTOMERS WHERE NAME RLIKE ''sh$
    

    Following are records whose name ends with ”sh” −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00

    Here, we are retrieving the records that have names containing ”an” −

    SELECT NAME FROM CUSTOMERS WHERE NAME RLIKE ''an
    

    Following are the records −

    ID NAME AGE ADDRESS SALARY
    2 Khilan 25 Delhi 1500.00

    This following query retrieves all the records whose names are ending with an vowel −

    SELECT NAME FROM CUSTOMERS WHERE NAME RLIKE ''[aeiou]$
    

    Following are the records −

    ID NAME AGE ADDRESS SALARY
    4 Chaitali 25 Mumbai 6500.00

    The below query finds all the names starting with a consonant and ending with ”ya”

    SELECT NAME FROM CUSTOMERS WHERE NAME RLIKE ''^[^aeiou].*ya$
    

    As we observe the output, there are no records that starts with consonant and ends with ”ya”.

    Empty set (0.00 sec)
    

    RLIKE On Strings

    The RLIKE operator can perform pattern matching not only on database tables but also on individual strings. Here, the result will obtain as 1 if the pattern exists in the given string, or 0 if it doesn”t. The result is retrieved as a result-set using the SQL SELECT statement.

    Syntax

    Following is the basic syntax of the RLIKE operator in MySQL −

    SELECT expression RLIKE pattern;
    

    Example

    In the following example, we are using the RLIKE query to check if a pattern exists in an individual string or not −

    SELECT ''Welcome To Tutorialspoint!'' RLIKE ''To
    

    The result-set will contain 1 because the pattern ”TO” exists in the specifed string.

    ”Welcome To Tutorialspoint!” RLIKE ”To”
    1

    Here, the pattern ”Hello” does not exist in the specifed string, thus it returns 0 as output.

    SELECT ''Welcome To Tutorialspoint!'' RLIKE ''Hello
    

    Executing the query above will produce the following output −

    ”Welcome To Tutorialspoint!” RLIKE ”Hello”
    0

    Example

    REGEXP is alternative syntax to the RLIKE in MySQL. Both the operators have same result.

    In the below query, if the given pattern is not found in the specifed string, this operator returns 0 −

    SELECT ''Welcome to Tutorialspoint'' REGEXP ''unknown
    

    Following is the output −

    ”Welcome to Tutorialspoint” REGEXP ”unknown”
    0

    Here, the pattern ”is” does not exist in the specifed string, thus it returns 1 as output.

    SELECT ''This is a sample string'' REGEXP ''is
    

    Executing the query above will produce the following output −

    ”This is a sample string” REGEXP ”is”
    1

    Example

    If either of the first two operands is NULL, the RLIKE operator returns NULL.

    SELECT NULL RLIKE ''value
    

    Following is the output −

    NULL RLIKE ”value”
    NULL

    Here, the pattern we are searching is NULL, thus the output will also be NULL.

    SELECT ''Tutorialspoint'' RLIKE NULL;
    

    Executing the query above will produce the following output −

    ”Tutorialspoint” RLIKE NULL
    NULL

    Example

    If you use the NOT clause before RLIKE operator, it returns 0 in case of a match else returns 1 (reverse of the original return values).

    SELECT NOT ''This is a sample string'' RLIKE ''is
    

    Following is the output −

    NOT ”This is a sample string” RLIKE ”is”
    0

    Here, the pattern ”unknown” is not present in the specifed string, thus the following query returns 1 as output.

    SELECT NOT ''Welcome to Tutorialspoint'' REGEXP ''unknown
    

    Executing the query above will produce the following output −

    NOT ”Welcome to Tutorialspoint” REGEXP ”unknown”
    1

    RLIKE Operator Using a Client Program

    We can also perform the MySQL RLike operator using the client programs to search data in a database using patterns (or regular expressions).

    Syntax

    Following are the syntaxes of this operation in various programming languages −

    To search data from a MySQL database using a pattern or regexp through PHP program, we need to execute the following “SELECT” statement using the mysqli function query() as −

    $sql = "SELECT * FROM person_tbl WHERE NAME RLIKE ''sh$''";
    $mysqli->query($sql);
    

    To search data from a MySQL database using a pattern or regexp through Node.js program, we need to execute the following “SELECT” statement using the query() function of the mysql2 library as −

    sql = "SELECT * FROM person_tbl WHERE NAME RLIKE ''sh$''";
    con.query(sql);
    

    To search data from a MySQL database using a pattern or regexp through Java program, we need to execute the following “SELECT” statement using the JDBC function executeUpdate() as −

    String sql = "SELECT NAME FROM person_tbl WHERE NAME RLIKE ''^sa''";
    statement.executeQuery(sql);
    

    To search data from a MySQL database using a pattern or regexp through Python program, we need to execute the following “SELECT” statement using the execute() function of the MySQL Connector/Python as −

    sql = ''SELECT NAME FROM person_tbl WHERE NAME RLIKE ''^sa''''
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = "SELECT * FROM person_tbl WHERE NAME RLIKE ''sh$''"; if($result = $mysqli->query($sql)){ printf("Table records: n"); while($row = mysqli_fetch_array($result)){ printf("Id %d, Name %s, Age %d, Address %s", $row[''ID''], $row[''NAME''], $row[''AGE''], $row[''ADDRESS'']); printf("n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table records:
    Id 3, Name Santosh, Age 34, Address Hyderabad
    Id 6, Name Ramesh, Age 40, Address Mumbai
    
    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);
     sql = "SELECT * FROM person_tbl WHERE NAME RLIKE ''sh$''";
     console.log("Select query executed successfully..!");
     console.log("Table records: ");
     con.query(sql);
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    Select query executed successfully..!
    Table records:
    [
      { ID: 3, NAME: ''Santosh'', AGE: 34, ADDRESS: ''Hyderabad'' },
      { ID: 6, NAME: ''Ramesh'', AGE: 40, ADDRESS: ''Mumbai'' }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class RlikeOperator {
        public static void main(String[] args) {
            String url = "jdbc:mysql://localhost:3306/TUTORIALS";
            String user = "root";
            String password = "password";
            ResultSet rs;
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "SELECT NAME FROM person_tbl WHERE NAME RLIKE ''^sa''";
                rs = st.executeQuery(sql);
                System.out.println("Table records: ");
                while(rs.next()) {
                    String name = rs.getString("Name");
                    System.out.println("Name: " + name);
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Table records:
    Name: Santosh
    
    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()
    rlike_operator_query = f"SELECT NAME FROM person_tbl WHERE NAME RLIKE ''^sa''"
    cursorObj.execute(rlike_operator_query)
    result = cursorObj.fetchall()
    print("Names that start with ''sa'':")
    for row in result:
        print(row[0])
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Names that start with ''sa'':
    Santosh
    

    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 – Regular Expressions nhận dự án làm có lương

    MySQL – Regular Expressions

    Table of content


    MySQL supports various types of pattern matching operations to retrieve filtered result-sets from huge database tables. In previous chapters, we have already learned about the LIKE operator for pattern matching. In this chapter, we will see another pattern matching operation based on regular expressions.

    MySQL Regular Expressions

    A regular expression is loosely defined as a sequence of characters that represent a pattern in an input text. It is used to locate or replace text strings using some patterns; this pattern can either be a single character, multiple characters or words, etc.

    MySQL implements regular expression support using International Components for Unicode (ICU), which provides full Unicode support and is multi-byte safe.

    In MySQL, it is a powerful way to perform a complex search operations in a database to retrieve desired content. And unlike the LIKE operator, the regular expressions are not restricted on search patterns (like % and _) as they use several other meta characters to expand the flexibility and control during pattern matching. This is performed using the REGEXP operator.

    Syntax

    Following is the basic syntax of the REGEXP operator in MySQL −

    expression REGEXP pattern
    

    Patterns used with REGEXP

    Following is the table of pattern, which can be used along with the REGEXP operator.

    Pattern What the pattern matches
    ^ Beginning of string
    $ End of string
    . Any single character
    […] Any character listed between the square brackets
    [^…] Any character not listed between the square brackets
    p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3
    * Zero or more instances of preceding element
    + One or more instances of preceding element
    {n} n instances of preceding element
    {m,n} m through n instances of preceding element
    [A-Z] Any uppercase letter
    [a-z] Any lowercase letter
    [0-9] Any digit (from 0 to 9)
    [[:<:]] Beginning of words
    [[:>:]] Ending of words
    [:class:] A character class, i.e. use [:alpha:] to match letters from the alphabet

    Examples

    The following example demonstrates the usage of some patterns mentioned in the table above, along with the REGEXP operator. For that, we are first creating a database table to perform the search on.

    Assume we are creating a table called CUSTOMERS using the following query −

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

    Now, insert some values into it using the INSERT statements given below −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 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 );
    

    Execute the following query to display all the records present in above created table −

    SELECT * FROM CUSTOMERS;
    

    Following are the records present in CUSTOMERS table −

    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

    REGEXP with Patterns −

    Now, we are finding all the records in the CUSTOMERS table whose name starts with ”k”

    SELECT * FROM CUSTOMERS WHERE NAME REGEXP ''^k
    

    Executing the query above will produce the following output −

    ID NAME AGE ADDRESS SALARY
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    6 Komal 22 Hyderabad 4500.00

    The following query retrieves all records in CUSTOMERS table whose name ends with ”sh”

    SELECT * FROM CUSTOMERS WHERE NAME REGEXP ''sh$
    

    Executing the query above will produce the following output −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00

    Here, we are retrieving all the records whose name contain ”sh”

    SELECT * FROM CUSTOMERS WHERE NAME REGEXP ''sh
    

    As we can see the output, there are only two names that contain ”sh”.

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

    In the following query, we are finding all the names starting with a vowel and ending with ”ol”

    SELECT * FROM CUSTOMERS WHERE NAME REGEXP ''^[aeiou].*ol$
    

    It returned an empty set because the CUSTOMERS table do not have any names who starts with vowel and ends with ”ol”

    Empty set (0.00 sec)
    

    The following query finds all the names in the CUSTOMERS table whose name starts with a consonant −

    SELECT * FROM CUSTOMERS WHERE NAME REGEXP ''^[^aeiou]
    

    Executing the query above will produce the following output −

    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

    Regular Expression Functions and Operators

    Following is the table of functions and operators of regular expressions.

    S. No Function or Operator
    1

    NOT REGEXP

    Negation of REGEXP

    2

    REGEXP

    Checks whether the string matches regular expression or not

    3

    REGEXP_INSTR()

    Returns the starting index of substring matching regular expression

    4

    REGEXP_LIKE()

    Returns whether the string matches the regular expression

    5

    REGEXP_REPLACE()

    Replaces substrings matching the regular expression

    6

    REGEXP_SUBSTR()

    Returns substrings matching the regular expression

    7

    RLIKE

    Checks whether the string matches regular expression or not


    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 – SET nhận dự án làm có lương

    MySQL – SET

    Table of content


    The MySQL SET data type

    The MySQL SET data type is used to store a set of values chosen from a predefined list of values. Each column of the SET datatype can have zero or more values chosen from its list of values. These values are specified as a comma-separated list when inserting or updating data.

    It is important to note that the list of values that can be stored in a SET column is defined at the time the table is created, and any values outside this list are not allowed.

    For example, if we define a SET column like this −

    test_col SET(''one'', ''two'') NOT NULL
    

    The possible values for this column are −

    • An empty string (””)
    • ”one”
    • ”two”
    • ”one,two”

    Storage of SET Data Type

    A MySQL SET column can hold a maximum of 64 distinct members, which means that duplicate values are not allowed. If duplicates exist, MySQL will generate an error or a warning when strict SQL mode is enabled. Additionally, MySQL automatically removes trailing spaces from SET values when creating a table.

    In MySQL, when you store a number in a SET column, the bits set in the binary representation of that number determine which set members are included in the column value. Consider the following query for a better understanding −

    Create table test_table (
       ID int auto_increment primary key ,
       COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'')
    );
    

    In the above query, each set member is assigned a single bit with corresponding decimal and binary values −

    Set Member Decimal Value Binary Value
    Goa 1 0001
    Assam 2 -0010
    Delhi 4 0100
    Kerala 8 1000

    So, if a value of 3 is assigned to the column (binary: 0011), it selects the first two SET members, resulting in ”Goa,Assam”.

    Example

    First of all, let us create a table with the name test_table using the following query −

    Create table test_table (
       ID int auto_increment primary key ,
       COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'')
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.02 sec)
    

    When inserting values into a SET column, there is no specific order required for listing the elements. Even if a particular element is listed multiple times, when retrieved later, each element will appear only once, following the order specified during table creation.

    Here, we are inserting the values into the set −

    INSERT INTO test_table (COL1) VALUES
    (''Goa,Assam''),
    (''Assam,Goa''),
    (''Goa,Assam,Goa''),
    (''Goa,Assam,Assam''),
    (''Assam,Goa,Assam'');
    

    Output

    The output produced is as shown below −

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

    Verification

    Let us display all the records of the ”test_table” using the SELECT statement as follows −

    SELECT * FROM test_table;
    

    As we can see the output below, all the values in ”COL1” will appear as ”Goa,Assam” −

    ID COL1
    1 Goa,Assam
    2 Goa,Assam
    3 Goa,Assam
    4 Goa,Assam
    5 Goa,Assam

    Example

    In the following query, we are searching for the SET values in the table using the MySQL LIKE operator. It finds rows where ”COL1” contains ”GOA” anywhere, even as a substring −

    SELECT * FROM test_table WHERE COL1 LIKE ''%Goa%
    

    Output

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

    ID COL1
    1 Goa,Assam
    2 Goa,Assam
    3 Goa,Assam
    4 Goa,Assam
    5 Goa,Assam

    Example

    In here, we are fetching the rows where the values are exactly ”Goa,Assam” and in the same order as listed in the ”COL1” definition −

    SELECT * FROM test_table WHERE COL1 = ''Goa,Assam
    

    Output

    The output for the above query is as given below −

    ID COL1
    1 Goa,Assam
    2 Goa,Assam
    3 Goa,Assam
    4 Goa,Assam
    5 Goa,Assam

    Updating the SET Values

    In MySQL, you can update SET elements in various ways: by replacing elements, adding elements, or removing elements from the SET data. Here are examples of each method −

    Replacing SET Data

    In the following query, we replace the value in the 5th row with the number 11, which corresponds to Goa + Assam + Kerala (8 + 2 + 1) −

    UPDATE test_table SET COL1 = 11 WHERE Id = 5;
    

    Output

    The query executes successfully and produces the following output −

    Query OK, 1 row affected (0.01 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    

    Verification

    To verify the changes done in the test_table, use the following SELECT query −

    SELECT * FROM test_table;
    

    Following is the output produced −

    ID COL1
    1 Goa,Assam
    2 Goa,Assam
    3 Goa,Assam
    4 Goa,Assam
    5 Goa,Assam,Kerala

    Adding Data to SET

    You can add elements to an existing SET column using the CONCAT() function. In this example, we add “Kerala” to the value in the 3rd row −

    UPDATE test_table SET COL1 = CONCAT(COL1, ",Kerala")
    WHERE Id = 3;
    

    Output

    The output for this query is as follows −

    Query OK, 1 row affected (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    

    Verification

    To verify the changes done in the test_table, use the following SELECT query −

    SELECT * FROM test_table;
    

    The result shows the updated value −

    ID COL1
    1 Goa,Assam
    2 Goa,Assam
    3 Goa,Assam,Kerala
    4 Goa,Assam
    5 Goa,Assam,Kerala

    Removing Data from SET

    To remove a specific SET element, you can use the & ~ bitwise operation. In this example, we remove the “Assam” element from the value in the 4th row −

    UPDATE test_table SET COL1 = COL1 & ~2 WHERE ID = 4;
    

    Output

    The output for this query is as follows −

    Query OK, 1 row affected (0.01 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    

    Verification

    Let us verify the test_table using the below query −

    SELECT * FROM test_table;
    

    Following is the table obtained −

    ID COL1
    1 Goa,Assam
    2 Goa,Assam
    3 Goa,Assam,Kerala
    4 Goa
    5 Goa,Assam,Kerala

    SET Datatype Using a Client Program

    We can also create column of the SET datatype using the client program.

    Syntax

    To create a column of SET datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −

    $sql = "CREATE TABLE test_table (ID INT auto_increment primary key, COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') )";
    $mysqli->query($sql);
    

    To create a column of SET datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE test_table (ID INT auto_increment primary key, COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') )";
    con.query(sql);
    

    To create a column of SET datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE test_table (ID INT auto_increment primary key, COL1 set("Goa", "Assam", "Delhi", "Kerala"))";
    statement.execute(sql);
    

    To create a column of SET datatype 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 (ID INT AUTO_INCREMENT PRIMARY KEY,  COL1 SET(''Goa'', ''Assam'', ''Delhi'', ''Kerala''))''
    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.
    ''); $sql = ''Create table test_table (ID INT auto_increment primary key, COL1 set("Goa", "Assam", "Delhi", "Kerala") ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q ="INSERT INTO test_table (COL1) VALUES (''Goa,Assam''), (''Assam,Goa''), (''Goa,Assam,Goa''), (''Goa,Assam,Assam''), (''Assam,Goa,Assam'')"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM test_table"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Col_1: %s", $row["ID"], $row["COL1"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Table Records:
     ID: 1, Col_1: Goa,Assam
     ID: 2, Col_1: Goa,Assam
     ID: 3, Col_1: Goa,Assam
     ID: 4, Col_1: Goa,Assam
     ID: 5, Col_1: Goa,Assam
    
    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 test_table table, that accepts one column of set type.
       sql = "Create table test_table (ID INT auto_increment primary key, COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') )";
       con.query(sql);
    
       //insert data into created table
       sql = "INSERT INTO test_table (COL1) VALUES (''Goa,Assam''), (''Assam,Goa''), (''Goa,Assam,Goa''), (''Goa,Assam,Assam''), (''Assam,Goa,Assam'')";
       con.query(sql);
    
       //select datatypes of salary
       sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''test_table'' AND COLUMN_NAME = ''col1''`;
       con.query(sql, function (err, result) {
         if (err) throw err;
         console.log(result);
       });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''set'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Set {
       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...!");
    
             //Set data types...!;
             String sql = "Create table test_table (ID INT auto_increment primary key, COL1 set("Goa", "Assam", "Delhi", "Kerala"))";
             statement.execute(sql);
             System.out.println("column of a SET type created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE test_table");
             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 SET type created successfully...!
    ID int
    COL1 set(''Goa'',''Assam'',''Delhi'',''Kerala'')
    
    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 Set column
    sql = ''''''
    CREATE TABLE test_table (
    ID INT AUTO_INCREMENT PRIMARY KEY,
    COL1 SET(''Goa'', ''Assam'', ''Delhi'', ''Kerala'')
    )
    ''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Data to be inserted
    data_to_insert = [
        (''Goa,Assam'',),
        (''Assam,Goa'',),
        (''Goa,Assam,Goa'',),
        (''Goa,Assam,Assam'',),
        (''Assam,Goa,Assam'',)
    ]
    # Insert data into the created table
    insert_query = "INSERT INTO test_table (COL1) VALUES (%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 test_table"
    cursorObj.execute(select_query)
    result = cursorObj.fetchall()
    print("Test 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.
    Test Table Data:
    (1, {''Assam'', ''Goa''})
    (2, {''Assam'', ''Goa''})
    (3, {''Assam'', ''Goa''})
    (4, {''Assam'', ''Goa''})
    (5, {''Assam'', ''Goa''})
    

    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 – BLOB nhận dự án làm có lương

    MySQL – BLOB

    Table of content


    Many user applications require the storage of different types of data, including text, images, files, and more. Using BLOBs in a MySQL database allows you to store all these types of data within the same database, eliminating the need for a separate file system.

    The MySQL BLOB Data Type

    The MySQL BLOB (Binary Large Object) data type is used to store binary data, such as images, audio, video, or any other type of binary file. BLOB columns can store variable-length binary data, making it suitable for handling files of various sizes.

    Consider an application that collects user information through forms. This information may include personal details, such as name and address, along with image proofs like PAN cards or AADHAR cards. Instead of managing these files separately in a file system, you can store them as BLOBs in a MySQL database.

    Syntax

    Following is the basic syntax to assign BLOB data type on a table field −

    CREATE TABLE table_name (column_name BLOB,...)
    

    Example

    Let us consider a basic example to show how to assign BLOB datatype to a table field. Here, we are creating a table named ”demo_table” with two fields “ID” and “DEMO_FILE” −

    CREATE TABLE demo_table (
       ID INT NOT NULL,
       DEMO_FILE BLOB
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.01 sec)
    

    You can see the table structure with the following command −

    DESC demo_table;
    

    The table obtained is as follows −

    Field Type Null Key Default Extra
    ID int NO NULL
    DEMO_FILE blob YES NULL

    Inserting Data into BLOB Fields

    You can insert some values into a database table, by loading a file to the BLOB field using the LOAD_FILE() function. However, before doing so, ensure that the following conditions are met −

    • File Existence −The file you want to insert must exist on the MySQL server host location. To determine the required location, you can use the secure_file_priv variable with the following command. If the result of this command is not empty, the file to be loaded must be located in that specific directory.

    SHOW VARIABLES LIKE secure_file_priv;
    
  • Specify Full File Path − When using the LOAD_FILE() function, you must pass the full path of the file as an argument, like ”/users/tutorialspoint/file_name.txt”. For Windows users, remember to use double backslashes as escape characters in the path (”//users//tutorialspoint//file_name.txt”).

  • Check ”max_allowed_packet” Value − MySQL Server has a max_allowed_packet variable that determines the maximum allowed file size for loading. To check the value of this variable, you can use the following command −

  • SHOW VARIABLES LIKE max_allowed_packet;
    

    Ensure that the file size does not exceed the value specified in this variable.

  • Grant FILE Privileges − Make sure the MySQL user account has FILE privileges granted. To grant file privileges to a user, you can use the following command (usually performed by a user with administrative privileges, such as ”root”) −

  • GRANT FILE ON *.* TO ''username''@''hostname
    FLUSH PRIVILEGES;
    
  • File Readability − Lastly, make sure that the file is readable by the MySQL server.

  • Example

    To insert values into a previously created table ”demo_table”, you can use the following INSERT query −

    INSERT INTO demo_table
    VALUES(1,
    LOAD_FILE("C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\sample.txt"));
    

    To verify the insertion, you can retrieve the data from the ”demo_table” using the following query −

    SELECT * FROM demo_table;
    

    We can see in the output below, the table contains the hex string of content present in the ”sample.txt” file. You can load any type of files into MySQL, like images, multimedia files, PDF documents etc. −

    ID DEMO_FILE
    1 0x5468697320697320612073616D706C652066696C65

    Types of BLOB Datatype

    MySQL provides four types of BLOB datatypes, each with varying maximum storage capacities. While they all serve the same purpose of storing binary data, such as images or files, they differ in the maximum size of objects they can accommodate. Here are the four BLOB datatypes −

    • TINYBLOB − It can store a maximum of 255 bytes, or 255 characters.

    • BLOB − It can store up to 65,535 (216 – 1) bytes, which is equivalent to 64KB of data.

    • MEDIUMBLOB − It can store up to 16,777,215 (224 – 1) bytes, or 4GB.

    • LONGBLOB − It is the largest among these datatypes and can store objects up to 4,294,967,295 bytes (232 – 1), or 4GB.

    Let us try to create tables with all types of BLOB datatypes mentioned above.

    Creating a Table with TINYBLOB Datatype

    In this example, we are creating a table named ”demo_tinyblob” with TINYBLOB datatype on a field −

    CREATE TABLE demo_tinyblob (ID INT, DEMO_FIELD TINYBLOB);
    

    Output

    Following is the output obtained −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    You can see the table structure with the following command −

    DESC demo_tinyblob;
    

    The table obtained is as follows −

    Field Type Null Key Default Extra
    ID int YES NULL
    DEMO_FIELD tinyblob YES NULL

    Creating a Table with MEDIUMBLOB Datatype

    Here, we are creating a table named ”demo_mediumblob” with a field of type MEDIUMBLOB using the following query −

    CREATE TABLE demo_mediumblob (ID INT, DEMO_FIELD MEDIUMBLOB);
    

    Output

    Output of the above code is as follows −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    You can see the table structure with the following command −

    DESC demo_mediumblob;
    

    Following is the table obtained −

    Field Type Null Key Default Extra
    ID int YES NULL
    DEMO_FIELD mediumblob YES NULL

    Creating a Table with LONGBLOB Datatype

    In this case, we are creating a table named ”demo_longblob” with a field of type LONGBLOB −

    CREATE TABLE demo_longblob (ID INT, DEMO_FIELD LONGBLOB);
    

    Output

    Following is the result produced −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    You can see the table structure with the command given below −

    DESC demo_longblob;
    

    The table produced is as shown below −

    Field Type Null Key Default Extra
    ID int YES NULL
    DEMO_FIELD longblob YES NULL

    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 – TINYINT nhận dự án làm có lương

    MySQL – TINYINT

    Table of content


    The MySQL TINYINT Data Type

    The MySQL TINYINT data type is used to store integer values within a very small range. It occupies just 1 byte (8 bits) of storage and can hold values from -128 to 127 for signed TINYINT or 0 to 255 for unsigned TINYINT.

    When you define a TINYINT column in MySQL, by default it is considered as SIGNED. This means it can hold both positive and negative numbers within a specific range. Additionally, you can use either “TINYINT” or “INT1” to define such a column because they work the same way.

    Syntax

    Following is the syntax of the MySQL TINYINT data type −

    TINYINT(M) [SIGNED | UNSIGNED | ZEROFILL]
    

    Example

    First, let us create a table with the name tinyint_table using the below query −

    CREATE TABLE tinyint_table (
       col1 TINYINT,
       col2 TINYINT UNSIGNED,
       col3 TINYINT ZEROFILL
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected, 1 warning (0.03 sec)
    

    Now, let us try to insert some values (128, 128, 128) into these columns as shown below −

    INSERT INTO tinyint_table VALUES (128, 128, 128);
    

    An error is generated for the value in col1 because the value we inserted is out of range −

    ERROR 1264 (22003): Out of range value for column ''col1'' at row 1
    

    Next, if we try to insert a negative value into the TINYINT UNSIGNED column (“col2”), it will result in an error because UNSIGNED values cannot be negative −

    INSERT INTO tinyint_table VALUES (127, -120, 128);
    

    The error message displayed is as follows −

    ERROR 1264 (22003): Out of range value for column ''col2'' at row 1
    

    Similarly, if we insert -128 into the TINYINT ZEROFILL column (“col3”), an error will be generated −

    INSERT INTO tinyint_table VALUES (127, 128, -128);
    

    The output is as shown below −

    ERROR 1264 (22003): Out of range value for column ''col3'' at row 1
    

    However, if we insert values within the valid range, the insertion will succeed as shown below −

    INSERT INTO tinyint_table VALUES (127, 128, 128);
    

    Following is the output of the above code −

    Query OK, 1 row affected (0.01 sec)
    

    Finally, we can retrieve all the records present in the table using the following SELECT query −

    SELECT * FROM tinyint_table;
    

    This query will display the following result −

    col1 col2 col3
    127 128 128

    TINYINT Datatype Using a Client Program

    We can also create column of the TINYINT datatype using the client program.

    Syntax

    To create a column of TINYINT datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −

    $sql = ''CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )
    $mysqli->query($sql);
    

    To create a column of TINYINT datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
    con.query(sql);
    

    To create a column of TINYINT datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
    statement.execute(sql);
    

    To create a column of TINYINT datatype 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 tinyint_table (col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL)''
    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.
    ''); $sql = ''CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q = " INSERT INTO tinyint_table (col1, col2, col3) VALUES (100, 105, 110)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM tinyint_table"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" Col_1: %s, Col_2: %s, Col_3: %s", $row["col1"], $row["col2"], $row["col3"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Table Records:
     Col_1: 100, Col_2: 105, Col_3: 110
    
    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 tinyint_table table, that accepts one column of tinyint type.
      sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
      con.query(sql);
    
      //insert data into created table
      sql =
        "INSERT INTO tinyint_table (col1, col2, col3) VALUES (100, 105, 110)";
      con.query(sql);
    
      //select datatypes of salary
      sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''tinyint_table'' AND COLUMN_NAME = ''col2''`;
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''tinyint'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class TinyInt {
       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...!");
    
             //TinyInt data types...!;
             String sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
             statement.execute(sql);
             System.out.println("column of a TINYINT type created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE tinyint_table");
             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 TINYINT type created successfully...!
    col1 tinyint
    col2 tinyint unsigned
    col3 tinyint(3) unsigned zerofill
    
    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 Tinyint column
    sql = ''''''
    CREATE TABLE tinyint_table (
    col1 TINYINT,
    col2 TINYINT UNSIGNED,
    col3 TINYINT ZEROFILL
    )''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Insert data into the created table
    insert_query = "INSERT INTO tinyint_table (col1, col2, col3) VALUES (127, 128, 128);"
    cursorObj.execute(insert_query)
    # Commit the changes after the insert operation
    connection.commit()
    print("Rows inserted successfully.")
    # Now display the table records
    select_query = "SELECT * FROM tinyint_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:
    (127, 128, 128)
    

    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 – INT nhận dự án làm có lương

    MySQL – INT

    Table of content


    The MySQL INT Data Type

    The MySQL INT data type is used to store whole numbers without the decimal places (integers).

    However, MySQL provides various integer data types, such as TINYINT, SMALLINT, MEDIUMINT, and BIGINT to cater to different ranges of whole numbers.

    The following table illustrates the characteristics of different integer types in MySQL, including storage in bytes, minimum value, and maximum value for both signed and unsigned options −

    Type Storage (Bytes) Minimum value (Signed/Unsigned) Maximum value (Signed/Unsigned)
    TINYINT 1 -128/ 0 127/ 255
    SMALLINT 2 -32768/ 0 32767/ 65535
    MEDIUMINT 3 -8388608/ 0 8388607/ 16777215
    INT 4 -8388607/ 16777215 2147483647/ 4294967295
    BIGINT 8 – 9223372036854775808 / 0 9223372036854775807 / 18446744073709551615

    We have to choose the data types based on the kind (type) of data being stored. If possible, we need to use smaller data types to minimize the database size. TINYINT can be used for small numbers, while INT or BIGINT is used for large numbers like phone numbers in a country.

    Auto Increment with MySQL INT

    In MySQL, you can use the AUTO_INCREMENT attribute with an INT column to automatically generate unique values for that column. Here”s how it works −

    • Initial Value − When you create a table with an AUTO_INCREMENT INT column, the sequence starts with 1.

    • Inserting NULL or 0 − When you insert a record with a NULL or 0 value for the AUTO_INCREMENT column, MySQL sets the value to the next sequence value. This means it assigns the next available integer starting from 1.

    • Inserting Non-NULL Values − If you insert a non-NULL value into the AUTO_INCREMENT column, MySQL accepts that value and continues the sequence based on the new value inserted.

    Example

    First of all, we are creating a table named STUDENTS with an AUTO_INCREMENT INT column named “ID” −

    CREATE TABLE STUDENTS (
       ID int auto_increment,
       NAME varchar(20),
       primary key (ID)
    );
    

    When we insert records into this table without specifying values for the “ID” column, MySQL automatically generates unique values for “ID” starting from 1.

    Here, we are inserting three rows into the STUDENTS table using the below INSERT query −

    INSERT INTO STUDENTS (NAME) VALUES
    (''Tilak''), (''Akash''), (''Surya''), (''Deepak'');
    

    The STUDENTS table created is as follows −

    ID NAME
    1 Tilak
    2 Akash
    3 Surya
    4 Deepak

    Now, let us insert a row where we provide an explicit value for the “ID” column −

    INSERT INTO STUDENTS (ID, NAME) VALUES (15, ''Arjun'');
    

    Following is the output obtained −

    Query OK, 1 row affected (0.01 sec)
    

    Since we specified the “ID” as 15, MySQL resets the sequence to 16. If we insert a new row without specifying the “ID,” MySQL will use 16 as the next AUTO_INCREMENT value −

    INSERT INTO STUDENTS (NAME) VALUES (''Dev'');
    

    The output obtained is as follows −

    Query OK, 1 row affected (0.01 sec)
    

    Now, let us retrieve the records from the “STUDENTS” table −

    SELECT * FROM STUDENTS;
    

    The table produced is −

    ID NAME
    1 Tilak
    2 Akash
    3 Surya
    4 Deepak
    15 Arjun
    16 Dev
    From MySQL 5.1 version and onwards, the AUTO_INCREMENT column accepts only positive values and does not allow negative values.

    MySQL INT UNSIGNED

    In MySQL, when you define an UNSIGNED INT on a column, that column is restricted to storing only non-negative values (i.e., positive values). Negative values are not allowed in such columns.

    Example

    Let us create a table with the name EMPLOYEES using the following query −

    CREATE TABLE EMPLOYEES (
       ID int auto_increment,
       NAME varchar(30) not null,
       AGE int UNSIGNED,
       Primary key(ID)
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.04 sec)
    

    Now, let us insert a row with a non-negative value into the “AGE” column −

    INSERT INTO EMPLOYEES (NAME, AGE) VALUES (''Varun'', 32);
    

    The above query will execute successfully since the value provided for the “AGE” column is non-negative.

    Query OK, 1 row affected (0.01 sec)
    

    However, if we attempt to insert a negative value into the “AGE” column, MySQL will generate an error −

    INSERT INTO EMPLOYEES (NAME, AGE) VALUES (''Sunil'', -10);
    

    MySQL will issue an error as shown below −

    ERROR 1264 (22003): Out of range value for column ''AGE'' at row 1
    

    MySQL INT with Display Width Attribute

    In MySQL, you can specify a display width for the INT data type by using parentheses after the INT keyword. For instance, using INT(5) sets the display width to five digits.

    It”s important to note that the display width attribute for INT in MySQL doesn”t affect the range of values that can be stored in the column. It formats integer values in applications, and is included as metadata in the result set.

    For example, if you insert the value 12345 into the id column of the EMPLOYEES table, it will be stored as is. When you retrieve it, some applications may choose to pad it with leading zeros to ensure it is displayed as five digits (e.g., 012345).

    MySQL INT with ZEROFILL Attribute

    In MySQL, the ZEROFILL attribute is a non-standard attribute that can be applied to numeric data types. It adds leading zeros to the displayed values, making sure the number is displayed with a fixed width, especially useful for numerical codes.

    Example

    Let us create a table with the name ZEROFILL_TABLE with ZEROFILL applied to INT columns using the query below −

    CREATE TABLE ZEROFILL_TABLE (
       col1 int(4) ZEROFILL,
       col2 int(6) ZEROFILL,
       col3 int(8) ZEROFILL
    );
    

    The output obtained is as follows −

    Query OK, 0 rows affected, 6 warnings (0.02 sec)
    

    Now, we are inserting a new row into the above-created table −

    INSERT INTO ZEROFILL_TABLE (col1, col2, col3)
    VALUES (1, 7, 3);
    

    Following is the output of the above code −

    Query OK, 1 row affected (0.00 sec)
    

    Now, let us display the records from the ZEROFILL_TABLE table −

    SELECT * FROM ZEROFILL_TABLE;
    

    We can see in the output below, the values are displayed with the specified width, and leading zeros are added to maintain that width, as determined by the ZEROFILL attribute −

    col1 col2 col3
    0001 000007 00000003

    INT Datatype Using a Client Program

    We can also create column of the INT datatype using the client program.

    Syntax

    To create a column of INT datatype 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 AUTO_INCREMENT primary key not null, reg_No INT )
    $mysqli->query($sql);
    

    To create a column of INT datatype 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 AUTO_INCREMENT primary key not null, reg_No INT )";
    con.query(sql);
    

    To create a column of INT datatype 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 AUTO_INCREMENT primary key not null, reg_No INT)";
    statement.execute(sql);
    

    To create a column of INT datatype 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 auto_increment, NAME varchar(20), 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 AUTO_INCREMENT primary key not null, reg_No INT ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } //insert data into created table $q = "INSERT INTO students (reg_No) VALUES (101), (102)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT Id, reg_No FROM students"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Reg: %s", $row["Id"], $row["reg_No"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table Records:
    ID: 1, Reg: 101
    ID: 2, Reg: 102
    
    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 students table, that accepts one column of int type.
       sql = "CREATE TABLE students (Id INT AUTO_INCREMENT primary key not null, reg_No INT )";
       con.query(sql);
    
       //insert data into created table
       sql = "INSERT INTO students (reg_No) VALUES (101), (102)";
       con.query(sql);
    
       //select datatypes of salary
       sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''students'' AND COLUMN_NAME = ''reg_No''`;
       con.query(sql, function (err, result) {
          if (err) throw err;
          console.log(result);
       });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''int'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Int {
       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...!");
    
             //Int data types...!;
             String sql = "CREATE TABLE students(Id INT AUTO_INCREMENT primary key not null, reg_No INT)";
             statement.execute(sql);
             System.out.println("column of a INT 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 INT type created successfully...!
    Id int
    reg_No 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 int column
    sql = ''''''CREATE TABLE students (
    ID int auto_increment,
    NAME varchar(20),
    primary key (ID)
    )''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Data to be inserted
    data_to_insert = [
        (1, ''Tilak''),
        (2, ''Akash''),
        (3, ''Surya''),
        (4, ''Deepak''),
        (15, ''Arjun''),
        (16, ''Dev'')
    ]
    # Insert data into the created table
    insert_query = "INSERT INTO STUDENTS (ID, NAME) VALUES (%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, ''Tilak'')
    (2, ''Akash'')
    (3, ''Surya'')
    (4, ''Deepak'')
    (15, ''Arjun'')
    (16, ''Dev'')
    

    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 – BIT nhận dự án làm có lương

    MySQL – BIT

    Table of content


    A bit represents the basic unit of data in programming languages. It can store only two values, represented as 0 or 1.

    The MySQL BIT Data Type

    The MySQL BIT data type is used to store binary values within a specified range. The range is determined by the number of bits you allocate to the BIT column.

    If we try to insert an integer value instead of BIT values, MySQL automatically converts them into BIT values. We have to ensure that the integer value we are adding must be within the range for conversion to BIT values.

    For instance, if you have a BIT(3) column, it can store values from 000 to 111 in binary, which corresponds to 0 to 7 in integer format. If you try to insert the integer 8 into this BIT(3) column, you”ll get an error because 8 in binary is 1000, which is outside the valid range of the column.

    Syntax

    Following is the syntax of the MySQL BIT datatype −

    BIT(n)
    

    Here, the range of n value is from 1 to 64. If you don”t provide the “n” value, the default is 1, resulting in a single-bit BIT column. Hence, the following queries will give the same output −

    Column_name BIT(1);
    and
    Column_name BIT;
    

    Bit Value Literal

    • To specify bit value literals, you can use the b”val or 0bval notations, where val is a binary value containing only 0s and 1s. The leading ”b” is case-insensitive.

    b01
    B11
    
  • Note that the 0b notation is case-sensitive, so 0B”1000” is an invalid bit literal value.

  • 0B''1000''
    

    Example

    Let us create a table named STUDENTS and use the BIT data type for the AGE column as shown below −

    CREATE TABLE STUDENTS(
       ID int auto_increment,
       NAME varchar(40),
       AGE BIT(3),
       primary key (ID)
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.01 sec)
    

    Now, we are inserting the values “5” and “3” into the AGE column of the STUDENTS table −

    INSERT INTO STUDENTS (NAME, AGE) VALUES
    (''Varun'', 5),
    (''Akash'', 3);
    

    Output of the above query is as shown below −

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

    We can use the following query to display the inserted values in the AGE column of the STUDENTS table −

    SELECT * from STUDENTS;
    

    We can see in the output below that the values “5” and “3” are stored in binary format −

    ID NAME AGE
    1 Varun 0x05
    2 Akash 0x03

    Now, let us insert another value “10”. In binary format, “10” is represented as “1010”. However, we defined the AGE column to have a range of only three bits. Therefore, the following query will generate an error because the value 10 is greater than 7 −

    INSERT INTO STUDENTS (NAME, AGE) VALUES (''Priya'', 10);
    

    The output indicates that the data is too long for the AGE column.

    ERROR 1406 (22001): Data too long for column ''AGE'' at row 1
    

    To insert bit value literals into the “AGE” column, you can use the B”val notation. Here, we are inserting “110” which is equivalent to the integer value “6” as shown below −

    INSERT INTO STUDENTS (NAME, AGE) VALUES(''Priya'', B''110'');
    

    The result obtained is as follows −

    Query OK, 1 row affected (0.01 sec)
    

    Let us display all the records in the “STUDENTS” table using the following query −

    SELECT * from STUDENTS;
    

    We can see in the output below that the value “6” has been inserted in binary format as “0x06” −

    ID NAME AGE
    1 Varun 0x05
    2 Akash 0x03
    3 Priya 0x06

    Verification

    To verify and display the inserted values in the “AGE” column in binary/bit format, you can use the MySQL BIN() function −

    SELECT ID, NAME, BIN(AGE) FROM STUDENTS;
    

    The output shows the values in binary format −

    ID NAME BIN(AGE)
    1 Varun 101
    2 Akash 11
    3 NULL 110

    In the above output, we can see that the leading zeros are removed. If we want to display them, we can use the LPAD function as shown below −

    SELECT ID, NAME, LPAD(BIN(AGE), 5, "0") FROM STUDENTS;
    

    Following is the output obtained −

    ID NAME LPAD(BIN(AGE), 5, “0”)
    1 Varun 00101
    2 Akash 00011
    3 NULL 00110

    BIT Datatype Using a Client Program

    We can also create column of the BIT datatype using the client program.

    Syntax

    To create a column of BIT datatype 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 auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )
    $mysqli->query($sql);
    

    To create a column of BIT datatype 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 auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )";
    con.query(sql);
    

    To create a column of BIT datatype 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 auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID))";
    statement.execute(sql);
    

    To create a column of BIT datatype 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 auto_increment, NAME varchar(40), AGE BIT(3),  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.
    ''); //creating a table student where age is bit data types $sql = ''CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q = " INSERT INTO students (NAME, AGE) VALUES (''Varun'', 5), (''Akash'', 3)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM students"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Age: %d", $row["ID"], $row["AGE"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Table Records:
    ID: 1, Age: 5
    ID: 2, Age: 3
    
    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 students table, that accepts one column of bit type.
      sql = "CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )";
      con.query(sql);
    
      //insert data into created table
      sql = "INSERT INTO students (NAME, AGE) VALUES (''Varun'', 5), (''Akash'', 3)";
      con.query(sql);
    
      //select datatypes of salary
      sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''students'' AND COLUMN_NAME = ''AGE''`;
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''bit'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Bit {
       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...!");
    
             //Bit data types...!;
             String sql = "CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID))";
             statement.execute(sql);
             System.out.println("column of a BIT 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 BIT type created successfully...!
    ID int
    NAME varchar(40)
    AGE bit(3)
    
    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 BIT column
    sql = ''''''
    CREATE TABLE students(
    ID int auto_increment,
    NAME varchar(40),
    AGE BIT(3),
    primary key (ID)
    )
    ''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Data to be inserted
    data_to_insert = [
        (''Varun'', 5),
        (''Akash'', 3)
    ]
    # Insert data into the created table
    insert_query = "INSERT INTO students (NAME, AGE) VALUES (%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, ''Varun'', 5)
    (2, ''Akash'', 3)
    

    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 – FLOAT nhận dự án làm có lương

    MySQL – FLOAT

    Table of content


    The FLOAT data type is a part of the numeric data type. Numeric data types are used to store numbers, and they can be categorized into various subtypes based on their characteristics, such as storage size and precision.

    The MySQL FLOAT Data Type

    The MySQL FLOAT datatype is a floating-point number type that stores approximate numeric values. It stores approximate numeric values in 4 bytes and represents single-precision values.

    FLOAT is suitable for a wide range of numeric values but stores them in an approximate manner due to the IEEE 754 standard limitations.

    FLOAT data type can represent both signed and unsigned attributes of a data value in versions prior to MySQL 8.0.17, but the unsigned FLOAT is deprecated in MySQL 8.0.17 and later versions.

    Syntax

    Following is the basic syntax to set the datatype of a field as FLOAT −

    CREATE TABLE (column_name FLOAT, ...);
    

    Example

    In this example, let us create a new database table named ”datatype_demo” using CREATE TABLE statement with columns representing FLOAT values −

    CREATE TABLE datatype_demo(
       ID INT,
       NAME VARCHAR(50),
       HEIGHT FLOAT,
       WEIGHT FLOAT
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.03 sec)
    

    Verification

    Once the table is created, we can verify the data types of the ”HEIGHT” and ”WEIGHT” fields by retrieving the table”s definition as shown below −

    DESC datatype_demo;
    

    The result of the DESC command will show that the ”HEIGHT” and ”WEIGHT” fields have the FLOAT data type −

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(50) YES NULL
    HEIGHT float YES NULL
    WEIGHT float YES NULL

    To verify further, let us insert some values into the table using the following INSERT statement −

    INSERT INTO datatype_demo VALUES
    (1, ''John'', 171.3, 65.7),
    (2, ''Rob'', 45, 75),
    (3, ''Salman'', 12.74839, 54.262),
    (4, ''Arush'', NULL, NULL),
    (5, ''James'', ''h'', ''w'');
    

    Following is the output obtained −

    ERROR 1265 (01000): Data truncated for column ''HEIGHT'' at row 1
    

    As expected, the FLOAT fields accept single precision floating-point numbers without any issues. However, when attempting to insert non-numeric values into these fields, such as ”h” and ”w,” MySQL raises an error, indicating data truncation.

    Finally, to view the data that has been inserted into the table, we can use the SELECT statement as shown below −

    SELECT * FROM datatype_demo;
    

    The resultant table is as follows −

    ID NAME HEIGHT WEIGHT
    1 John 171.3 65.7
    2 Rob 45 75
    3 Salman 12.7484 54.262
    4 Arush NULL NULL

    Other Representations of MySQL FLOAT

    MySQL has a provision to specify the range of precision (not the exponent) for the FLOAT datatype in the form of bits. These bits are specified within the parenthesis following the keyword FLOAT, i.e. FLOAT(p).

    However, this precision value is only used to determine the storage size and only holds up to 7 decimal places, with the range from 0 to 23 bits. If the precision bit exceeds 23, the data type becomes DOUBLE.

    Example

    First, we will drop the existing ”datatype_demo” table −

    DROP TABLE datatype_demo;
    

    The output obtained is as follows −

    Query OK, 0 rows affected (0.01 sec)
    

    Then, we will create a new table ”datatype_demo” specifying a precision of 20 bits for the ”HEIGHT” column −

    CREATE TABLE datatype_demo(
       ID INT,
       NAME VARCHAR(50),
       HEIGHT FLOAT(20)
    );
    

    Following is the output of the above code −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    Even though we specified a precision of 20 bits, the ”HEIGHT” column will still store float values within the single-precision range, holding up to 7 decimal places. To verify the table”s definition, we can use the DESC command as shown below −

    DESC datatype_demo;
    

    The table produced is as follows −

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(50) YES NULL
    HEIGHT float YES NULL

    If the precision bit exceeds 23, the datatype becomes DOUBLE. Look at the query below −

    CREATE TABLE datatype_demo1(
       ID INT,
       NAME VARCHAR(50),
       HEIGHT FLOAT(30)
    );
    

    we get the following output −

    Query OK, 0 rows affected (0.02 sec)
    

    Again, we can verify the table”s definition using the DESC command −

    DESC datatype_demo1;
    

    Following is the table obtained −

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(50) YES NULL
    HEIGHT double YES NULL

    Float Datatype Using a Client Program

    We can also create column of the Float datatype using the client program.

    Syntax

    To create a column of Float datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −

    $sql = ''CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))
    $mysqli->query($sql);
    

    To create a column of Float datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
    con.query(sql);
    

    To create a column of Float datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
    statement.execute(sql);
    

    To create a column of Float datatype 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 datatype_demo(ID INT, NAME VARCHAR(50), HEIGHT FLOAT, WEIGHT FLOAT)''''
    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.
    ''); //creating a table temp where we are inserting the celsius and Fahrenheit values in float $sql = ''CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id)) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q = " INSERT INTO temp(Celsius, Fahrenheit) VALUES ( 36.2, 97.16), ( 35.8, 96.44), ( 37.32, 99.17), ( 35.89, 96.602);"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM temp"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Celsius: %f, Fahrenheit: %f", $row["Id"], $row["Celsius"], $row["Fahrenheit"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Table Records:
     ID: 1, Celsius: 36.200000, Fahrenheit: 97.160000
     ID: 2, Celsius: 35.800000, Fahrenheit: 96.440000
     ID: 3, Celsius: 37.320000, Fahrenheit: 99.170000
     ID: 4, Celsius: 35.890000, Fahrenheit: 96.602000
    
    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 student table, that accepts one column of float type.
      sql =
        "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
      con.query(sql);
    
      //insert data into created table
      sql =
        "INSERT INTO temp(Celsius, Fahrenheit) VALUES ( 36.2, 97.16), ( 35.8, 96.44), ( 37.32, 99.17), ( 35.89, 96.602)";
      con.query(sql);
      //select datatypes of salary
      sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''temp'' AND COLUMN_NAME = ''Celsius''`;
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''float'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Float {
       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...!");
    
             //Float data types...!;
             String sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
             statement.execute(sql);
             System.out.println("column of a Float type created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE temp");
             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 Float type created successfully...!
    Id int
    Celsius float
    Fahrenheit float
    
    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 float column
    sql = ''''''
    CREATE TABLE datatype_demo(ID INT,
    NAME VARCHAR(50),
    HEIGHT FLOAT,
    WEIGHT FLOAT
    )
    ''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Data to be inserted
    data_to_insert = [
        (1, ''John'', 171.3, 65.7),
        (2, ''Rob'', 45, 75),
        (3, ''Salman'', 12.74839, 54.262),
        (4, ''Arush'', None, None),
    ]
    # Insert data into the created table
    insert_query = "INSERT INTO datatype_demo (ID, NAME, HEIGHT, WEIGHT) VALUES (%s, %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 datatype_demo"
    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, ''John'', 171.3, 65.7)
    (2, ''Rob'', 45.0, 75.0)
    (3, ''Salman'', 12.7484, 54.262)
    (4, ''Arush'', None, None)
    

    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