Category: My SQL

  • MySQL FUNCTIONS and OPERATORS

    FUNCTIONS and OPERATORS

    In the following section, we have given a list of FUNCTIONS and OPERATORS in MySQL as anyone can view the FUNCTIONS at a glance and jump immediately to his/her requirement.

    MySQL Function & OperatorsDescription
    Introduction of MySQL functions and operatorsTypes of MySQL functions and operators.
    MySQL Comparison Functions and OperatorsSome Comparison Functions and Operators are –
    Between andCOALESCE()NULL Safe equal to operator (<=>)Equal operator(=)Greater than or equal operator(>=)Greater than operator(>)GREATEST()IN()INTERVAL()IS NOT NULLIS NOTIS NULLISIS NULL()LEAST()LESS THAN OR EQUAL OPERATOR(<=)LESS THAN OPERATOR(<)LIKENOT BETWEEN ANDNOT EQUAL OPERATOR(<>,!=)NOT IN()NOT LIKESTRCMP()
    MySQL Logical OperatorsMySQL logical AND operator compares two expressions and returns true if both of the expressions are true.
    Some Logical Operators are –
    And operatorNot operatorOr operatorXor operator
    MySQL Control Flow FunctionsSome Control Flow Functions are –
    Case operatorIF()IFNULL()NULLIF()
    MySQL String FunctionsSome String Functions in MySQL are –
    ASCIIBINBIT_LENGTHCHAR_LENGTHCHARCHARACTER_LENGTHCONCAT_WSCONCATELTEXPORT_SETFIELDFIND_IN_SETFORMATHEXINSERTINSTRLCASELEFTLENGTHLIKELOAD_FILELOCATELOWERLPADLTRIMMAKE_SETMIDNOT LIKENOT REGEXPOCTET_LENGTHORDPOSITIONQUOTEREGEXPREPEATREPLACEREVERSERIGHTRLIKENOT RLIKERPADRTRIMSOUNDEXSOUNDS_LIKESPACESTRCMPSUBSTRSUBSTRING_INDEXSUBSTRINGTRIMUCASEUNHEXUPPER
    MySQL Mathematical FunctionsSome Mathematical Functions in MySQL are –
    ABS()ACOS()ASIN()ATAN2()ATAN()CEIL()CEILING()CONV()COS()COT()CRC32()DEGREES()DIVDIVISIONEXP()FLOOR()LN()LOG()LOG2()LOG10()MOD()OCT()PI()POW()POWER()RADIANS()RAND()ROUND()SIGN()SIN()SQRT()TAN()TRUNCATE()FORMAT()
    MySQL Date and Time FunctionsMySQL Date and Time Functions are used in various type of date and time operation.
    MySQL Encryption and Compression FunctionsMySQL Encryption and Compression Functions are used to encrypt and decrypt a string.
    Some Encryption and Compression Functions in MySQL are –
    AES_DECRYPT()AES_ENCRYPT()COMPRESS()DECODE()DES_DECRYPT()DES_ENCRYPT()ENCODE()ENCRYPT()MD5()OLD_PASSWORD()PASSWORD()SHA1()UNCOMPRESS()UNCOMPRESSED_LENGTH()
    MySQL Bit FunctionsSome Bit Functions in MySQL are –
    BIT_COUNTBITWISE ANDINVERT BITSBITWISE ORBITWISE XORLeft shiftRight shift
    MySQL Information FunctionsSome Information Functions in MySQL are –
    BENCHMARK()CHARSET()COERCIBILITY()COLLATION()CONNECTION_ID()CURRENT_USER(), CURRENT_USERDATABASE()FOUND_ROWS()LAST_INSERT_ID()SCHEMA()SESSION_USER()SYSTEM_USER()USER()VERSION()
  • MySQL aggregate functions and grouping

    aggregate functions

    MySQL aggregate functions retrieve a single value after performing a calculation on a set of values.

    In general, aggregate functions ignore null values.

    Often, aggregate functions are accompanied by the GROUP BY clause of the SELECT statement.

    List of MySQL aggregate functions and a hint of what they do

    AVG()

    MySQL AVG() retrieves the average value of the argument.

    BIT_AND()

    MySQL BIT_AND() bitwise and.

    BIT_OR()

    MySQL BIT_OR() retrieves bitwise or.

    BIT_XOR()

    MySQL BIT_OR() retrieves bitwise xor.

    COUNT(DISTINCT)

    MySQL COUNT(DISTINCT) retrieves the count of a number of different values.

    COUNT()

    MySQL COUNT() retrieves a count of the number of rows returned.

    GROUP_CONCAT()

    MySQL GROUP_CONCAT() retrieves a concatenated string.

    MAX()

    MySQL MAX() retrieves the maximum value.

    MIN()

    MySQL BIT_OR() retrieves the minimum value.

    STD()

    MySQL MIN()retrieves the population standard deviation.

    STDDEV_POP()

    MySQL BIT_OR() retrieves the population standard deviation.

    STDDEV_SAMP()

    MySQL STDDEV_POP() retrieves the sample standard deviation.

    STDDEV()

    MySQL STDDEV() retrieves the population standard deviation.

    SUM()

    MySQL SUM() retrieves the sum.

    VAR_POP()

    MySQL VAR_POP() the population standard variance.

    VAR_SAMP()

    MySQL VAR_POP() the sample variance.

    VARIANCE()

    MySQL VAR_POP()the population standard variance.

  • MySQL UNION

    UNION

    In MySQL, the UNION operator is used to combine the result from multiple SELECT statements into a single result set.

    The default characteristic of UNION is, to remove the duplicate rows from the result. The DISTINCT keyword which is optional does not make any effect, because, by default, it specifies duplicate-row removal. But if we use the optional keyword ALL, the duplicate-row removal does not happen and the result set includes all matching rows from all the SELECT statements.

    Syntax :SELECT … UNION [ALL | DISTINCT] SELECT … [UNION [ALL | DISTINCT] SELECT …]

    Pictorial presentation of UNION operator

    The UNION operator returns result from both queries after eliminating the duplicate rows.

    mysql union operator image

    Sample Tables

    employees:

    job_history:

    Example

    If we want to display the present and previous details of jobs of all employees once the following MySQL statement can be used.

    Select employee_id, job_id
    FROM employees
    UNION
    Select employee_id,job_id
    FROM job_history;
    

    Copy

    Sample Output:+————-+————+ | employee_id | job_id | +————-+————+ | 100 | AD_PRES | | 101 | AD_VP | | 102 | AD_VP | | 103 | IT_PROG | | 104 | IT_PROG | | 105 | IT_PROG | | 106 | IT_PROG | | 107 | IT_PROG | | 108 | FI_MGR | | 109 | FI_ACCOUNT | | 110 | FI_ACCOUNT | | 111 | FI_ACCOUNT | | 112 | FI_ACCOUNT | | 113 | FI_ACCOUNT | | 114 | PU_MAN | | 115 | PU_CLERK | | 116 | PU_CLERK | | 117 | PU_CLERK | | 118 | PU_CLERK | | 119 | PU_CLERK | | 120 | ST_MAN | | 121 | ST_MAN | | 122 | ST_MAN | | 123 | ST_MAN | | 124 | ST_MAN | | 125 | ST_CLERK | | 126 | ST_CLERK | | 127 | ST_CLERK | | 128 | ST_CLERK | | 129 | ST_CLERK | | 130 | ST_CLERK | | 131 | ST_CLERK | | 132 | ST_CLERK | | 133 | ST_CLERK | | 134 | ST_CLERK | | 135 | ST_CLERK | | 136 | ST_CLERK | | 137 | ST_CLERK | | 138 | ST_CLERK | | 139 | ST_CLERK | | 140 | ST_CLERK | | 141 | ST_CLERK | | 142 | ST_CLERK | | 143 | ST_CLERK | | 144 | ST_CLERK | | 145 | SA_MAN | | 146 | SA_MAN | | 147 | SA_MAN | | 148 | SA_MAN | | 149 | SA_MAN | | 150 | SA_REP | | 151 | SA_REP | | 152 | SA_REP | | 153 | SA_REP | | 154 | SA_REP | | 155 | SA_REP | | 156 | SA_REP | | 157 | SA_REP | | 158 | SA_REP | | 159 | SA_REP | | 160 | SA_REP | | 161 | SA_REP | | 162 | SA_REP | | 163 | SA_REP | | 164 | SA_REP | | 165 | SA_REP | | 166 | SA_REP | | 167 | SA_REP | | 168 | SA_REP | | 169 | SA_REP | | 170 | SA_REP | | 171 | SA_REP | | 172 | SA_REP | | 173 | SA_REP | | 174 | SA_REP | | 175 | SA_REP | | 176 | SA_REP | | 177 | SA_REP | | 178 | SA_REP | | 179 | SA_REP | | 180 | SH_CLERK | | 181 | SH_CLERK | | 182 | SH_CLERK | | 183 | SH_CLERK | | 184 | SH_CLERK | | 185 | SH_CLERK | | 186 | SH_CLERK | | 187 | SH_CLERK | | 188 | SH_CLERK | | 189 | SH_CLERK | | 190 | SH_CLERK | | 191 | SH_CLERK | | 192 | SH_CLERK | | 193 | SH_CLERK | | 194 | SH_CLERK | | 195 | SH_CLERK | | 196 | SH_CLERK | | 197 | SH_CLERK | | 198 | SH_CLERK | | 199 | SH_CLERK | | 200 | AD_ASST | | 201 | MK_MAN | | 202 | MK_REP | | 203 | HR_REP | | 204 | PR_REP | | 205 | AC_MGR | | 206 | AC_ACCOUNT | | 102 | IT_PROG | | 101 | AC_ACCOUNT | | 101 | AC_MGR | | 201 | MK_REP | | 114 | ST_CLERK | | 122 | ST_CLERK | | 176 | SA_MAN | | 200 | AC_ACCOUNT | | 0 | | +————-+————+

    Pictorial presentation of output

    mysql union operator image

    Here in the above picture shows, only the employee_id and job_id surrounded the red rectangle are same in employees and job_history table, so it comes once in the output but the other employee_id and job_id are different in both the tables, so they come each.

    MySQL UNION ALL

    The UNION ALL operator does not eliminate duplicate selected rows and returns all rows.

    Pictorial presentation of UNION ALL operator

    The UNION ALL operator returns all the rows from both the queries and no duplication elimination happens.

    mysql union operator image

    MySQL UNION vs UNION ALL

    In MySQL the UNION operator returns the combined result from multiple SELECT statements into a single result set but exclude the duplicate rows where as the UNION ALL operator avoids the elimination of duplicate selected rows and returns all rows.

    See the example below.

    Example

    If we want to display the present and previous details of jobs of all employees, and they may appear more than once, the following MySQL statement can be used.

    Select employee_id, job_id,department_id
    FROM employees
    UNION ALL
    Select employee_id,job_id,department_id
    FROM job_history;
    

    Copy

    Sample Output:+————-+————+—————+ | employee_id | job_id | department_id | +————-+————+—————+ | 100 | AD_PRES | 90 | | 101 | AD_VP | 90 | | 102 | AD_VP | 90 | | 103 | IT_PROG | 60 | | 104 | IT_PROG | 60 | | 105 | IT_PROG | 60 | | 106 | IT_PROG | 60 | | 107 | IT_PROG | 60 | | 108 | FI_MGR | 100 | | 109 | FI_ACCOUNT | 100 | | 110 | FI_ACCOUNT | 100 | | 111 | FI_ACCOUNT | 100 | | 112 | FI_ACCOUNT | 100 | | 113 | FI_ACCOUNT | 100 | | 114 | PU_MAN | 30 | | 115 | PU_CLERK | 30 | | 116 | PU_CLERK | 30 | | 117 | PU_CLERK | 30 | | 118 | PU_CLERK | 30 | | 119 | PU_CLERK | 30 | | 120 | ST_MAN | 50 | | 121 | ST_MAN | 50 | | 122 | ST_MAN | 50 | | 123 | ST_MAN | 50 | | 124 | ST_MAN | 50 | | 125 | ST_CLERK | 50 | | 126 | ST_CLERK | 50 | | 127 | ST_CLERK | 50 | | 128 | ST_CLERK | 50 | | 129 | ST_CLERK | 50 | | 130 | ST_CLERK | 50 | | 131 | ST_CLERK | 50 | | 132 | ST_CLERK | 50 | | 133 | ST_CLERK | 50 | | 134 | ST_CLERK | 50 | | 135 | ST_CLERK | 50 | | 136 | ST_CLERK | 50 | | 137 | ST_CLERK | 50 | | 138 | ST_CLERK | 50 | | 139 | ST_CLERK | 50 | | 140 | ST_CLERK | 50 | | 141 | ST_CLERK | 50 | | 142 | ST_CLERK | 50 | | 143 | ST_CLERK | 50 | | 144 | ST_CLERK | 50 | | 145 | SA_MAN | 80 | | 146 | SA_MAN | 80 | | 147 | SA_MAN | 80 | | 148 | SA_MAN | 80 | | 149 | SA_MAN | 80 | | 150 | SA_REP | 80 | | 151 | SA_REP | 80 | | 152 | SA_REP | 80 | | 153 | SA_REP | 80 | | 154 | SA_REP | 80 | | 155 | SA_REP | 80 | | 156 | SA_REP | 80 | | 157 | SA_REP | 80 | | 158 | SA_REP | 80 | | 159 | SA_REP | 80 | | 160 | SA_REP | 80 | | 161 | SA_REP | 80 | | 162 | SA_REP | 80 | | 163 | SA_REP | 80 | | 164 | SA_REP | 80 | | 165 | SA_REP | 80 | | 166 | SA_REP | 80 | | 167 | SA_REP | 80 | | 168 | SA_REP | 80 | | 169 | SA_REP | 80 | | 170 | SA_REP | 80 | | 171 | SA_REP | 80 | | 172 | SA_REP | 80 | | 173 | SA_REP | 80 | | 174 | SA_REP | 80 | | 175 | SA_REP | 80 | | 176 | SA_REP | 80 | | 177 | SA_REP | 80 | | 178 | SA_REP | 0 | | 179 | SA_REP | 80 | | 180 | SH_CLERK | 50 | | 181 | SH_CLERK | 50 | | 182 | SH_CLERK | 50 | | 183 | SH_CLERK | 50 | | 184 | SH_CLERK | 50 | | 185 | SH_CLERK | 50 | | 186 | SH_CLERK | 50 | | 187 | SH_CLERK | 50 | | 188 | SH_CLERK | 50 | | 189 | SH_CLERK | 50 | | 190 | SH_CLERK | 50 | | 191 | SH_CLERK | 50 | | 192 | SH_CLERK | 50 | | 193 | SH_CLERK | 50 | | 194 | SH_CLERK | 50 | | 195 | SH_CLERK | 50 | | 196 | SH_CLERK | 50 | | 197 | SH_CLERK | 50 | | 198 | SH_CLERK | 50 | | 199 | SH_CLERK | 50 | | 200 | AD_ASST | 10 | | 201 | MK_MAN | 20 | | 202 | MK_REP | 20 | | 203 | HR_REP | 40 | | 204 | PR_REP | 70 | | 205 | AC_MGR | 110 | | 206 | AC_ACCOUNT | 110 | | 102 | IT_PROG | 60 | | 101 | AC_ACCOUNT | 110 | | 101 | AC_MGR | 110 | | 201 | MK_REP | 20 | | 114 | ST_CLERK | 50 | | 122 | ST_CLERK | 50 | | 200 | AD_ASST | 90 | | 176 | SA_REP | 80 | | 176 | SA_MAN | 80 | | 200 | AC_ACCOUNT | 90 | | 0 | | 0 | +————-+————+—————+ 118 rows in set (0.11 sec)

    Pictorial presentation of output

    mysql union operator image

    Here in the above picture shows, only the employee_id and job_id surrounded the red rectangle are same in employees and job_history table and they all have appeared in the result set. Here UNION ALL have to avoid the elimination of duplicate rows.

    MySQL UNION DISTINCTThe DISTINCT clause with UNION produced nothing extra as the simple UNION done. From the UNION operator, we know that all rows will be displayed from both the queries except the duplicate are once.

    Example

    If we want to display the present and previous details of jobs of all employees once the following MySQL statement can be used.

    SELECT DISTINCT employee_id, job_id
    FROM employees
    UNION
    SELECT DISTINCT employee_id,job_id
    FROM job_history;
    

    Copy

    Output :

    The result will be same as the UNION operator do.

    MySQL UNION ORDER BYThe ORDER BY clause with UNION arrange the rows in the result set in a specific order. The default order is ascending. The ORDER BY only used at the very end of the statement.

    Example

    If we want to display the present and previous details of jobs of all employees once the following MySQL statement can be used.

    SELECT  employee_id, job_id
    FROM employees
    UNION
    SELECT  employee_id,job_id
    FROM job_history
    ORDER BY employee_id;
    

    Copy

    The result will be same as the UNION operator do.

    Sample Output:+————-+————+ | employee_id | job_id | +————-+————+ | 0 | | | 100 | AD_PRES | | 101 | AC_ACCOUNT | | 101 | AC_MGR | | 101 | AD_VP | ….. | 107 | IT_PROG | | 108 | FI_MGR | | 113 | FI_ACCOUNT | | 114 | PU_MAN | | 114 | ST_CLERK | ….. | 128 | ST_CLERK | | 129 | ST_CLERK | | 134 | ST_CLERK | | 135 | ST_CLERK | ….. | 149 | SA_MAN | | 150 | SA_REP | | 158 | SA_REP | | 159 | SA_REP | ….. | 176 | SA_REP | | 176 | SA_MAN | | 177 | SA_REP | | 200 | AC_ACCOUNT | | 200 | AD_ASST | | 201 | MK_REP | | 201 | MK_MAN | ….. | 204 | PR_REP | | 205 | AC_MGR | | 206 | AC_ACCOUNT | +————-+————+ 116 rows in set (0.00 sec)

  • MySQL SELECT statement

    SELECT statement

    MySQL SELECT statement is used to retrieve rows from one or more tables. The statement can also include UNION statements and subqueries.

    Syntax:SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr [, select_expr …] [FROM table_references [WHERE where_condition] [GROUP BY {col_name | expr | position} [ASC | DESC], … [WITH ROLLUP]] [HAVING where_condition] [ORDER BY {col_name | expr | position} [ASC | DESC], …] [LIMIT {[offset,] row_count | row_count OFFSET offset}] [PROCEDURE procedure_name(argument_list)] [INTO OUTFILE ‘file_name’ export_options | INTO DUMPFILE ‘file_name’ | INTO var_name [, var_name]] [FOR UPDATE | LOCK IN SHARE MODE]]

    Arguments:

    NameDescriptions
    SELECTSELECT statement is used to fetch rows or records from one or more tables. 
    * , ALLIndicating all columns.
    columnColumns or list of columns.
    tableIndicates the name of the table from where the rows will be retrieved.
    DISTINCTDISTINCT clause is used to retrieve unique rows from a table.
    DISTINCTROWDISTINCTROW is a synonym for DISTINCT.
    HIGH_PRIORITYIf used with SELECT, the associated query obtains higher priority than an update statement. It runs even if the table on which the query is applied is locked by an update query. It can be used only with MyISAM, MEMORY, and MERGE storage engines. And can be used only if the associated query is very fast as well as done at once. If a SELECT statements are part of a UNION, you can not use HIGH_PRIORITY along with.
    STRAIGHT_JOINIf used with SELECT, associated tables are joined in the order they are arranged in the corresponding FROM clause. This can not be used to make a query fast and also can be used in the table_references list.
    SQL_SMALL_RESULTCan be used with GROUP BY or DISTINCT. It tells the optimizer (a component of DataBase system which determines to the most efficient way of executing a query) that the result set is small, so use fast temporary tables to store the resulting table instead of using sorting.
    SQL_BIG_RESULTCan be used with GROUP BY or DISTINCT. It tells the optimizer (a component of DataBase system which determines to the most efficient way of executing a query) that the result set has many rows, so use disk-based temporary tables if needed, and prefer sorting to use a temporary table with a key on the GROUP BY elements.
    SQL_BUFFER_RESULTIt forces the result to be put into a temporary table. If used, MySQL can free the table locks early and takes less time to send the result set to the client where it may take a long time. It can not be used for subqueries or following UNION.
    SQL_CACHEIt tells MySQL to store the result in the query cache (A DataBase system component which stores the text of a SELECT statement along with the corresponding result sent to the client ) if it is cacheable. The value of the query_cache_type system variable is 2 or DEMAND.
    SQL_NO_CACHEIt tells MySQL not to store the result in the query cache (A DataBase system component which stores the text of a SELECT statement along with the corresponding result sent to the client ). It can also be used for views if it accompanies a SELECT statement.
    SQL_CALC_FOUND_ROWSIt tells MySQL to calculate the number of rows in a result set. While calculating rows in this fashion, LIMIT clause is ignored. The number of rows can then be retrieved with SELECT FOUND_ROWS().
    select_exprAn expression.
    FROMThis clause is used after SELECT and preceding tables or subqueries.
    table_referencesName of the tables used in a SELECT statement.
    WHEREThe conditions are supplied after this keyword (in a select statement).
    where_conditionConditions placed after WHERE.
    GROUP BYIf used, the results returned from the field name used after GROUP BY clause is grouped together in result set.
    col_nameName of the column or columns or fields.
    exprAn expression.
    positionRefers to the position of columns beginning with 1.
    ASCIf used, results are returned in ascending order.
    DESCIf used, results are returned in descending order.
    WITH ROLLUPThis modifier can be used with GROUP BY clause. If used, extra rows are added to the summary output.
    HAVINGThis modifier can be used with GROUP BY clause and aggregate functions. Can not be used with WHERE clause.
    ORDER BYMySQL ORDER BY clause specifies the order in which columns are sorted while retrieving data in a SELECT statement.
    LIMITIt is always followed by one or two numeric arguments. The first argument is the offset of the first row to be returned and the second argument is the maximum number of rows returned in the result set.
    PROCEDUREThis clause names a procedure that should process the data in the result set.
    INTO OUTFILETakes a backup of the associated table in a file specified.
    INTO DUMPFILEIf used instead of INTO OUTFILE, only one row is written into the file. Useful if BLOB values are to be stored in a file.
    var_nameA variable name to store data temporarily.
    FOR UPDATEIf used with a storage engine that uses page or row locks, untill the end of the transaction, rows checked by the query are write-locked.
    LOCK IN SHARE MODEIf used, a shared lock is set upon the rows examined by the associated query. So, other transactions can read the examined rows, can not update or delete those rows.

    Following clauses are commonly used in SELECT statements:

    • Each select_expr indicates a column that you want to retrieve. There must be at least one select_expr.
    • table_references indicates the table or tables from which to retrieve rows.
    • The WHERE clause, if given, indicates the condition or conditions that rows must satisfy to be selected. where_condition is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause (i.e without any condition).
    • In the WHERE expression, you can use any of the functions and operators that MySQL supports, except for aggregate functions.

    SELECT can also be used to retrieve rows computed without reference to any table.

    For example:mysql> SELECT 5 – 3 ; +——-+ | 5 – 3 | +——-+ | 2 | +——-+ 1 row in set (0.00 sec)

    You can specify DUAL as a dummy table name where no tables are referenced :

    mysql> SELECT 5 – 3 FROM DUAL; +——-+ | 5 – 3 | +——-+ | 2 | +——-+ 1 row in set (0.00 sec)

    DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.

    In general, clauses used must be given in exactly the order shown in the syntax description. For example, a HAVING clause must come after any GROUP BY clause and before any ORDER BY clause. In the consequent pages of w3resource MySQL tutorial, you will find detail discussion accompanied by examples (often with PHP codes) of the said arguments of the SELECT statement.

    MySQL selecting all data

    MySQL SELECT statement without any condition retrieves all records from a table. The following SELECT statement will retrieve all data from publisher table.

    SELECT *
    FROM publisher;
    

    Copy

    Table: publisher

    Output:mysql> SELECT * FROM publisher; +——–+——————————+———–+———–+—————-+————–+————+ | pub_id | pub_name | pub_city | country | country_office | no_of_branch | estd | +——–+——————————+———–+———–+—————-+————–+————+ | P001 | Jex Max Publication | New York | USA | New York | 15 | 1969-12-25 | | P002 | BPP Publication | Mumbai | India | New Delhi | 10 | 1985-10-01 | | P003 | New Harrold Publication | Adelaide | Australia | Sydney | 6 | 1975-09-05 | | P004 | Ultra Press Inc. | London | UK | London | 8 | 1948-07-10 | | P005 | Mountain Publication | Houstan | USA | Sun Diego | 25 | 1975-01-01 | | P006 | Summer Night Publication | New York | USA | Atlanta | 10 | 1990-12-10 | | P007 | Pieterson Grp. of Publishers | Cambridge | UK | London | 6 | 1950-07-15 | | P008 | Novel Publisher Ltd. | New Delhi | India | Bangalore | 10 | 2000-01-01 | +——–+——————————+———–+———–+—————-+————–+————+ 8 rows in set (0.00 sec)

    PHP script

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>example-select-all-data - php MySQL examples | w3resource</title>
    </head>
    <body>
    <?php
    echo "<h2>List of the publishers with other detail : </h2>";
    echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
    echo "<tr style='font-weight: bold;'>";
    echo "<td width='200' align='center'>Publisher's ID</td><td width='200'align='center'>Publisher's Name</td><td width='200' align='center'>Publisher's City</td><td width='200' align='center'>Publisher's Country</td><td width='200' align='center'>Country Office</td><td width='200' align='center'>Number of branches</td><td width='200' align='center'>Date of Establishment</td>";
    echo "</tr>";
    include("../dbopen.php");
    $result = MySQL_query("SELECT * FROM publisher");
    while($row=MySQL_fetch_array($result))
    {
    echo "<tr>";
    echo "<td align='center' width='200'>" . $row['pub_id'] . "</td>";
    echo "<td align='center' width='200'>" . $row['pub_name'] . "</td>";
    echo "<td align='center' width='100'>" . $row['pub_city'] . "</td>";
    echo "<td align='center' width='100'>" . $row['country'] . "</td>";
    echo "<td align='center' width='100'>" . $row['country_office'] . "</td>";
    echo "<td align='center' width='100'>" . $row['no_of_branch'] . "</td>";
    echo "<td align='center' width='100'>" . $row['estd'] . "</td>";
    echo "</tr>";
    }
    echo "</table>";
    ?>
    </body>
    </html>
    

    Copy

    View the example in browser

    MySQL SELECT specific rows

    When a user wants to retrieve some individual rows from a table, a WHERE clause has to be added with the SELECT statement immediately followed by a condition.

    Syntax:SELECT * FROM WHERE where_condition

    Here * indicates all columns.

    Example:

    This following SELECT statement will retrieve those particular rows where ‘country’ is the USA.

    Code :SELECT * FROM publisher WHERE country=’USA’

    Output:> mysql> SELECT * FROM publisher -> WHERE country=’USA’; +——–+————————–+———-+———+—————-+————–+————+ | pub_id | pub_name | pub_city | country | country_office | no_of_branch | estd | +——–+————————–+———-+———+—————-+————–+————+ | P001 | Jex Max Publication | New York | USA | New York | 15 | 1969-12-25 | | P005 | Mountain Publication | Houstan | USA | Sun Diego | 25 | 1975-01-01 | | P006 | Summer Night Publication | New York | USA | Atlanta | 10 | 1990-12-10 | +——–+————————–+———-+———+—————-+————–+————+ 3 rows in set (0.01 sec)

    MySQL SELECT specific rows with AND operator

    MySQL AND operator is used to combine more than one conditions aiming to fetch records when both of the conditions are satisfied. The following SELECT statement will retrieve those particular rows where country and city of the publisher are ‘USA’ and ‘New York’.

    Code:

    SELECT *
    FROM publisher
    WHERE country='USA'
    AND pub_city='New York';
    

    Copy

    Output:mysql> SELECT * FROM publisher -> WHERE country=’USA’ -> AND pub_city=’New York’; +——–+————————–+———-+———+—————-+————–+————+ | pub_id | pub_name | pub_city | country | country_office | no_of_branch | estd | +——–+————————–+———-+———+—————-+————–+————+ | P001 | Jex Max Publication | New York | USA | New York | 15 | 1969-12-25 | | P006 | Summer Night Publication | New York | USA | Atlanta | 10 | 1990-12-10 | +——–+————————–+———-+———+—————-+————–+————+ 2 rows in set (0.00 sec)

    MySQL SELECT specific columns

    To retrieve records from specific columns, you need to specify a list of comma separated columns. The following MySQL statement returns the name of the book, author id, and price of the books from book_mast table.

    Table: book_mast

    Code:

    SELECT book_name,aut_id,book_price
    FROM book_mast;
    

    Copy

    Output:mysql> SELECT book_name,aut_id,book_price -> FROM book_mast; +————————————-+——–+————+ | book_name | aut_id | book_price | +————————————-+——–+————+ | Introduction to Electrodynamics | AUT001 | 85.00 | | Understanding of Steel Construction | AUT002 | 105.50 | | Guide to Networking | AUT003 | 200.00 | | Transfer of Heat and Mass | AUT004 | 250.00 | | Conceptual Physics | AUT005 | 145.00 | | Fundamentals of Heat | AUT006 | 112.00 | | Advanced 3d Graphics | AUT007 | 56.00 | | Human Anatomy | AUT008 | 50.50 | | Mental Health Nursing | AUT009 | 145.00 | | Fundamentals of Thermodynamics | AUT010 | 225.00 | | The Experimental Analysis of Cat | AUT011 | 95.00 | | The Nature of World | AUT005 | 88.00 | | Environment a Sustainable Future | AUT012 | 100.00 | | Concepts in Health | AUT013 | 180.00 | | Anatomy & Physiology | AUT014 | 135.00 | | Networks and Telecommunications | AUT015 | 45.00 | +————————————-+——–+————+ 16 rows in set (0.01 sec)

    MySQL select specific columns with distinct operator

    DISTINCT clause is used to retrieve unique rows from a table. The following MySQL statement retrieves the unique author ids from book_mast table.

    Code:

    SELECT DISTINCT aut_id
    FROM book_mast;
    

    Copy

    Output:mysql> SELECT DISTINCT aut_id -> FROM book_mast; +——–+ | aut_id | +——–+ | AUT001 | | AUT002 | | AUT003 | | AUT004 | | AUT005 | | AUT006 | | AUT007 | | AUT008 | | AUT009 | | AUT010 | | AUT011 | | AUT012 | | AUT013 | | AUT014 | | AUT015 | +——–+ 15 rows in set (0.01 sec)

    Note : If you look at the book_mast table shown under Sample table : book_mast heading, you would find that AUT005 (in ‘aut_id’ column) has appeared more than once. Using DISTINCT clause, we got rid of this redundancy.

    MySQL SELECT specific columns with logical OR operator

    OR operator retrieves records from a table if at least one of the given conditions is satisfied. The following MySQL statement retrieves records of pub_name, country, pub_city columns from publisher table if either Country (i.e. country) of the publisher is ‘USA’ or his city (i.e. pub_city) is ‘New York’.

    Code:

    SELECT pub_name, country,pub_city
    FROM publisher
    WHERE country='USA' OR pub_city='New York';
    

    Copy

    Output:mysql> SELECT pub_name,country,pub_city -> FROM publisher -> WHERE country=’USA’ OR pub_city=’New York’; +————————–+———+———-+ | pub_name | country | pub_city | +————————–+———+———-+ | Jex Max Publication | USA | New York | | Mountain Publication | USA | Houstan | | Summer Night Publication | USA | New York | +————————–+———+———-+ 3 rows in set (0.00 sec)

    MySQL sorting rows in ascending order

    MySQL ORDER BY clause specifies the order in which columns are sorted while retrieving data in a SELECT statement. By default, columns are sorted in ascending order. You can use ASC keyword to achieve the same result.

    Note : In the case of character type column sorting the sorting is dependent upon case sensitivity. The default sort order is ascending this means smallest value comes first. To sort in reverse order, DESC key has to be used.

    In the following MySQL statement, all records of pub_name, country and pub_city columns of publisher table are being fetched and sorted against pub_name column. Since we have not specified any order keyword (ASC or DESC), by default, it is sorted in ascending order.

    Code:

    SELECT pub_name, country,pub_city 
    FROM publisher
    ORDER BY pub_name;
    

    Copy

    Output:mysql> SELECT pub_name,country,pub_city -> FROM publisher -> ORDER BY pub_name; +——————————+———–+———–+ | pub_name | country | pub_city | +——————————+———–+———–+ | BPP Publication | India | Mumbai | | Jex Max Publication | USA | New York | | Mountain Publication | USA | Houstan | | New Harrold Publication | Australia | Adelaide | | Novel Publisher Ltd. | India | New Delhi | | Pieterson Grp. of Publishers | UK | Cambridge | | Summer Night Publication | USA | New York | | Ultra Press Inc. | UK | London | +——————————+———–+———–+ 8 rows in set (0.02 sec)

    MySQL sorting rows in descending order

    The following MySQL statement sort rows of a table in descending order using ORDER BY clause.

    Code:

    SELECT pub_name, country,pub_city
    FROM publisher
    ORDER BY pub_name DESC;
    

    Copy

    Output:mysql> SELECT pub_name,country,pub_city -> FROM publisher -> ORDER BY pub_name DESC; +——————————+———–+———–+ | pub_name | country | pub_city | +——————————+———–+———–+ | Ultra Press Inc. | UK | London | | Summer Night Publication | USA | New York | | Pieterson Grp. of Publishers | UK | Cambridge | | Novel Publisher Ltd. | India | New Delhi | | New Harrold Publication | Australia | Adelaide | | Mountain Publication | USA | Houstan | | Jex Max Publication | USA | New York | | BPP Publication | India | Mumbai | +——————————+———–+———–+ 8 rows in set (0.00 sec)

    MySQL sorting rows on multiple columns

    Sort can be performed on multiple columns. The way this type of sort happen is, firstly the rows will be sorted on the first column then the rows will be sorted on the second column whose first column’s data are same.

    In the following MySQL statement, all records of pub_name, country and pub_city columns of publisher table are being fetched and sorted against country and pub_city columns. Since we have not specified any order keyword (ASC or DESC), by default, it is sorted in ascending order.

    Code:

    SELECT pub_name, country,pub_city
    FROM publisher
    ORDER BY country,pub_city;
    

    Copy

    Output :mysql> SELECT pub_name, country, pub_city -> FROM publisher -> ORDER BY country, pub_city; +——————————+———–+———–+ | pub_name | country | pub_city | +——————————+———–+———–+ | New Harrold Publication | Australia | Adelaide | | BPP Publication | India | Mumbai | | Novel Publisher Ltd. | India | New Delhi | | Pieterson Grp. of Publishers | UK | Cambridge | | Ultra Press Inc. | UK | London | | Mountain Publication | USA | Houstan | | Jex Max Publication | USA | New York | | Summer Night Publication | USA | New York | +——————————+———–+———–+ 8 rows in set (0.00 sec)

    MySQL select with NULL value

    IS NULL, IS NOT NULL is used to select or test if a value stored in a table is NULL. While writing a MySQL statement, NULL keyword is used to specify a null value.

    What is NULL value ?

    • A value of NULL says that the value is unknown, not applicable or will be added later.
    • A value of NULL is not an empty or zero value.
    • No two null values are equal.
    • Since a value of NULL is unknown, comparisons between two null values, or between a NULL and any other value, returns unknown.

    Example of SELECT with NULL :

    Code:

    SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;
    

    Copy

    Output:mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1> NULL; +———-+———–+———-+———+ | 1 = NULL | 1 <> NULL | 1 < NULL | 1> NULL | +———-+———–+———-+———+ | NULL | NULL | NULL | NULL | +———-+———–+———-+———+ 1 row in set (0.01 sec)

    Example of SELECT with IS NULL, IS NOT NULL :

    Code:

    SELECT 1 IS NULL, 1 IS NOT NULL;
    

    Copy

    Output:mysql> SELECT 1 IS NULL, 1 IS NOT NULL; +———–+—————+ | 1 IS NULL | 1 IS NOT NULL | +———–+—————+ | 0 | 1 | +———–+—————+ 1 row in set (0.00 sec)

  • MySQL DELETE statement

    DELETE statement

    DELETE statement is used to remove rows from a table.

    Version: MySQL 5.6

    Single-table syntax:DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM table_name [PARTITION (partition_name,…)] [WHERE where_condition] [ORDER BY …] [LIMIT row_count]

    Explanation:

    • The DELETE statement deletes rows from table_name and returns the number of deleted rows. You can use ROW_COUNT() function to check the number of deleted rows.
    • The conditions in the WHERE clause (optional) identify which rows to delete.
    • Without WHERE clause, all rows are deleted.
    • If you specify the ORDER BY clause, the rows are deleted in specified order.
    • The LIMIT clause is used to place a limit on the number of rows that can be deleted. These clauses apply to single-table deletes, but not multi-table deletes.

    Multiple-table syntax :DELETE [LOW_PRIORITY] [QUICK] [IGNORE] tbl_name[.*] [, tbl_name[.*]] … FROM table_references [WHERE where_condition]

    Or :DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name[.*] [, tbl_name[.*]] … USING table_references [WHERE where_condition]

    Important points:

    • Privileges: To delete a record(s) from a table, the user must have the DELETE privilege on that particular table.
    • The TRUNCATE TABLE statement is a faster way to empty a table than a DELETE statement with no WHERE clause. Here is a detail discussion on the difference between DELETE and TRUNCATE statement.
    • Subqueries: Currently there is no option to delete from a table and select from the same table in a subquery.
    • As of MySQL 5.6.2, DELETE supports explicit partition selection using the PARTITION option, which takes a comma-separated list of the names of one or more partitions or subpartitions (or both) from which to select rows to be dropped. Partitions not included in the list are ignored. Given a partitioned table t with a partition named p0, executing the statement DELETE FROM t PARTITION (p0) has the same effect on the table as executing ALTER TABLE t TRUNCATE PARTITION (p0); in both cases, all rows in partition p0 are dropped.
    • Auto-Increment Columns : If you delete the row containing the maximum value for an AUTO_INCREMENT column, the value is not reused for a MyISAM or InnoDB table.

    Example: MySQL DELETE specific rows or records

    The following statement will remove those records from the ‘newcate’ table which satisfies the condition ‘cate_id’ = ‘CA002’.

    Sample table: newcate

    Code:

    DELETE FROM newcate 
    WHERE cate_id='CA002';
    

    Copy

    Example: MySQL DELETE all rows or records

    If not accompanied by any condition about which rows are to be removed, MySQL DELETE statement removes all records or rows from a table. The following statement will remove all the rows or records from ‘Newcate’ table.

    Code:

    DELETE FROM Newcate;
    

    Copy

    Example: MySQL DELETE with ORDER BY for limited number of rows

    ORDER BY and LIMIT keyword can be used with MySQL DELETE statement to remove only a given number of rows, where columns are sorted in a specific order. The ORDER BY clause sorts the columns in a specific order and the LIMIT keyword deletes only the number rows mentioned by the numeric value immediately followed by LIMIT keyword. See the following example:

    Sample table : newauthor

    Code:

    DELETE FROM newauthor 
    ORDER BY country DESC LIMIT  2;
    

    Copy

    The statement above will do the following –
    1. order the rows of ‘newauthor’ table in descending order according to column ‘country’,
    2. 
    delete only two(2) rows for each ‘country’.

    Example: MySQL DELETE rows using subqueries with alias and EXISTS

    A subquery can be used with MySQL DELETE statement. This is useful when you want to delete rows depending upon a complex condition.

    If we want to remove records from ‘newauthor’ table with following conditions –
    1. ‘aut_id’ of ‘newauthor’ table must exist in ‘book_mast’ table,
    2. ‘no_pages’ of ‘book_mast’ table must be more than 300,
    3. ‘aut_id’ of ‘newauthor’ and ‘aut_id’ of ‘book_mast’ must match,

    then execute the following code.

    Sample table: newauthor

    Sample table: book_mast

    Code:

    DELETE FROM newauthor 
    WHERE exists 
    (SELECT * 
    FROM  book_mast 
    WHERE no_page>300 
    AND newauthor.aut_id=book_mast.aut_id);
    

    Copy

    MySQL TRUNCATE table

    MySQL TRUNCATE TABLE statement is used to delete all the rows from a table. Apparently, this is similar to ‘DELETE FROM <TABLE NAME>’ statement,but they are quite different.

    Difference between TRUNCATE and DELETE

    TRUNCATEDELETE
    It is a DDL command (i.e. a command used to define the database structure or schema) and once you have deleted the rows using it, you can not use the ROLLBACK to undo the task.It is a DML command (i.e. a command used for managing data) and can be rolled back.
    You can’t use WHERE clause.You can use WHERE clause.
    Faster than DELETE.Slower than TRUNCATE.

    Syntax:TRUNCATE table<table_name>

    Where table_name indicates name of the table

    Example: MySQL TRUNCATE table

    The following MySQL statement will delete all the rows from the newauthor table.

    Sample table: newauthor

    Code:

    TRUNCATE TABLE newauthor;
    
  • MySQL UPDATE Statement

    UPDATE Table

    The MySQL UPDATE statement is used to update columns of existing rows in a table with new values.

    Version: 5.6

    Syntax :

    Single table:UPDATE [LOW_PRIORITY] [IGNORE] table_reference       SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] …       [WHERE where_condition]       [ORDER BY …]       [LIMIT row_count]

    Multiple tables:UPDATE [LOW_PRIORITY] [IGNORE] table_references       SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] …       [WHERE where_condition]

    Arguments

    NameDescription
    table_reference(s)Name of table(s) to be updated.
    col_name1, col_name2, ..Name of column(s) to be updated.
    expr1, expr2,…New value(s).
    • For a single table, the UPDATE statement updates columns of existing rows in the named table with new values. Specific columns can be modified using the SET clause by supplying new values for that column.
    • The WHERE clause can be used to specify the conditions those identify which rows to update. Without using WHERE clause, all rows are updated.
    • The ORDER BY clause is used to update the order that is already specified.
    • The LIMIT clause specifies a limit on the number of rows that can be updated.
    • For multiple tables, UPDATE updates row in each table named in table_references that satisfy the conditions. In this case, ORDER BY and LIMIT cannot be used.

    The UPDATE statement supports the following modifiers:

    • LOW_PRIORITY: Using LOW_PRIORITY keyword, execution of the UPDATE is delayed until no other clients are reading from the table. This affects only storage engines that use only table-level locking (such as MyISAM, MEMORY, and MERGE).
    • IGNORE : Using IGNORE keyword, the update statement does not abort even if errors occur during the update. Rows for which duplicate-key conflicts occur are not updated. Rows for which columns are updated to values that would cause data conversion errors are updated to the closest valid values instead.

    Following are some examples on MySQL update where we have used newpurchase as sample table.

    Sample table: newpurchase

    MySQL UPDATE column

    MySQL UPDATE column can be used to update some specific columns. The following MySQL statement will update the ‘receive_qty’ column of newpurchase table with a new value 20.

    UPDATE newpurchase SET receive_qty=20;
    

    Copy

    MySQL UPDATE with WHERE

    MySQL UPDATE command can be used with WHERE clause to filter (against certain conditions) which rows will be updated. The following MySQL statement will update the ‘receive_qty’ column of newpurchase table with a new value 25 if the value of purch_price is more than 50.

    UPDATE newpurchase 
    SET receive_qty=25 
    WHERE purch_price>50;
    

    Copy

    MySQL UPDATE using NULL

    MySQL UPDATE command can be used to update a column value to NULL by setting column_name = NULL, where column_name is the name of the column to be updated. The following MySQL statement will update pub_lang column with NULL if purch_price is more than 50. In this statement, other columns are also updated with respective new values.

    UPDATE newpurchase 	
    SET receive_qty=20,pub_lang='Hindi',pub_lang=NULL 
    WHERE purch_price>50;
    

    Copy

    MySQL UPDATE multiple columns

    MySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated. The following MySQL statement will update receive_qty, pub_lang, and receive_dt columns with new values 20, Hindi and 2008-07-10 if purch_price is more than 50.

    UPDATE newpurchase 
    SET receive_qty=20,pub_lang='Hindi',receive_dt='2008-07-10' 
    WHERE purch_price>50;
    

    Copy

    MySQL UPDATE with subqueries

    Here in the following, we have discussed how to use MySQL UPDATE command with subqueries.

    The following MySQL statement will update purch_price with purch_price multiplied by 5 if it satisfies the condition defined in the subquery started with SELECT wrapped within a pair of parenthesis.

    The subquery retrieves only those cate_ids from purchase table if their corresponding receive_qty is more than 10.

    UPDATE  newpurchase 
    SET purch_price=purch_price*.05
    WHERE cate_id IN(SELECT cate_id 
    FROM purchase 
    WHERE receive_qty>10);
    

    Copy

    Updating MySQL Table using PHP Script

    You can update MySQL table data (using UPDATE command) through a PHP script. Within the script, PHP function MySQL_query() execute the SQL command. We have used a table called ‘item’ to apply the query:
    Table Name : item Structure : item_code varchar(20), value int(11), quantity int(11) where item_code is the primary key. In the following rows of item table, ‘value’ column which is marked with red rectangle will be updated.

    item master

    PHP Script

     <?php
      $dbhost = 'localhost';
      $dbuser = 'root';
      $dbpass = '';
      $connec = MySQL_connect($dbhost, $dbuser, $dbpass);
      if(!$connec)
      {
      die('Could not connect: ' . MySQL_error());
      }
      $sql = "UPDATE item
      SET value = '112'
      WHERE item_code='item1'";
      MySQL_select_db('MySQL');
      $result = MySQL_query($sql, $connec);
      if(!$result)
      {
      die('Could not update data: ' . MySQL_error());
      }
      echo "Data successfully updated...";
      MySQL_close($connec);
      ?>
    

    Copy

    Sample Output:

    updated item master

    Multiple Updates in MySQL

    Sample table: table1

    sample table test1

    Problem

    If you want to update the val1 with 5,8 and 7 for concerned id 1,3 and 4 and the other val1 will remain same and the val2 will be updated with 13 and 5 for the concerned id 2 and 4 and the other will remain same, the following update statement can be used by using IF and CASE.

    Code:

    UPDATE table1 SET val1= CASE id 
    
                          WHEN 1 THEN 5 
                          WHEN 3 THEN 8 
                          WHEN 4 THEN 7 
                          ELSE val1
                        END, 
                 val2= CASE id 
                          WHEN 2 THEN 13 
                          WHEN 4 THEN 5 
                          ELSE val2 
                        END
             WHERE id IN (1, 2, 3, 4);

    Copy

    Pictorial presentation:

    mysql update iamge

    Sample Output:

    Mysql update image1

    Examples: MySQL UPDATE on multiple tables

    Here we have used two tables book_mast and purchase for the following exampleas sample table. We have shown some of the columns in the associated tables. Here are the tables below -MySQL> SELECT book_id,book_name,pub_lang,book_price -> FROM book_mast; +——–+————————————+———+———-+ | book_id| book_name | pub_lang|book_price| +——–+————————————+———+———-+ | BK001 | Introduction to Electrodynamics | English | 85.00| | BK002 | Understanding of Steel Construction| English | 105.50| | BK003 | Guide to Networking | Hindi | 200.00| | BK004 | Transfer of Heat and Mass | English | 250.00| | BK005 | Conceptual Physics | NULL | 145.00| | BK006 | Fundamentals of Heat | German | 112.00| | BK007 | Advanced 3d Graphics | Hindi | 56.00| | BK008 | Human Anatomy | German | 50.50| | BK009 | Mental Health Nursing | English | 145.00| | BK010 | Fundamentals of Thermodynamics | English | 225.00| | BK011 | The Experimental Analysis of Cat | French | 95.00| | BK012 | The Nature of World | English | 88.00| | BK013 | Environment a Sustainable Future | German | 100.00| | BK014 | Concepts in Health | NULL | 180.00| | BK015 | Anatomy & Physiology | Hindi | 135.00| | BK016 | Networks and Telecommunications | French | 45.00| +——–+————————————+———+———-+ 16 rows in set (0.00 sec) and MySQL> SELECT book_id,pub_lang,purch_price,total_cost -> FROM purchase; +———+———-+————-+————+ | book_id | pub_lang | purch_price | total_cost | +———+———-+————-+————+ | BK001 | English | 75.00 | 1125.00 | | BK004 | English | 55.00 | 440.00 | | BK005 | NULL | 20.00 | 400.00 | | BK004 | English | 35.00 | 525.00 | | BK001 | English | 25.00 | 200.00 | | BK003 | Hindi | 45.00 | 900.00 | +———+———-+————-+————+ 6 rows in set (0.02 sec)

    https://www.adsensecustomsearchads.com/afs/ads?psid=5134551505&channel=AutoRsVariant&cx=r-440389826592af9d2&fexp=21404%2C17301383%2C71847096&client=pub-2153208817642134&r=m&sct=ID%3Df1c5d672aa31266c%3AT%3D1706354011%3ART%3D1706354011%3AS%3DALNI_MZlJMMg_q5l3r_1tPiuFzhttpHLOQ&sc_status=6&hl=en&rpbu=http%3A%2F%2Fgoogle.com&rpqp=q&type=3&rs_tt=c&oe=UTF-8&ie=UTF-8&format=r5&nocache=9511706465573335&num=0&output=afd_ads&domain_name=www.w3resource.com&v=3&bsl=10&pac=0&u_his=7&u_tz=-480&dt=1706465573337&u_w=1366&u_h=768&biw=1297&bih=644&psw=1297&psh=644&frm=0&cl=600476684&uio=-&cont=autors-container-0&drt=0&jsid=csa&jsv=600476684&rurl=https%3A%2F%2Fwww.w3resource.com%2Fmysql%2Fupdate-table%2Fupdate-table.php&referer=https%3A%2F%2Fwww.w3resource.com%2Fmysql%2Fmysql-partition.php

    If we want to update the book_price of the table book_mast by an increment of 5% and also update the purch_price and total_cost of puchase table by an increment of 5%, and this increment will affect only those rows in both book_mast and purchase table, which publishing language is English and book_id matching in both the tables, we can write the following code –

    UPDATE book_mast,purchase
    SET book_mast.book_price=book_mast.book_price+(book_mast.book_price*.05),
    purchase.purch_price=purchase.purch_price+(purchase.purch_price*.05),
    purchase.total_cost=receive_qty*(purchase.purch_price+(purchase.purch_price*.05))
    WHERE book_mast.book_id=purchase.book_id
    AND purchase.pub_lang="English";
    

    Copy

    After updating it is to be shown that, the highlighted rows have been effected in both the tables.MySQL> SELECT book_id,book_name,pub_lang,book_price -> FROM book_mast; +——–+————————————+———+———-+ | book_id| book_name | pub_lang|book_price| +——–+————————————+———+———-+ | BK001 | Introduction to Electrodynamics | English | 89.25| | BK002 | Understanding of Steel Construction| English | 105.50| | BK003 | Guide to Networking | Hindi | 200.00| | BK004 | Transfer of Heat and Mass | English | 262.50| | BK005 | Conceptual Physics | NULL | 145.00| | BK006 | Fundamentals of Heat | German | 112.00| | BK007 | Advanced 3d Graphics | Hindi | 56.00| | BK008 | Human Anatomy | German | 50.50| | BK009 | Mental Health Nursing | English | 145.00| | BK010 | Fundamentals of Thermodynamics | English | 225.00| | BK011 | The Experimental Analysis of Cat | French | 95.00| | BK012 | The Nature of World | English | 88.00| | BK013 | Environment a Sustainable Future | German | 100.00| | BK014 | Concepts in Health | NULL | 180.00| | BK015 | Anatomy & Physiology | Hindi | 135.00| | BK016 | Networks and Telecommunications | French | 45.00| +——–+————————————+———+———-+ 16 rows in set (0.01 sec) and MySQL> SELECT book_id,pub_lang,purch_price,total_cost -> FROM purchase; +———+———-+————-+————+ | book_id | pub_lang | purch_price | total_cost | +———+———-+————-+————+ | BK001 | English | 78.75 | 1181.25 | | BK004 | English | 57.75 | 462.00 | | BK005 | NULL | 20.00 | 400.00 | | BK004 | English | 36.75 | 551.25 | | BK001 | English | 26.25 | 210.00 | | BK003 | Hindi | 45.00 | 900.00 | +———+———-+————-+————+ 6 rows in set (0.08 sec)

    MySQL: Update with Join Statement

    Sample tables

    sample table test1

    Problem

    If we want to update the aval1of table11 with the bval1 of table12 against the following condition –

    1). the id of table11 and table13 must be matched, and

    2). bval2 of table12 must be matched with the cval1 of table13 –

    then the following code can be used.

    Code:

    UPDATE table11, table12, table13 
    SET table11.aval1 = table12.bval1
    WHERE table11.id = table13.id 
    AND table12.bval2 = table13.cval1
    

    Copy

    Explanation

    Mysql update three tables explaination

    Output:

    Mysql update three tables image2
  • MySQL INSERT statement

    INSERT statement

    MySQL INSERT statement is used to insert record(s) or row(s) into a table. The insertion of records or rows in the table can be done in two ways, insert a single row at a time, and insert multiple rows at a time.

    Version: MySQL 5.6

    Syntax:INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] [(col_name,…)] {VALUES | VALUE} ({expr | DEFAULT},…),(…),… [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] … ]

    or:INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] SET col_name={expr | DEFAULT}, … [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] … ]

    or:INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] [(col_name,…)] SELECT … [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] … ]

    Arguments:

    NameDescriptions
    INSERTInserts new rows into an existing table.
    LOW_PRIORITYUsing the LOW_PRIORITY keyword, execution of the INSERT is delayed until no other clients are reading from the table. This includes other clients that began reading while existing clients are reading. Therefore it is possible, for a client that issues an INSERT LOW_PRIORITY statement to wait for a very long time (or even forever) in a read-heavy environment.
    DELAYEDUsing DELAYED keyword, the server puts the row or rows to be inserted into a buffer, and the INSERT DELAYED statement (issued by the client) can then continue immediately. The server holds the rows if the table is in use. The server begins inserting rows, when the table is free, checking periodically to see whether there are any new read requests for the table. If there are any new read requests, the delayed row queue is suspended until the table becomes free again.
    HIGH_PRIORITYUsing HIGH_PRIORITY, it overrides the effect of the –low-priority-updates option if the server was started with that option. It also causes concurrent inserts not to be used.
    LOW_PRIORITY and HIGH_PRIORITY affect only storage engines that use only table-level locking such as MyISAM, MEMORY, and MERGE.
    IGNOREUsing the IGNORE keyword, errors that occur while executing the INSERT statement are ignored.
    INTOInserts new rows into an existing table.
    tbl_nameName of the table where rows will be inserted.
    PARTITIONIn MySQL 5.6.2 and later, you can control which partitions and subpartitions accept new rows when inserting into a partitioned table. The PARTITION option takes a comma-separated list of the names of one or more partitions or subpartitions (or both) of the table. If any of the rows which are ready to insert, by a given INSERT statement do not match one of the partitions listed, the INSERT statement fails with the error Found a row not matching the given partition set.
    partition_nameName of the partitioned table(s).
    col_nameA comma-separated list of column names.You can specify a comma-separated list of column names following the table name and a value for each named column must be provided by the VALUES list or the SELECT statement.If you do not specify the column names for INSERT … VALUES or INSERT … SELECT, values for every column in the table must be provided by the VALUES list (same as order of the columns in the table) or the SELECT statement.The SET clause indicates the column names explicitly.
    VALUES | VALUEIf strict SQL mode is off, any column not explicitly given a value is set to its default (explicit or implicit) value. For example, if you specify a column list that does not name all the columns in the table, unnamed columns are set to their default values.The keyword DEFAULT is used to set a column explicitly to its default value.If both the column list and the VALUES list are empty, INSERT creates a row with each column set to its default value.You can specify an expression expr to provide a column value. This might involve type conversion if the type of the expression does not match the type of the column, and conversion of a given value can result in different inserted values depending on the data type. For example, inserting the string ‘1998.0e-2’ into an INT, FLOAT, DECIMAL(10,6), or YEAR column results in the values 1998, 19.9821, 19.982100, and 1998 being inserted, respectively.

    INSERT … SELECT

    To insert many rows quickly into a table from one or many tables you can use INSERT … SELECT statement. Here is the syntax :

    Syntax:INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] [(col_name,…)] SELECT … [ ON DUPLICATE KEY UPDATE col_name=expr, … ]

    The following conditions hold for a INSERT … SELECT statements :

    • Using the IGNORE keyword, ignore rows that would cause duplicate-key violations.
    • The keyword DELAYED is ignored with INSERT … SELECT.
    • The target table of the INSERT statement may appear in the FROM clause of the SELECT part of the query.
    • AUTO_INCREMENT columns work as usual.
    • To avoid ambiguous column reference problems when the SELECT and the INSERT refer to the same table.
    • In MySQL 5.6.2 and later, you can control which partitions and subpartitions accept new rows when inserting into a partitioned table.

    Example:INSERT INTO tb2 (fld_id) SELECT tbl.fld_order_id FROM tbl WHERE tbl.fld_order_id > 200;

    INSERT DELAYED

    The DELAYED option for the INSERT statement is a MySQL extension to standard SQL that can be used for certain kinds of tables (such as MyISAM). When a client uses INSERT DELAYED, it gets an okay from the server at once, and the row is queued to be inserted when the table is not in use by any other thread.

    Syntax:INSERT DELAYED …

    INSERT … ON DUPLICATE KEY UPDATE

    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs a UPDATE of the old row. For example, if column x is declared as UNIQUE and contains the value 1, the following two statements have similar effect:INSERT INTO table (x,y,z) VALUES (1,2,3) ON DUPLICATE KEY UPDATE z=z+1; UPDATE table SET z=z+1 WHERE x=1;

    Note: The effects are not identical for an InnoDB table where a is an auto-increment column. With an auto-increment column, an INSERT statement increases the auto-increment value but UPDATE does not.

    Examples:

    MySQL INSERT INTO statement is used to insert record(s) or row(s) into a table.

    Syntax:INSERT INTO table_name ([column_name],[…column_name],…) VALUES( [column_value],[..column_value]);

    Example with PHP code to insert data into a MySQL table

    HTML code (say form.html):

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>form to insert data</title>
    </head>
    <body>
    <form method="post" action="insert.php">
    <input type="text" name="name" />
    <input type="text" name="email" />
    <input type="text" name="address" />
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    

    Copy

    PHP code (say insert.php):

    <?php
    $host="localhost"; //yout host name
    $username="root";  //yout user name
    $password="";      // your password
    $db_name="test";  // your database name
    $con=MySQL_connect("$host", "$username", "$password")or die("cannot connect"); //MySQL connection
    MySQL_select_db("$db_name")or die("can not select DB"); //select your database
    $name = $_POST['name'];
    $email = $_POST['email'];
    $address = $_POST['address'];
    $query = "INSERT INTO test (name,email,address) VALUES ('$name', '$email', '$address')";
    MySQL_query($query) or die('Query "' . $query . '" failed: ' . MySQL_error());
    // name, email and address are fields of your fields; test your table. $name, $email and $address are values collected from the form
    ?>
    

    Copy

    MySQL: INSERT one row in a table

    The following statement inserts a single row into a table using MySQL INSERT INTO statement.

    Code:

    INSERT INTO newcate 
    VALUES ("CA006","Sports");
    

    Copy

    The above statement will insert one row in the table ‘newcate’. We have not mentioned any column name here. That is why all of the columns will be affected.mysql> select * from newcate; +———+————–+ | cate_id | cate_descrip | +———+————–+ | CA001 | Science | | CA002 | Technology | | CA003 | Computers | | CA004 | Nature | | CA005 | Medical | | CA006 | Sports | +———+————–+ 6 rows in set (0.00 sec)

    MySQL: INSERT values for specific columns

    The following statement inserts values for specific columns using MySQL INSERT INTO statement.

    Sample table: newpurchase

    Code:

    INSERT INTO newpurchase  (invoice_no,ord_no,book_name)
    VALUES  ("INV001","ORD006",”An advance book of Computer”);
    

    Copy

    The above statement will insert one(1) row in the table ‘newpurchase’ for the columns ‘invoice_no’, ‘ord_no’, and ‘book_name’.

    MySQL: INSERT NULL values

    The following statement inserts NULL values into one or more columns using MySQL INSERT INTO statement.

    Sample table: newpurchase

    Code:

    INSERT INTO newpurchase (invoice_no,ord_no,book_name) 
    VALUES ("INV002","ORD007",NULL);
    

    Copy

    The above statement will insert one(1) row in the table ‘newpurchase’. Columns ‘invoice_no’, ‘ord_no’, and ‘book_name’ got populated with values where as column ‘book_name’ got populated with the NULL value.

    Inserting multiple rows in a single SQL query

    In MySQL, you can insert multiple rows in a single SQL query. Here is the syntax:INSERT INTO Table ( Column1, Column2 ) VALUES ( Value1, Value2 ), ( Value1, Value2 );

    MySQL INSERT rows with SELECT statement

    The following statement inserts values into a table using MySQL INSERT INTO statement when the column names and values are collected from another identical table using MySQL SELECT statement. This way you can insert values of one table into another when tables are identical.

    Sample table : purchase

    Code:

    INSERT INTO testpurchase 
    SELECT * 
    FROM purchase;
    

    Copy

    MySQL INSERT rows with SELECT statement and WHERE

    The following statement inserts values into a table using MySQL INSERT INTO statement when the column names and values are collected from another identical table using MySQL SELECT and WHERE. This way you can insert values based upon some conditions of one table into another when tables are identical.

    Sample table: purchase

    Code:

    INSERT INTO testpurchase 
    SELECT * 
    FROM purchase 
    WHERE YEAR(invoice_dt)='2008';
    

    Copy

    The above statement performs the following operations –

    • insert rows into  ‘testpurchase’ table from the identical table ‘purchase’,
    • the year of ‘invoice_date’ of ‘purchase’ table must be ‘2008’ .
  • MySQL Partitioning

    What is Partitioning?

    Partitioning (a database design technique) improves performance, manageability, simplifies maintenance and reduce the cost of storing large amounts of data. Partitioning can be achieved without splitting tables by physically putting tables on individual disk drives. Partitioning allows tables, indexes, and index-organized tables to be subdivided into smaller pieces, therefore queries that access only a fraction of the data can run faster because there is fewer data to scan. There are two major forms of partitioning :

    • Horizontal Partitioning : Horizontal partitioning divides table rows into multiple partitions (based on a logic). All columns defined to a table are found in each partition, so no actual table attributes are missing. All the partition can be addressed individually or collectively. For example, a table that contains whole year sale transaction being partitioned horizontally into twelve distinct partitions, where each partition contains one month’s data.
    • Vertical Partitioning : Vertical partitioning divides a table into multiple tables that contain fewer columns. Like horizontal partitioning, in vertical partitioning a query scan fewer data which increases query performance. For example, a table that contains a number of very wide text or BLOB columns that aren’t addressed often being broken into two tables that have the most referenced columns in one table and the text or BLOB data in another.

    MySQL partitioning

    Version: MySQL 5.6

    MySQL supports basic table partitioning but does not support vertical partitioning ( MySQL 5.6). This section describes in detail how to implement partitioning as part of your database.

    By checking the output of the SHOW PLUGINS statement you will be sure whether your MySQL server supports the partition or not. See the following output :

    Sample Output:mysql> SHOW PLUGINS; +—————————-+———-+——————–+———+———+ | Name | Status | Type | Library | License | +—————————-+———-+——————–+———+———+ | binlog | ACTIVE | STORAGE ENGINE | NULL | GPL | | MySQL_native_password | ACTIVE | AUTHENTICATION | NULL | GPL | | MySQL_old_password | ACTIVE | AUTHENTICATION | NULL | GPL | | sha256_password | ACTIVE | AUTHENTICATION | NULL | GPL | | CSV | ACTIVE | STORAGE ENGINE | NULL | GPL | | MEMORY | ACTIVE | STORAGE ENGINE | NULL | GPL | | MyISAM | ACTIVE | STORAGE ENGINE | NULL | GPL | | MRG_MYISAM | ACTIVE | STORAGE ENGINE | NULL | GPL | | ARCHIVE | ACTIVE | STORAGE ENGINE | NULL | GPL | | BLACKHOLE | ACTIVE | STORAGE ENGINE | NULL | GPL | | FEDERATED | DISABLED | STORAGE ENGINE | NULL | GPL | | InnoDB | ACTIVE | STORAGE ENGINE | NULL | GPL | | INNODB_TRX | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | INNODB_LOCKS | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | INNODB_CMPMEM | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | —————————| —— | —————— | —- | — | | —————————| —— | —————— | —- | — | | —————————| —— | —————— | —- | — | | INNODB_SYS_TABLESPACES | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | INNODB_SYS_DATAFILES | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | PERFORMANCE_SCHEMA | ACTIVE | STORAGE ENGINE | NULL | GPL | | partition | ACTIVE | STORAGE ENGINE | NULL | GPL | +—————————-+———-+——————–+———+———+ 42 rows in set (0.21 sec)

    MySQL 5.6 Community binaries include partitioning support.

    Enable and disable partitioning support :

    • To enable partitioning (if you are compiling MySQL 5.6 from source), the build must be configured with the -DWITH_PARTITION_STORAGE_ENGINE option.
    • To disable partitioning support, you can start the MySQL Server with the –skip-partition option, in which case the value of have_partitioning is DISABLED.

    How to partition a table?

    In MySQL you can partition a table using CREATE TABLE or ALTER TABLE command. See the following CREATE TABLE syntax :CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,…)

    [table_options]

    [partition_options]

    partition_options:PARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY(column_list) | RANGE(expr) | LIST(expr) } [PARTITIONS num] [SUBPARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY(column_list) } [SUBPARTITIONS num] ] [(partition_definition[, partition_definition] …)

    partition_definition:PARTITION partition_name [VALUES {LESS THAN {(expr) | MAXVALUE} | IN (value_list)}] [[STORAGE] ENGINE [=] engine_name] [COMMENT [=] ‘comment_text’ ] [DATA DIRECTORY [=] ‘data_dir’] [INDEX DIRECTORY [=] ‘index_dir’] [MAX_ROWS [=] max_number_of_rows] [MIN_ROWS [=] min_number_of_rows] [TABLESPACE [=] tablespace_name] [NODEGROUP [=] node_group_id] [(subpartition_definition [, subpartition_definition] …)]

    subpartition_definition:SUBPARTITION logical_name [[STORAGE] ENGINE [=] engine_name] [COMMENT [=] ‘comment_text’ ] [DATA DIRECTORY [=] ‘data_dir’] [INDEX DIRECTORY [=] ‘index_dir’] [MAX_ROWS [=] max_number_of_rows] [MIN_ROWS [=] min_number_of_rows] [TABLESPACE [=] tablespace_name] [NODEGROUP [=] node_group_id]

    ALTER TABLE: Partition operations

    ALTER TABLE statement can be used for adding, dropping, merging, and splitting partitions, and for performing partitioning maintenance. Here we have defined a nonpartitioned table:

    CREATE TABLE sale_mast (
    bill_no INT,
    bill_date DATETIME
    );
    

    Copy

    This table can be partitioned by HASH (or in another type), using the bill_no column as the partitioning key, into 6 (or other) partitions using ALTER TABLE statement :

    ALTER TABLE t1
    
    PARTITION BY HASH(id)
    PARTITIONS 6;

    Copy

    Partition naming :

    Names of partitions follow the rules of other MySQL identifiers such as databases, tables, constraint, stored procedure etc. Partition names are not case-sensitive.

    Advantages of partitioning

    • During the scan operation, MySQL optimizer accesses those partitions that will satisfy a particular query. For example, a whole year sale records table may be broken up into 4 partitions (i.e. sale data from of Apr-Jun (partition p0), Jul-Sep (partition p1) , Oct-Dec (partition p2), Jam-Mar (partition p0)) . If a query is issued that contains sale data between Jul-Sep quarter, then it scans the partition p1 only instead of total table records and the query will complete much sooner.
    • Partitioning allows you to have more control over how data is managed inside the database. For example, you can drop specific partitions in a partitioned table where data loses its usefulness. The process of adding new data, in some cases, be greatly facilitated by adding one or more new partitions for storing that data using ALTER TABLE command.
    • In partitioning, it is possible to store more data in one table than can be held on a single disk or file system partition.
    • MySQL 5.6 supports explicit partition selection for queries. For example, SELECT * FROM table1 PARTITION (p0,p1) WHERE col1< 10 selects only those rows in partitions p0 and p1 that match the WHERE condition, this can greatly speed up queries
    • Partition selection also supports the data modification statements DELETE, INSERT, REPLACE, UPDATE, and LOAD DATA, LOAD XML.

    Types of MySQL partitioning

    Following types of partitioning are available in MySQL 5.6 :

    MySQL RANGE Partitioning

    In MySQL, RANGE partitioning mode allows us to specify various ranges for which data is assigned. Ranges should be contiguous but not overlapping, and are defined using the VALUES LESS THAN operator. In the following example, sale_mast table contains four columns bill_no, bill_date, cust_code and amount. This table can be partitioned by range in various of ways, depending on your requirement. Here we have used the bill_date column and decide to partition the table 4 ways by adding a PARTITION BY RANGE clause. In these partitions the range of the sale date (sale_date) are as of follow :

    • partition p0 ( sale between 01-01-2013 to 31-03-2013)
    • partition p1 ( sale between 01-04-2013 to 30-06-2013)
    • partition p2 ( sale between 01-07-2013 to 30-09-2013)
    • partition p3 ( sale between 01-10-2013 to 30-12-2013)

    Let create the table :mysql> CREATE TABLE sale_mast (bill_no INT NOT NULL, bill_date TIMESTAMP NOT NULL, cust_code VARCHAR(15) NOT NULL, amount DECIMAL(8,2) NOT NULL) PARTITION BY RANGE (UNIX_TIMESTAMP(bill_date))( PARTITION p0 VALUES LESS THAN (UNIX_TIMESTAMP(‘2013-04-01’)), PARTITION p1 VALUES LESS THAN (UNIX_TIMESTAMP(‘2013-07-01’)), PARTITION p2 VALUES LESS THAN (UNIX_TIMESTAMP(‘2013-10-01’)), PARTITION p3 VALUES LESS THAN (UNIX_TIMESTAMP(‘2014-01-01’))); Query OK, 0 rows affected (1.50 sec)

    Now insert some records in sale_mast table :mysql> INSERT INTO sale_mast VALUES (1, ‘2013-01-02’, ‘C001’, 125.56), (2, ‘2013-01-25’, ‘C003’, 456.50), (3, ‘2013-02-15’, ‘C012’, 365.00), (4, ‘2013-03-26’, ‘C345’, 785.00), (5, ‘2013-04-19’, ‘C234’, 656.00), (6, ‘2013-05-31’, ‘C743’, 854.00), (7, ‘2013-06-11’, ‘C234’, 542.00), (8, ‘2013-07-24’, ‘C003’, 300.00), (8, ‘2013-08-02’, ‘C456’, 475.20); Query OK, 9 rows affected (0.07 sec) Records: 9 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM sale_mast; +———+———————+———–+——–+ | bill_no | bill_date | cust_code | amount | +———+———————+———–+——–+ | 1 | 2013-01-02 00:00:00 | C001 | 125.56 | | 2 | 2013-01-25 00:00:00 | C003 | 456.50 | | 3 | 2013-02-15 00:00:00 | C012 | 365.00 | | 4 | 2013-03-26 00:00:00 | C345 | 785.00 | | 5 | 2013-04-19 00:00:00 | C234 | 656.00 | | 6 | 2013-05-31 00:00:00 | C743 | 854.00 | | 7 | 2013-06-11 00:00:00 | C234 | 542.00 | | 8 | 2013-07-24 00:00:00 | C003 | 300.00 | | 9 | 2013-08-02 00:00:00 | C456 | 475.20 | +———+———————+———–+——–+ 9 rows in set (0.00 sec)

    Here is the partition status of sale_mast table:mysql> SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME=’sale_mast’; +—————-+————+ | PARTITION_NAME | TABLE_ROWS | +—————-+————+ | p0 | 4 | | p1 | 3 | | p2 | 2 | | p3 | 0 | +—————-+————+ 4 rows in set (0.02 sec)

    In the above way you can partition the table based on sale amount (amount. In these partitions the range of the sale amount (amount) are as of follow :

    • partition p0 ( sale amount < 100 )
    • partition p1 ( sale amount < 500 )
    • partition p2 ( sale amount <1000 )
    • partition p3 ( sale amount<1500 )

    Let create the table :mysql> CREATE TABLE sale_mast1 (bill_no INT NOT NULL, bill_date TIMESTAMP NOT NULL, cust_codE VARCHAR(15) NOT NULL, amount INT NOT NULL) PARTITION BY RANGE (amount) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (500), PARTITION p2 VALUES LESS THAN (1000), PARTITION p3 VALUES LESS THAN (1500)); Query OK, 0 rows affected (1.34 sec)

    Drop a MySQL partition

    If you feel some data are useless in a partitioned table you can drop one or more partition(s). To delete all rows from partition p0 of sale_mast, you can use the following statement :MySQL> ALTER TABLE sale_mast TRUNCATE PARTITION p0; Query OK, 0 rows affected (0.49 sec) mysql> SELECT * FROM sale_mast; +———+———————+———–+——–+ | bill_no | bill_date | cust_code | amount | +———+———————+———–+——–+ | 5 | 2013-04-19 00:00:00 | C234 | 656.00 | | 6 | 2013-05-31 00:00:00 | C743 | 854.00 | | 7 | 2013-06-11 00:00:00 | C234 | 542.00 | | 8 | 2013-07-24 00:00:00 | C003 | 300.00 | | 9 | 2013-08-02 00:00:00 | C456 | 475.20 | +———+———————+———–+——–+ 5 rows in set (0.01 sec)

    Here is the partition status of sale_mast after dropping the partition p0 :MySQL> SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME=’sale_mast’; +—————-+————+ | PARTITION_NAME | TABLE_ROWS | +—————-+————+ | p0 | 0 | | p1 | 3 | | p2 | 2 | | p3 | 0 | +—————-+————+ 4 rows in set (0.05 sec)

    MySQL LIST Partitioning

    List partition allows us to segment data based on a pre-defined set of values (e.g. 1, 2, 3). This is done by using PARTITION BY LIST(expr) where expr is a column value and then defining each partition by means of a VALUES IN (value_list), where value_list is a comma-separated list of integers. In MySQL 5.6, it is possible to match against only a list of integers (and possibly NULL) when partitioning by LIST. In the following example, sale_mast2 table contains four columns bill_no, bill_date, agent_code, and amount. Suppose there are 11 agents represent three cities A, B, C these can be arranged in three partitions with LIST Partitioning as follows :

    CityAgent ID
    A1, 2, 3
    B4, 5, 6
    C7, 8, 9, 10, 11

    Let create the table :mysql> CREATE TABLE sale_mast2 (bill_no INT NOT NULL, bill_date TIMESTAMP NOT NULL, agent_codE INT NOT NULL, amount INT NOT NULL) PARTITION BY LIST(agent_code) ( PARTITION pA VALUES IN (1,2,3), PARTITION pB VALUES IN (4,5,6), PARTITION pC VALUES IN (7,8,9,10,11)); Query OK, 0 rows affected (1.17 sec)

    MySQL COLUMNS Partitioning

    In COLUMNS partitioning it is possible to use multiple columns in partitioning keys. There are two types of COLUMNS partitioning :

    In addition, both RANGE COLUMNS partitioning and LIST COLUMNS partitioning support the use of non-integer columns for defining value ranges or list members. The permitted data types are shown in the following list:

    Both RANGE COLUMNS partitioning and LIST COLUMNS partitioning support following data types for defining value ranges or list members.

    • All integer types: TINYINT, SMALLINT, MEDIUMINT, INT (INTEGER), and BIGINT.
    • DATE and DATETIME.

    RANGE COLUMNS partitioning

    RANGE COLUMNS partitioning is similar to range partitioning with some significant difference. RANGE COLUMNS accepts a list of one or more columns as partition keys. You can define the ranges using various columns of types (mentioned above) other than integer types.

    https://www.adsensecustomsearchads.com/afs/ads?psid=5134551505&channel=AutoRsVariant&cx=r-440389826592af9d2&fexp=21404%2C17301371%2C17301372%2C17301383%2C71847096&client=pub-2153208817642134&r=m&sct=ID%3Df1c5d672aa31266c%3AT%3D1706354011%3ART%3D1706354011%3AS%3DALNI_MZlJMMg_q5l3r_1tPiuFzhttpHLOQ&sc_status=6&hl=en&rpbu=http%3A%2F%2Fgoogle.com&rpqp=q&type=3&rs_tt=c&oe=UTF-8&ie=UTF-8&format=r5&nocache=3231706465149559&num=0&output=afd_ads&domain_name=www.w3resource.com&v=3&bsl=10&pac=0&u_his=7&u_tz=-480&dt=1706465149562&u_w=1366&u_h=768&biw=933&bih=448&psw=933&psh=448&frm=0&cl=600476684&uio=-&cont=autors-container-0&drt=0&jsid=csa&jsv=600476684&rurl=https%3A%2F%2Fwww.w3resource.com%2Fmysql%2Fmysql-partition.php&referer=https%3A%2F%2Fwww.w3resource.com%2Fmysql%2Faltering-table%2Faltering-table.php

    Here is the basic syntax for creating a table partitioned by RANGE COLUMNS :CREATE TABLE table_name PARTITIONED BY RANGE COLUMNS(column_list) ( PARTITION partition_name VALUES LESS THAN (value_list)[, PARTITION partition_name VALUES LESS THAN (value_list)][, …] ) column_list: column_name[, column_name][, …] value_list: value[, value][, …]

    • column_list is a list of one or more columns.
    • value_list is a list of values and must be supplied for each partition definition.
    • column list and in the value list defining each partition must occur in the same order
    • The order of the column names in the partitioning column list and the value lists do not have to be the same as the order of the table column definitions in CREATE TABLE statement.

    Here is an example :mysql> CREATE TABLE table3 (col1 INT, col2 INT, col3 CHAR(5), col4 INT) PARTITION BY RANGE COLUMNS(col1, col2, col3) (PARTITION p0 VALUES LESS THAN (50, 100, ‘aaaaa’), PARTITION p1 VALUES LESS THAN (100,200,’bbbbb’), PARTITION p2 VALUES LESS THAN (150,300,’ccccc’), PARTITION p3 VALUES LESS THAN (MAXVALUE, MAXVALUE, MAXVALUE)); Query OK, 0 rows affected (1.39 sec)

    In the above example –

    • Table table3 contains the columns col1, col2, col3, col4
    • The first three columns have participated in partitioning COLUMNS clause, in the order col1, col2, col3.
    • Each value list used to define a partition contains 3 values in the same order and (INT, INT, CHAR(5)) form.

    LIST COLUMNS partitioning

    LIST COLUMNS accepts a list of one or more columns as partition keys.You can use various columns of data of types other than integer types as partitioning columns. You can use string types, DATE, and DATETIME columns

    In a company there are agents in 3 cities, for sales and marketing purposes. We have organized the agents in 3 cities as shown in the following table :

    CityAgent ID
    AA1, A2, A3
    BB1, B2, B3
    CC1, C2, C3, C4, C5

    Let create a table with LIST COLUMNS partitioning based on the above information :mysql> CREATE TABLE salemast ( agent_id VARCHAR(15), agent_name VARCHAR(50), agent_address VARCHAR(100), city_code VARCHAR(10)) PARTITION BY LIST COLUMNS(agent_id) ( PARTITION pcity_a VALUES IN(‘A1’, ‘A2’, ‘A3’), PARTITION pcity_b VALUES IN(‘B1’, ‘B2’, ‘B3’), PARTITION pcity_c VALUES IN (‘C1’, ‘C2’, ‘C3’, ‘C4’, ‘C5’)); Query OK, 0 rows affected (1.06 sec)

    You can use DATE and DATETIME columns in LIST COLUMNS partitioning, see the following example :CREATE TABLE sale_master (bill_no INT NOT NULL, bill_date DATE, cust_code VARCHAR(15) NOT NULL, amount DECIMAL(8,2) NOT NULL) PARTITION BY RANGE COLUMNS (bill_date)( PARTITION p_qtr1 VALUES LESS THAN (‘2013-04-01’), PARTITION p_qtr2 VALUES LESS THAN (‘2013-07-01’), PARTITION p_qtr3 VALUES LESS THAN (‘2013-10-01’), PARTITION p_qtr4 VALUES LESS THAN (‘2014-01-01’));

    MySQL HASH Partitioning

    MySQL HASH partition is used to distribute data among a predefined number of partitions on a column value or expression based on a column value. This is done by using PARTITION BY HASH(expr) clause, adding in CREATE TABLE STATEMENT. In PARTITIONS num clause, num is a positive integer represents the number of partitions of the table. The following statement creates a table that uses hashing on the studetn_id column and is divided into 4 partitions :

    MySQL>CREATE TABLE student (student_id INT NOT NULL, 
    class VARCHAR(8), name VARCHAR(40),
    date_of_admission DATE NOT NULL DEFAULT '2000-01-01') 
    PARTITION BY HASH(student_id) 
    PARTITIONS 4;
    Query OK, 0 rows affected (1.43 sec)
    

    Copy

    It is also possible to make a partition based on the year in which a student was admitted. See the following statement :

    MySQL> CREATE TABLE student (student_id INT NOT NULL, 
    class VARCHAR(8), class VARCHAR(8), name VARCHAR(40),
    date_of_admission DATE NOT NULL DEFAULT '2000-01-01') 
    PARTITION BY HASH(YEAR(date_of_admission)) 
    PARTITIONS 4;
    Query OK, 0 rows affected (1.27 sec)
    

    Copy

    MySQL KEY Partitioning

    MySQL KEY partition is a special form of HASH partition, where the hashing function for key partitioning is supplied by the MySQL server. The server employs its own internal hashing function which is based on the same algorithm as PASSWORD(). This is done by using PARTITION BY KEY, adding in CREATE TABLE STATEMENT. In KEY partitioning KEY takes only a list of zero or more column names. Any columns used as the partitioning key must comprise part or all of the table’s primary key if the table has one. If there is a primary key in a table, it is used as partitioning key when no column is specified as the partitioning key. Here is an example :MySQL> CREATE TABLE table1 ( id INT NOT NULL PRIMARY KEY, fname VARCHAR(25), lname VARCHAR(25)) PARTITION BY KEY() PARTITIONS 2; Query OK, 0 rows affected (0.84 sec)

    If there is no primary key but there is a unique key in a table, then the unique key is used for the partitioning key :MySQL> CREATE TABLE table2 ( id INT NOT NULL, fname VARCHAR(25), lname VARCHAR(25), UNIQUE KEY (id)) PARTITION BY KEY() PARTITIONS 2; Query OK, 0 rows affected (0.77 sec)

    MySQL Subpartitioning

    Subpartitioning is a method to divide each partition further in a partitioned table. See the following CREATE TABLE statement :

    CREATE TABLE table10 (BILL_NO INT, sale_date DATE, cust_code VARCHAR(15), 
    AMOUNT DECIMAL(8,2))
    PARTITION BY RANGE(YEAR(sale_date) )
    SUBPARTITION BY HASH(TO_DAYS(sale_date))
    SUBPARTITIONS 4 (
    PARTITION p0 VALUES LESS THAN (1990),
    PARTITION p1 VALUES LESS THAN (2000),
    PARTITION p2 VALUES LESS THAN (2010),
    PARTITION p3 VALUES LESS THAN MAXVALUE
    );
    

    Copy

    In the above statement –

    • The table has 4 RANGE partitions.
    • Each of these partitions—p0, p1, p2 and p3—is further divided into 4 subpartitions.
    • Therefore the entire table is divided into 4 * 4 = 16 partitions.

    Here is the partition status of table10 :mysql> SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME=’stable’; +—————-+————+ | PARTITION_NAME | TABLE_ROWS | +—————-+————+ | p0 | 0 | | p0 | 0 | | p0 | 0 | | p0 | 0 | | p1 | 0 | | p1 | 0 | | p1 | 0 | | p1 | 0 | | p2 | 0 | | p2 | 0 | | p2 | 0 | | p2 | 0 | | p3 | 0 | | p3 | 0 | | p3 | 0 | | p3 | 0 | +—————-+————+ 16 rows in set (0.16 sec)

  • MySQL INSERT statement

    INSERT statement

    MySQL INSERT statement is used to insert record(s) or row(s) into a table. The insertion of records or rows in the table can be done in two ways, insert a single row at a time, and insert multiple rows at a time.

    Version: MySQL 5.6

    Syntax:INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] [(col_name,…)] {VALUES | VALUE} ({expr | DEFAULT},…),(…),… [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] … ]

    or:INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] SET col_name={expr | DEFAULT}, … [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] … ]

    or:INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] [(col_name,…)] SELECT … [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] … ]

    Arguments:

    NameDescriptions
    INSERTInserts new rows into an existing table.
    LOW_PRIORITYUsing the LOW_PRIORITY keyword, execution of the INSERT is delayed until no other clients are reading from the table. This includes other clients that began reading while existing clients are reading. Therefore it is possible, for a client that issues an INSERT LOW_PRIORITY statement to wait for a very long time (or even forever) in a read-heavy environment.
    DELAYEDUsing DELAYED keyword, the server puts the row or rows to be inserted into a buffer, and the INSERT DELAYED statement (issued by the client) can then continue immediately. The server holds the rows if the table is in use. The server begins inserting rows, when the table is free, checking periodically to see whether there are any new read requests for the table. If there are any new read requests, the delayed row queue is suspended until the table becomes free again.
    HIGH_PRIORITYUsing HIGH_PRIORITY, it overrides the effect of the –low-priority-updates option if the server was started with that option. It also causes concurrent inserts not to be used.
    LOW_PRIORITY and HIGH_PRIORITY affect only storage engines that use only table-level locking such as MyISAM, MEMORY, and MERGE.
    IGNOREUsing the IGNORE keyword, errors that occur while executing the INSERT statement are ignored.
    INTOInserts new rows into an existing table.
    tbl_nameName of the table where rows will be inserted.
    PARTITIONIn MySQL 5.6.2 and later, you can control which partitions and subpartitions accept new rows when inserting into a partitioned table. The PARTITION option takes a comma-separated list of the names of one or more partitions or subpartitions (or both) of the table. If any of the rows which are ready to insert, by a given INSERT statement do not match one of the partitions listed, the INSERT statement fails with the error Found a row not matching the given partition set.
    partition_nameName of the partitioned table(s).
    col_nameA comma-separated list of column names.You can specify a comma-separated list of column names following the table name and a value for each named column must be provided by the VALUES list or the SELECT statement.If you do not specify the column names for INSERT … VALUES or INSERT … SELECT, values for every column in the table must be provided by the VALUES list (same as order of the columns in the table) or the SELECT statement.The SET clause indicates the column names explicitly.
    VALUES | VALUEIf strict SQL mode is off, any column not explicitly given a value is set to its default (explicit or implicit) value. For example, if you specify a column list that does not name all the columns in the table, unnamed columns are set to their default values.The keyword DEFAULT is used to set a column explicitly to its default value.If both the column list and the VALUES list are empty, INSERT creates a row with each column set to its default value.You can specify an expression expr to provide a column value. This might involve type conversion if the type of the expression does not match the type of the column, and conversion of a given value can result in different inserted values depending on the data type. For example, inserting the string ‘1998.0e-2’ into an INT, FLOAT, DECIMAL(10,6), or YEAR column results in the values 1998, 19.9821, 19.982100, and 1998 being inserted, respectively.

    INSERT … SELECT

    To insert many rows quickly into a table from one or many tables you can use INSERT … SELECT statement. Here is the syntax :

    Syntax:INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [PARTITION (partition_name,…)] [(col_name,…)] SELECT … [ ON DUPLICATE KEY UPDATE col_name=expr, … ]

    The following conditions hold for a INSERT … SELECT statements :

    • Using the IGNORE keyword, ignore rows that would cause duplicate-key violations.
    • The keyword DELAYED is ignored with INSERT … SELECT.
    • The target table of the INSERT statement may appear in the FROM clause of the SELECT part of the query.
    • AUTO_INCREMENT columns work as usual.
    • To avoid ambiguous column reference problems when the SELECT and the INSERT refer to the same table.
    • In MySQL 5.6.2 and later, you can control which partitions and subpartitions accept new rows when inserting into a partitioned table.

    Example:INSERT INTO tb2 (fld_id) SELECT tbl.fld_order_id FROM tbl WHERE tbl.fld_order_id > 200;

    INSERT DELAYED

    The DELAYED option for the INSERT statement is a MySQL extension to standard SQL that can be used for certain kinds of tables (such as MyISAM). When a client uses INSERT DELAYED, it gets an okay from the server at once, and the row is queued to be inserted when the table is not in use by any other thread.

    Syntax:INSERT DELAYED …

    INSERT … ON DUPLICATE KEY UPDATE

    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs a UPDATE of the old row. For example, if column x is declared as UNIQUE and contains the value 1, the following two statements have similar effect:INSERT INTO table (x,y,z) VALUES (1,2,3) ON DUPLICATE KEY UPDATE z=z+1; UPDATE table SET z=z+1 WHERE x=1;

    Note: The effects are not identical for an InnoDB table where a is an auto-increment column. With an auto-increment column, an INSERT statement increases the auto-increment value but UPDATE does not.

    Examples:

    MySQL INSERT INTO statement is used to insert record(s) or row(s) into a table.

    Syntax:INSERT INTO table_name ([column_name],[…column_name],…) VALUES( [column_value],[..column_value]);

    Example with PHP code to insert data into a MySQL table

    HTML code (say form.html):

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>form to insert data</title>
    </head>
    <body>
    <form method="post" action="insert.php">
    <input type="text" name="name" />
    <input type="text" name="email" />
    <input type="text" name="address" />
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    

    Copy

    PHP code (say insert.php):

    <?php
    $host="localhost"; //yout host name
    $username="root";  //yout user name
    $password="";      // your password
    $db_name="test";  // your database name
    $con=MySQL_connect("$host", "$username", "$password")or die("cannot connect"); //MySQL connection
    MySQL_select_db("$db_name")or die("can not select DB"); //select your database
    $name = $_POST['name'];
    $email = $_POST['email'];
    $address = $_POST['address'];
    $query = "INSERT INTO test (name,email,address) VALUES ('$name', '$email', '$address')";
    MySQL_query($query) or die('Query "' . $query . '" failed: ' . MySQL_error());
    // name, email and address are fields of your fields; test your table. $name, $email and $address are values collected from the form
    ?>
    

    Copy

    MySQL: INSERT one row in a table

    The following statement inserts a single row into a table using MySQL INSERT INTO statement.

    Code:

    INSERT INTO newcate 
    VALUES ("CA006","Sports");
    

    Copy

    The above statement will insert one row in the table ‘newcate’. We have not mentioned any column name here. That is why all of the columns will be affected.mysql> select * from newcate; +———+————–+ | cate_id | cate_descrip | +———+————–+ | CA001 | Science | | CA002 | Technology | | CA003 | Computers | | CA004 | Nature | | CA005 | Medical | | CA006 | Sports | +———+————–+ 6 rows in set (0.00 sec)

    MySQL: INSERT values for specific columns

    The following statement inserts values for specific columns using MySQL INSERT INTO statement.

    Sample table: newpurchase

    Code:

    INSERT INTO newpurchase  (invoice_no,ord_no,book_name)
    VALUES  ("INV001","ORD006",”An advance book of Computer”);
    

    Copy

    The above statement will insert one(1) row in the table ‘newpurchase’ for the columns ‘invoice_no’, ‘ord_no’, and ‘book_name’.

    MySQL: INSERT NULL values

    The following statement inserts NULL values into one or more columns using MySQL INSERT INTO statement.

    Sample table: newpurchase

    Code:

    INSERT INTO newpurchase (invoice_no,ord_no,book_name) 
    VALUES ("INV002","ORD007",NULL);
    

    Copy

    The above statement will insert one(1) row in the table ‘newpurchase’. Columns ‘invoice_no’, ‘ord_no’, and ‘book_name’ got populated with values where as column ‘book_name’ got populated with the NULL value.

    Inserting multiple rows in a single SQL query

    In MySQL, you can insert multiple rows in a single SQL query. Here is the syntax:INSERT INTO Table ( Column1, Column2 ) VALUES ( Value1, Value2 ), ( Value1, Value2 );

    MySQL INSERT rows with SELECT statement

    The following statement inserts values into a table using MySQL INSERT INTO statement when the column names and values are collected from another identical table using MySQL SELECT statement. This way you can insert values of one table into another when tables are identical.

    Sample table : purchase

    Code:

    INSERT INTO testpurchase 
    SELECT * 
    FROM purchase;
    

    Copy

    MySQL INSERT rows with SELECT statement and WHERE

    The following statement inserts values into a table using MySQL INSERT INTO statement when the column names and values are collected from another identical table using MySQL SELECT and WHERE. This way you can insert values based upon some conditions of one table into another when tables are identical.

    Sample table: purchase

    Code:

    INSERT INTO testpurchase 
    SELECT * 
    FROM purchase 
    WHERE YEAR(invoice_dt)='2008';
    

    Copy

    The above statement performs the following operations –

  • MySQL Partitioning


    What is Partitioning?

    Partitioning (a database design technique) improves performance, manageability, simplifies maintenance and reduce the cost of storing large amounts of data. Partitioning can be achieved without splitting tables by physically putting tables on individual disk drives. Partitioning allows tables, indexes, and index-organized tables to be subdivided into smaller pieces, therefore queries that access only a fraction of the data can run faster because there is fewer data to scan. There are two major forms of partitioning :

    • Horizontal Partitioning : Horizontal partitioning divides table rows into multiple partitions (based on a logic). All columns defined to a table are found in each partition, so no actual table attributes are missing. All the partition can be addressed individually or collectively. For example, a table that contains whole year sale transaction being partitioned horizontally into twelve distinct partitions, where each partition contains one month’s data.
    • Vertical Partitioning : Vertical partitioning divides a table into multiple tables that contain fewer columns. Like horizontal partitioning, in vertical partitioning a query scan fewer data which increases query performance. For example, a table that contains a number of very wide text or BLOB columns that aren’t addressed often being broken into two tables that have the most referenced columns in one table and the text or BLOB data in another.

    MySQL partitioning

    Version: MySQL 5.6

    MySQL supports basic table partitioning but does not support vertical partitioning ( MySQL 5.6). This section describes in detail how to implement partitioning as part of your database.

    By checking the output of the SHOW PLUGINS statement you will be sure whether your MySQL server supports the partition or not. See the following output :

    Sample Output:mysql> SHOW PLUGINS; +—————————-+———-+——————–+———+———+ | Name | Status | Type | Library | License | +—————————-+———-+——————–+———+———+ | binlog | ACTIVE | STORAGE ENGINE | NULL | GPL | | MySQL_native_password | ACTIVE | AUTHENTICATION | NULL | GPL | | MySQL_old_password | ACTIVE | AUTHENTICATION | NULL | GPL | | sha256_password | ACTIVE | AUTHENTICATION | NULL | GPL | | CSV | ACTIVE | STORAGE ENGINE | NULL | GPL | | MEMORY | ACTIVE | STORAGE ENGINE | NULL | GPL | | MyISAM | ACTIVE | STORAGE ENGINE | NULL | GPL | | MRG_MYISAM | ACTIVE | STORAGE ENGINE | NULL | GPL | | ARCHIVE | ACTIVE | STORAGE ENGINE | NULL | GPL | | BLACKHOLE | ACTIVE | STORAGE ENGINE | NULL | GPL | | FEDERATED | DISABLED | STORAGE ENGINE | NULL | GPL | | InnoDB | ACTIVE | STORAGE ENGINE | NULL | GPL | | INNODB_TRX | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | INNODB_LOCKS | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | INNODB_CMPMEM | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | —————————| —— | —————— | —- | — | | —————————| —— | —————— | —- | — | | —————————| —— | —————— | —- | — | | INNODB_SYS_TABLESPACES | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | INNODB_SYS_DATAFILES | ACTIVE | INFORMATION SCHEMA | NULL | GPL | | PERFORMANCE_SCHEMA | ACTIVE | STORAGE ENGINE | NULL | GPL | | partition | ACTIVE | STORAGE ENGINE | NULL | GPL | +—————————-+———-+——————–+———+———+ 42 rows in set (0.21 sec)

    MySQL 5.6 Community binaries include partitioning support.

    Enable and disable partitioning support :

    • To enable partitioning (if you are compiling MySQL 5.6 from source), the build must be configured with the -DWITH_PARTITION_STORAGE_ENGINE option.
    • To disable partitioning support, you can start the MySQL Server with the –skip-partition option, in which case the value of have_partitioning is DISABLED.

    How to partition a table?

    In MySQL you can partition a table using CREATE TABLE or ALTER TABLE command. See the following CREATE TABLE syntax :CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,…)

    [table_options]

    [partition_options]

    partition_options:PARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY(column_list) | RANGE(expr) | LIST(expr) } [PARTITIONS num] [SUBPARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY(column_list) } [SUBPARTITIONS num] ] [(partition_definition[, partition_definition] …)

    partition_definition:PARTITION partition_name [VALUES {LESS THAN {(expr) | MAXVALUE} | IN (value_list)}] [[STORAGE] ENGINE [=] engine_name] [COMMENT [=] ‘comment_text’ ] [DATA DIRECTORY [=] ‘data_dir’] [INDEX DIRECTORY [=] ‘index_dir’] [MAX_ROWS [=] max_number_of_rows] [MIN_ROWS [=] min_number_of_rows] [TABLESPACE [=] tablespace_name] [NODEGROUP [=] node_group_id] [(subpartition_definition [, subpartition_definition] …)]

    subpartition_definition:SUBPARTITION logical_name [[STORAGE] ENGINE [=] engine_name] [COMMENT [=] ‘comment_text’ ] [DATA DIRECTORY [=] ‘data_dir’] [INDEX DIRECTORY [=] ‘index_dir’] [MAX_ROWS [=] max_number_of_rows] [MIN_ROWS [=] min_number_of_rows] [TABLESPACE [=] tablespace_name] [NODEGROUP [=] node_group_id]

    ALTER TABLE: Partition operations

    ALTER TABLE statement can be used for adding, dropping, merging, and splitting partitions, and for performing partitioning maintenance. Here we have defined a nonpartitioned table:

    CREATE TABLE sale_mast (
    bill_no INT,
    bill_date DATETIME
    );
    

    Copy

    This table can be partitioned by HASH (or in another type), using the bill_no column as the partitioning key, into 6 (or other) partitions using ALTER TABLE statement :

    ALTER TABLE t1
    
    PARTITION BY HASH(id)
    PARTITIONS 6;

    Copy

    Partition naming :

    Names of partitions follow the rules of other MySQL identifiers such as databases, tables, constraint, stored procedure etc. Partition names are not case-sensitive.

    Advantages of partitioning

    • During the scan operation, MySQL optimizer accesses those partitions that will satisfy a particular query. For example, a whole year sale records table may be broken up into 4 partitions (i.e. sale data from of Apr-Jun (partition p0), Jul-Sep (partition p1) , Oct-Dec (partition p2), Jam-Mar (partition p0)) . If a query is issued that contains sale data between Jul-Sep quarter, then it scans the partition p1 only instead of total table records and the query will complete much sooner.
    • Partitioning allows you to have more control over how data is managed inside the database. For example, you can drop specific partitions in a partitioned table where data loses its usefulness. The process of adding new data, in some cases, be greatly facilitated by adding one or more new partitions for storing that data using ALTER TABLE command.
    • In partitioning, it is possible to store more data in one table than can be held on a single disk or file system partition.
    • MySQL 5.6 supports explicit partition selection for queries. For example, SELECT * FROM table1 PARTITION (p0,p1) WHERE col1< 10 selects only those rows in partitions p0 and p1 that match the WHERE condition, this can greatly speed up queries
    • Partition selection also supports the data modification statements DELETE, INSERT, REPLACE, UPDATE, and LOAD DATA, LOAD XML.

    Types of MySQL partitioning

    Following types of partitioning are available in MySQL 5.6 :

    • RANGE Partitioning
    • LIST Partitioning
    • COLUMNS Partitioning
    • HASH Partitioning
    • KEY Partitioning
    • Subpartitioning

    MySQL RANGE Partitioning

    In MySQL, RANGE partitioning mode allows us to specify various ranges for which data is assigned. Ranges should be contiguous but not overlapping, and are defined using the VALUES LESS THAN operator. In the following example, sale_mast table contains four columns bill_no, bill_date, cust_code and amount. This table can be partitioned by range in various of ways, depending on your requirement. Here we have used the bill_date column and decide to partition the table 4 ways by adding a PARTITION BY RANGE clause. In these partitions the range of the sale date (sale_date) are as of follow :

    • partition p0 ( sale between 01-01-2013 to 31-03-2013)
    • partition p1 ( sale between 01-04-2013 to 30-06-2013)
    • partition p2 ( sale between 01-07-2013 to 30-09-2013)
    • partition p3 ( sale between 01-10-2013 to 30-12-2013)

    Let create the table :mysql> CREATE TABLE sale_mast (bill_no INT NOT NULL, bill_date TIMESTAMP NOT NULL, cust_code VARCHAR(15) NOT NULL, amount DECIMAL(8,2) NOT NULL) PARTITION BY RANGE (UNIX_TIMESTAMP(bill_date))( PARTITION p0 VALUES LESS THAN (UNIX_TIMESTAMP(‘2013-04-01’)), PARTITION p1 VALUES LESS THAN (UNIX_TIMESTAMP(‘2013-07-01’)), PARTITION p2 VALUES LESS THAN (UNIX_TIMESTAMP(‘2013-10-01’)), PARTITION p3 VALUES LESS THAN (UNIX_TIMESTAMP(‘2014-01-01’))); Query OK, 0 rows affected (1.50 sec)

    Now insert some records in sale_mast table :mysql> INSERT INTO sale_mast VALUES (1, ‘2013-01-02’, ‘C001’, 125.56), (2, ‘2013-01-25’, ‘C003’, 456.50), (3, ‘2013-02-15’, ‘C012’, 365.00), (4, ‘2013-03-26’, ‘C345’, 785.00), (5, ‘2013-04-19’, ‘C234’, 656.00), (6, ‘2013-05-31’, ‘C743’, 854.00), (7, ‘2013-06-11’, ‘C234’, 542.00), (8, ‘2013-07-24’, ‘C003’, 300.00), (8, ‘2013-08-02’, ‘C456’, 475.20); Query OK, 9 rows affected (0.07 sec) Records: 9 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM sale_mast; +———+———————+———–+——–+ | bill_no | bill_date | cust_code | amount | +———+———————+———–+——–+ | 1 | 2013-01-02 00:00:00 | C001 | 125.56 | | 2 | 2013-01-25 00:00:00 | C003 | 456.50 | | 3 | 2013-02-15 00:00:00 | C012 | 365.00 | | 4 | 2013-03-26 00:00:00 | C345 | 785.00 | | 5 | 2013-04-19 00:00:00 | C234 | 656.00 | | 6 | 2013-05-31 00:00:00 | C743 | 854.00 | | 7 | 2013-06-11 00:00:00 | C234 | 542.00 | | 8 | 2013-07-24 00:00:00 | C003 | 300.00 | | 9 | 2013-08-02 00:00:00 | C456 | 475.20 | +———+———————+———–+——–+ 9 rows in set (0.00 sec)

    Here is the partition status of sale_mast table:mysql> SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME=’sale_mast’; +—————-+————+ | PARTITION_NAME | TABLE_ROWS | +—————-+————+ | p0 | 4 | | p1 | 3 | | p2 | 2 | | p3 | 0 | +—————-+————+ 4 rows in set (0.02 sec)

    In the above way you can partition the table based on sale amount (amount. In these partitions the range of the sale amount (amount) are as of follow :

    • partition p0 ( sale amount < 100 )
    • partition p1 ( sale amount < 500 )
    • partition p2 ( sale amount <1000 )
    • partition p3 ( sale amount<1500 )

    Let create the table :mysql> CREATE TABLE sale_mast1 (bill_no INT NOT NULL, bill_date TIMESTAMP NOT NULL, cust_codE VARCHAR(15) NOT NULL, amount INT NOT NULL) PARTITION BY RANGE (amount) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (500), PARTITION p2 VALUES LESS THAN (1000), PARTITION p3 VALUES LESS THAN (1500)); Query OK, 0 rows affected (1.34 sec)

    Drop a MySQL partition

    If you feel some data are useless in a partitioned table you can drop one or more partition(s). To delete all rows from partition p0 of sale_mast, you can use the following statement :MySQL> ALTER TABLE sale_mast TRUNCATE PARTITION p0; Query OK, 0 rows affected (0.49 sec) mysql> SELECT * FROM sale_mast; +———+———————+———–+——–+ | bill_no | bill_date | cust_code | amount | +———+———————+———–+——–+ | 5 | 2013-04-19 00:00:00 | C234 | 656.00 | | 6 | 2013-05-31 00:00:00 | C743 | 854.00 | | 7 | 2013-06-11 00:00:00 | C234 | 542.00 | | 8 | 2013-07-24 00:00:00 | C003 | 300.00 | | 9 | 2013-08-02 00:00:00 | C456 | 475.20 | +———+———————+———–+——–+ 5 rows in set (0.01 sec)

    Here is the partition status of sale_mast after dropping the partition p0 :MySQL> SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME=’sale_mast’; +—————-+————+ | PARTITION_NAME | TABLE_ROWS | +—————-+————+ | p0 | 0 | | p1 | 3 | | p2 | 2 | | p3 | 0 | +—————-+————+ 4 rows in set (0.05 sec)

    MySQL LIST Partitioning

    List partition allows us to segment data based on a pre-defined set of values (e.g. 1, 2, 3). This is done by using PARTITION BY LIST(expr) where expr is a column value and then defining each partition by means of a VALUES IN (value_list), where value_list is a comma-separated list of integers. In MySQL 5.6, it is possible to match against only a list of integers (and possibly NULL) when partitioning by LIST. In the following example, sale_mast2 table contains four columns bill_no, bill_date, agent_code, and amount. Suppose there are 11 agents represent three cities A, B, C these can be arranged in three partitions with LIST Partitioning as follows :

    CityAgent ID
    A1, 2, 3
    B4, 5, 6
    C7, 8, 9, 10, 11

    Let create the table :mysql> CREATE TABLE sale_mast2 (bill_no INT NOT NULL, bill_date TIMESTAMP NOT NULL, agent_codE INT NOT NULL, amount INT NOT NULL) PARTITION BY LIST(agent_code) ( PARTITION pA VALUES IN (1,2,3), PARTITION pB VALUES IN (4,5,6), PARTITION pC VALUES IN (7,8,9,10,11)); Query OK, 0 rows affected (1.17 sec)

    MySQL COLUMNS Partitioning

    In COLUMNS partitioning it is possible to use multiple columns in partitioning keys. There are two types of COLUMNS partitioning :

    • RANGE COLUMNS partitioning
    • LIST COLUMNS partitioning

    In addition, both RANGE COLUMNS partitioning and LIST COLUMNS partitioning support the use of non-integer columns for defining value ranges or list members. The permitted data types are shown in the following list:

    Both RANGE COLUMNS partitioning and LIST COLUMNS partitioning support following data types for defining value ranges or list members.

    • All integer types: TINYINT, SMALLINT, MEDIUMINT, INT (INTEGER), and BIGINT.
    • DATE and DATETIME.

    RANGE COLUMNS partitioning

    RANGE COLUMNS partitioning is similar to range partitioning with some significant difference. RANGE COLUMNS accepts a list of one or more columns as partition keys. You can define the ranges using various columns of types (mentioned above) other than integer types.

    https://www.adsensecustomsearchads.com/afs/ads?psid=5134551505&channel=AutoRsVariant&cx=r-440389826592af9d2&fexp=44759875%2C44759926%2C44759837%2C44795921%2C31080696%2C95320378%2C95320888%2C95321627%2C95322163%2C95323009%2C0%2C21404%2C17301374%2C17301375%2C17301383%2C71847096&client=pub-2153208817642134&r=m&sct=ID%3Df1c5d672aa31266c%3AT%3D1706354011%3ART%3D1706354011%3AS%3DALNI_MZlJMMg_q5l3r_1tPiuFzhttpHLOQ&sc_status=6&hl=en&rpbu=http%3A%2F%2Fgoogle.com&rpqp=q&type=3&rs_tt=c&oe=UTF-8&ie=UTF-8&format=r5&nocache=3161706402653327&num=0&output=afd_ads&domain_name=www.w3resource.com&v=3&bsl=10&pac=0&u_his=7&u_tz=-480&dt=1706402653331&u_w=1366&u_h=768&biw=1297&bih=644&psw=1297&psh=644&frm=0&cl=600476684&uio=-&cont=autors-container-0&drt=0&jsid=csa&jsv=600476684&rurl=https%3A%2F%2Fwww.w3resource.com%2Fmysql%2Fmysql-partition.php&referer=https%3A%2F%2Fwww.w3resource.com%2Fmysql%2Faltering-table%2Faltering-table.php

    Here is the basic syntax for creating a table partitioned by RANGE COLUMNS :

    • column_list is a list of one or more columns.
    • value_list is a list of values and must be supplied for each partition definition.
    • column list and in the value list defining each partition must occur in the same order
    • The order of the column names in the partitioning column list and the value lists do not have to be the same as the order of the table column definitions in CREATE TABLE statement.

    Here is an example :mysql> CREATE TABLE table3 (col1 INT, col2 INT, col3 CHAR(5), col4 INT) PARTITION BY RANGE COLUMNS(col1, col2, col3) (PARTITION p0 VALUES LESS THAN (50, 100, ‘aaaaa’), PARTITION p1 VALUES LESS THAN (100,200,’bbbbb’), PARTITION p2 VALUES LESS THAN (150,300,’ccccc’), PARTITION p3 VALUES LESS THAN (MAXVALUE, MAXVALUE, MAXVALUE)); Query OK, 0 rows affected (1.39 sec)

    In the above example –

    • Table table3 contains the columns col1, col2, col3, col4
    • The first three columns have participated in partitioning COLUMNS clause, in the order col1, col2, col3.
    • Each value list used to define a partition contains 3 values in the same order and (INT, INT, CHAR(5)) form.

    LIST COLUMNS partitioning

    LIST COLUMNS accepts a list of one or more columns as partition keys.You can use various columns of data of types other than integer types as partitioning columns. You can use string types, DATE, and DATETIME columns

    In a company there are agents in 3 cities, for sales and marketing purposes. We have organized the agents in 3 cities as shown in the following table :

    CityAgent ID
    AA1, A2, A3
    BB1, B2, B3
    CC1, C2, C3, C4, C5

    Let create a table with LIST COLUMNS partitioning based on the above information :mysql> CREATE TABLE salemast ( agent_id VARCHAR(15), agent_name VARCHAR(50), agent_address VARCHAR(100), city_code VARCHAR(10)) PARTITION BY LIST COLUMNS(agent_id) ( PARTITION pcity_a VALUES IN(‘A1’, ‘A2’, ‘A3’), PARTITION pcity_b VALUES IN(‘B1’, ‘B2’, ‘B3’), PARTITION pcity_c VALUES IN (‘C1’, ‘C2’, ‘C3’, ‘C4’, ‘C5’)); Query OK, 0 rows affected (1.06 sec)

    You can use DATE and DATETIME columns in LIST COLUMNS partitioning, see the following example :CREATE TABLE sale_master (bill_no INT NOT NULL, bill_date DATE, cust_code VARCHAR(15) NOT NULL, amount DECIMAL(8,2) NOT NULL) PARTITION BY RANGE COLUMNS (bill_date)( PARTITION p_qtr1 VALUES LESS THAN (‘2013-04-01’), PARTITION p_qtr2 VALUES LESS THAN (‘2013-07-01’), PARTITION p_qtr3 VALUES LESS THAN (‘2013-10-01’), PARTITION p_qtr4 VALUES LESS THAN (‘2014-01-01’));

    MySQL HASH Partitioning

    MySQL HASH partition is used to distribute data among a predefined number of partitions on a column value or expression based on a column value. This is done by using PARTITION BY HASH(expr) clause, adding in CREATE TABLE STATEMENT. In PARTITIONS num clause, num is a positive integer represents the number of partitions of the table. The following statement creates a table that uses hashing on the studetn_id column and is divided into 4 partitions :

    MySQL>CREATE TABLE student (student_id INT NOT NULL, 
    class VARCHAR(8), name VARCHAR(40),
    date_of_admission DATE NOT NULL DEFAULT '2000-01-01') 
    PARTITION BY HASH(student_id) 
    PARTITIONS 4;
    Query OK, 0 rows affected (1.43 sec)
    

    Copy

    It is also possible to make a partition based on the year in which a student was admitted. See the following statement :

    MySQL> CREATE TABLE student (student_id INT NOT NULL, 
    class VARCHAR(8), class VARCHAR(8), name VARCHAR(40),
    date_of_admission DATE NOT NULL DEFAULT '2000-01-01') 
    PARTITION BY HASH(YEAR(date_of_admission)) 
    PARTITIONS 4;
    Query OK, 0 rows affected (1.27 sec)
    

    Copy

    MySQL KEY Partitioning

    MySQL KEY partition is a special form of HASH partition, where the hashing function for key partitioning is supplied by the MySQL server. The server employs its own internal hashing function which is based on the same algorithm as PASSWORD(). This is done by using PARTITION BY KEY, adding in CREATE TABLE STATEMENT. In KEY partitioning KEY takes only a list of zero or more column names. Any columns used as the partitioning key must comprise part or all of the table’s primary key if the table has one. If there is a primary key in a table, it is used as partitioning key when no column is specified as the partitioning key. Here is an example :MySQL> CREATE TABLE table1 ( id INT NOT NULL PRIMARY KEY, fname VARCHAR(25), lname VARCHAR(25)) PARTITION BY KEY() PARTITIONS 2; Query OK, 0 rows affected (0.84 sec)

    If there is no primary key but there is a unique key in a table, then the unique key is used for the partitioning key :MySQL> CREATE TABLE table2 ( id INT NOT NULL, fname VARCHAR(25), lname VARCHAR(25), UNIQUE KEY (id)) PARTITION BY KEY() PARTITIONS 2; Query OK, 0 rows affected (0.77 sec)

    MySQL Subpartitioning

    Subpartitioning is a method to divide each partition further in a partitioned table. See the following CREATE TABLE statement :

    CREATE TABLE table10 (BILL_NO INT, sale_date DATE, cust_code VARCHAR(15), 
    AMOUNT DECIMAL(8,2))
    PARTITION BY RANGE(YEAR(sale_date) )
    SUBPARTITION BY HASH(TO_DAYS(sale_date))
    SUBPARTITIONS 4 (
    PARTITION p0 VALUES LESS THAN (1990),
    PARTITION p1 VALUES LESS THAN (2000),
    PARTITION p2 VALUES LESS THAN (2010),
    PARTITION p3 VALUES LESS THAN MAXVALUE
    );
    

    Copy

    In the above statement –

    • The table has 4 RANGE partitions.
    • Each of these partitions—p0, p1, p2 and p3—is further divided into 4 subpartitions.
    • Therefore the entire table is divided into 4 * 4 = 16 partitions.

    Here is the partition status of table10 :mysql> SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME=’stable’; +—————-+————+ | PARTITION_NAME | TABLE_ROWS | +—————-+————+ | p0 | 0 | | p0 | 0 | | p0 | 0 | | p0 | 0 | | p1 | 0 | | p1 | 0 | | p1 | 0 | | p1 | 0 | | p2 | 0 | | p2 | 0 | | p2 | 0 | | p2 | 0 | | p3 | 0 | | p3 | 0 | | p3 | 0 | | p3 | 0 | +—————-+————+ 16 rows in set (0.16 sec)