Mysql

171
What is a storage engine 1. A storage engine is a software which a DataBase management System uses to create, read, update and delete data from a database. 2. Storage engines are also called as DataBase Engines. Storage engines of MySQL Engines Description MyISAM Default storage engine, manages non transactional tables, prov MEMORY Provides in-memory tables, formerly known as HEAP. It sores al quick looks up of reference and other identical data. MERGE Groups more than one similar MyISAM tables to be treated as a InnoDB Provides transaction-safe tables, supports FOREIGN KEY referen recovery capabilities to protect data. It also support row-lev used in a multiuser environment. It stores data in clustered i BDB Provides transaction-safe tables. EXAMPLE You can create tables with this engine, but can not store or f new storage engine. NDBCLUSTER Used by MySQL Cluster to implement tables that are partitioned experimentally. ARCHIVE Used to store a large amount of data, does not support indexes CSV Stores data in Comma Separated Value format in a text file.

Transcript of Mysql

Page 1: Mysql

What is a storage engine

1. A storage engine is a software which a DataBase management System uses to create, read, update and delete data from a database.

2. Storage engines are also called as DataBase Engines.

Storage engines of MySQL

Engines Description

MyISAM Default storage engine, manages non transactional tables, provides high-speed storage and retrieval, supports full text searching.

MEMORY Provides in-memory tables, formerly known as HEAP. It sores all data in RAM for faster access than storing data on disks. Useful for quick looks up of reference and other identical data.

MERGE Groups more than one similar MyISAM tables to be treated as a single table, can handle non transactional tables, included by default.

InnoDB Provides transaction-safe tables, supports FOREIGN KEY referential-integrity constraints. It supports commit, rollback, and crash-recovery capabilities to protect data. It also support row-level locking. It's "consistent nonlocking reads" increases performance when used in a multiuser environment. It stores data in clustered indexes which reduces I/O for queries based on primary keys.

BDB Provides transaction-safe tables.

EXAMPLE You can create tables with this engine, but can not store or fetch data. Purpose of this is to teach developers about how to write a new storage engine.

NDBCLUSTER Used by MySQL Cluster to implement tables that are partitioned over many computers. Works on number of Unix platforms, works on Windows experimentally.

ARCHIVE Used to store a large amount of data, does not support indexes.

CSV Stores data in Comma Separated Value format in a text file.

BLACKHOLE Accepts data to store but always returns empty.

FEDERATED Added in MySQL 5.0.3. Stores data in a remote database.

Page 2: Mysql

Display a list of Storage Engines supported by your MySQL

installation

Command

SHOW ENGINES;

Output (taken using windows command prompt)

Output (taken using MySQL query browser)

Page 3: Mysql

Differences between InnoDB and MyISAM

InnoDB Storage Engine Features :

Storage limits 64TB Transactions

MVCC (Multiversion concurrency control) Yes Geospatial data type support

B-tree indexes Yes T-tree indexes

Full-text search indexes Yes Clustered indexes

Index caches Yes Compressed data

Cluster database support No Replication support

Backup / point-in-time recovery Yes Query cache support

Page 4: Mysql

MyISAM Storage Engine Features :

Storage limits 256TB Transactions

MVCC (Multiversion concurrency control) No Geospatial data type support

B-tree indexes Yes T-tree indexes

Full-text search indexes Yes Clustered indexes

Index caches Yes Compressed data

Cluster database support No Replication support

Backup / point-in-time recovery Yes Query cache support

What is data type

1. A data type specifies a particular type of data, such as integer, floating-point, Boolean etc.

2. A data type also specifies the possible values for that type, the operations that can be performed on that type and the way the values of that type are stored.

MySQL data types

MySQL supports a number of SQL standard data types in various categories. MySQL has Numeric Types, the DATETIME, DATE, and TIMESTAMP Types and String Types. Data types are discussed on this page are based on MySQL community server 5.6

MySQL Numeric Types

MySQL supports all standard SQL numeric data types which include INTEGER, SMALLINT, DECIMAL, and NUMERIC. It also supports the approximate numeric data types (FLOAT, REAL, and DOUBLE PRECISION). The keyword INT is a synonym for INTEGER, and the keywords DEC and FIXED are synonyms for DECIMAL. DOUBLE is a synonym for DOUBLE PRECISION (a nonstandard extension). REAL is a synonym for DOUBLE PRECISION (a nonstandard variation), unless the REAL_AS_FLOAT SQL mode is enabled. The BIT data type stores bit-field values and is supported for MyISAM, MEMORY, InnoDB, and NDB tables.

Page 5: Mysql

Integer types

SQL standard integer types INTEGER (or INT) and SMALLINT are supported by MySQL. As an extension to the standard, MySQL also supports the integer types TINYINT, MEDIUMINT, and BIGINT. Following table shows the required storage and range (maximum and minimum value for signed and unsigned integer) for each integer type.

Type Length in Bytes

Minimum Value(Signed)

Maximum Value(Signed)

TINYINT 1 -128 127

SMALLINT 2 -32768 32767

MEDIUMINT 3 -8388608 8388607 to

INT 4 -2147483648 2147483647

BIGINT 8 -9223372036854775808 9223372036854775807

Floating-Point Types

The FLOAT and DOUBLE types represent approximate numeric data values. MySQL uses four bytes for single-precision values and eight bytes for double-precision values.

Types Description

FLOAT A precision from 0 to 23 results in a four-byte single-precision FLOAT column

DOUBLE A precision from 24 to 53 results in an eight-byte double-precision DOUBLE column.

MySQL allows a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here values can be stored up to M digits in total where D represents the decimal point. For example, a column defined as FLOAT(8,5) will look like -999.99999. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001.

Following table shows the required storage and range (maximum and minimum value for signed and unsigned integer) for each floating-point type.

Page 6: Mysql

Type Lengthin Bytes

Minimum Value(Signed)

Maximum Value(Signed)

FLOAT 4 -3.402823466E+38  -1.175494351E-38

DOUBLE 8 -1.7976931348623157E+ 308

-2.2250738585072014E- 308

Fixed-Point Types

Fixed-Point data types are used to preserve exact precision, for example with currency data. In MySQL DECIMAL and NUMERIC types store exact numeric data values. MySQL 5.6 stores DECIMAL values in binary format.

In standard SQL the syntax DECIMAL(5,2)  (where 5 is the precision and 2 is the scale. ) be able to store any value with five digits and two decimals. Therefore the value range will be from -999.99 to 999.99. The syntax DECIMAL(M) is equivalent to DECIMAL(M,0). Similarly, the syntax DECIMAL is equivalent to DECIMAL(M,0). MySQL supports both of these variant forms of DECIMAL syntax. The default value of M is 10. If the scale is 0, DECIMAL values contain no decimal point or fractional part.The maximum number of digits for DECIMAL is 65, but the actual range for a given DECIMAL column can be constrained by the precision or scale for a given column.

Bit Value Types

The BIT data type is used to store bit-field values. A type of BIT(N) enables storage of N-bit values. N can range from 1 to 64.To specify bit values, b'value' notation can be used. value is a binary value written using zeros and ones. For example, b'111' and b'10000000' represent 7 and 128, respectively

Numeric type attributes

MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type

Types Description

TYPE(N) Where N is an integer and display width of the type is upto N digits.

ZEROFILL The default padding of spaces is replaced with zeros. So, for a column INT(3) ZEROFILL, 7 is displayed as 007.

Page 7: Mysql

MySQL Date and Time Types

The date and time types represents DATE, TIME, DATETIME, TIMESTAMP, and YEAR. Each type has a range of valid values, as well as a “zero” value.

DATETIME, DATE, and TIMESTAMP Types

Types Description

DATETIME Use when you need values containing both date and time information.

DATE Use when you need only date information.

TIMESTAMP Values are converted from the current time zone to UTC while storing, and converted back from UTC to the current time zone when retrieved.

Year Type

The YEAR type is a 1-byte type used to represent year values. It can be declared as YEAR(2) or YEAR(4) to specify a display width of two or four characters. If no width is given the default is four characters

YEAR(4) and YEAR(2) have different display format, but have the same range of values. For 4-digit format, MySQL displays YEAR values in YYYY format, with a range of 1901 to 2155, or 0000. For 2-digit format, MySQL displays only the last two (least significant) digits; for example, 70 (1970 or 2070) or 69 (2069).

You can specify YEAR values in a variety of formats:

String length Range

4-digit string '1901' to '2155'.

4-digit number 1901 to 2155.

1- or 2-digit string '0' to '99'. Values in the ranges '0' to '69' and '70' to '99' are converted to YEAR values in the ranges 2000 to 2069 and 1970 to 1999.

Page 8: Mysql

1- or 2-digit number 1 to 99. Values in the ranges 1 to 69 and 70 to 99 are converted to YEAR values in the ranges 2001 to 2069 and 1970 to 1999.

String Types

The string types are CHAR, VARCHAR, BINARY, VARBINARY, BLOB, TEXT, ENUM, and SET.

CHAR and VARCHAR Types

The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved. They also differ in maximum length and in whether trailing spaces are retained.

Types Description

CHAR Contains non-binary strings. Length is fixed as you declare while creating a table. When stored, they are right-padded with spaces to the specified length.

VARCHAR Contains non-binary strings. Columns are variable-length strings.

BINARY and VARBINARY Types

The BINARY and VARBINARY types are similar to CHAR and VARCHAR, except that they contain binary strings rather than nonbinary strings.

Types Description Range in bytes

BINARY Contains binary strings. 0 to 255

VARBINARY Contains binary strings. A value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions.

BLOB and TEXT Types

A BLOB is a binary large object that can hold a variable amount of data. There are four types of BLOB, TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. These differ only in the maximum length of the values they can hold. The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to the four BLOB types and have the same maximum lengths and storage requirements.

Page 9: Mysql

Types Description

BLOB Large binary object that containing a variable amount of data. Values are treated as binary strings.You don't need to specify length while creating a column.

TEXT Values are treated as character strings having a character set.

ENUM Types

A string object whose value is chosen from a list of values given at the time of table creation. For example -

CREATE TABLE length ( length ENUM('small', 'medium', 'large') );

SET Types

A string object having zero or more comma separated values (maximum 64). Values are chosen from a list of values given at the time of table creation.

Difference between MySQL Datetime and Timestamp

data Types

The DATETIME type is used when you need values containing both date and time information. MySQL retrieves and displays DATETIME values in ‘YYYY-MM-DD HH:MM:SS’ format. The supported range is 1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

The TIMESTAMP data type is also used when you need values containing both date and time information. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC

The major difference between DATETIME and TIMESTAMP is that TIMESTAMP values are converted from the current time zone to UTC while storing, and converted back from UTC to the current time zone when retrieved. The datetime data type value is unchanged.

See the following example :

Page 10: Mysql

The following command displays current time zone information :

Let create a table with two fields udatetime (data type -> datetime) utimestamp (data type -> timestamp) and insert one record with now() (returns the current date and time) as a value in both fields.

mysql> create table tempdate (udatetime datetime, utimestamp timestamp);

Query OK, 0 rows affected (0.32 sec)

mysql> insert into tempdate values ((now()), (now()));

Query OK, 1 row affected (0.05 sec)

Now see the records;

At this point the datetime and timestamp data types have same values.

In the above output both the fields have same values. Let change the timezone and see the result.

mysql> SET TIME_ZONE ='Europe/Paris';

Query OK, 0 rows affected (0.00 sec)

Now execute the following command :

mysql> select * from tempdate;

+---------------------+---------------------+

| udatetime | utimestamp |

+---------------------+---------------------+

| 2013-06-29 16:55:18 | 2013-06-29 13:25:18 |

+---------------------+---------------------+

1 row in set (0.00 sec)

The above output shows that udatetime (data type is DATETIME) is unchanged whereas utimestamp (data type is TIMESTAMP) is changed as the new timezone is set to 'Europe/Paris'.

MySql Connection

Page 11: Mysql

Introduction

Before you perform any operations, you need to connect to MySQL server and select a MySQL database.

Connecting to MySQL server from command line

Command

mysql -h HostName -u UserName -p

Parameters

Name Description

-h Keyword, followed by HOSTNAME.

HostName MySQL server name

-u Keyword, followed by USERNAME.

UserName MySQL user name

-p Asks you to enter password.

As soon as you enter this command, it asks you to provide password for the user you mentioned. Supplying the appropriate password would allow you to connect to MySQL server.

Connecting to MySQL database from command line

Command

mysql>use DatabaseName;Where DatabaseName is the database you want to select.

Page 12: Mysql

Disconnecting or closing MySQL server from

command line

Command

mysql>exitThis command must be executed form the mysql prompt.

Connecting to MySQL server and database using PHP

view plainprint?

1. <?php  2. $host="localhost";  3. $username="root";  4. $password="";  5. $db_name="bookinfo";  6. $con=mysql_connect("$host", "$username", "$password")or die("cannot 

connect");  7. mysql_select_db("$db_name")or die("cannot select DB");  8. ?>  9.               

Replace the values of the $host, $username, $password and $db_name according to your own setup. Notice that we have also selected the database with PHP, which is a must, before you can fetch data form a MySQL database.

Disconnecting or closing a MySQL connection using

PHP

view plainprint?

1. <?php  2. mysql_close($con);  3. ?>  4.               

Where $con=mysql_connect("$host", "$username", "$password")or die("cannot connect"), shown in the previous example.

Note

Page 13: Mysql

It will be convenient for you if you keep the script you require to connect to and disconnect from MySQL in a PHP file and then include that file in each PHP file you are using to perform various operations on database.

Using MySQL persistent connection with PHP

Description

1. MySQL persistent connection is a connection which first tries to find if any identical (i.e with same hostname, username and password) exists. If so, then commands followed will use that connection. If such a connection does not exist, it would create one.

2. MySQL persistent connection does not need a mysql_close().

PHP code

view plainprint?

1. <?php  2. $host="localhost";  3. $username="root";  4. $password="";  5. $db_name="bookinfo";  6. $con=mysql_pconnect("$host", "$username", "$password")or die("cannot 

connect"); mysql_select_db("$db_name")or die("cannot select DB");  7. ?>  8.               

Note

Use mysql_pconnect() for better performance out of your MySQL server

What is a database?

When an amount of data is stored in an organized way, that is called a Database. In computers, a database is managed by a software called Database management System.

What is a table?

A table is a set of data values. These values are organized using a vertical columns and horizontal rows. Columns are identified by their names.

Pictorial representation of a database with tables

Page 14: Mysql

Sample table : author

MySQL create database

In MySQL, the create statement is used to create a database.

Syntax

CREATE database [database_name];

Arguments

Name Description

database_name A database.

Example :

The following command creates 'bookinfo' database.

Page 15: Mysql

view plainprint?

1. CREATE DATABASE bookinfo;  

The database names are case sensitive under Unix but this restriction does not apply in Windows. This is also true for table names. The best practice is to use same letter case for creating database as well as table.

Note : A database which have just been created is not current database. The user must have to instruct to make it the current database. A database needs to be created only once but a user must have to select it each time he intends to work with that database.

MySQL use database

MySQL use statement is used to change the database from default to the given database.

Syntax

Use [database_name];

Arguments

Name Description

database_name A database.

MySQL show database

SHOW statement displays a list of currently existing databases on the server.

Syntax

SHOW [expression];

Arguments

Name Description

expression Databases.

Page 16: Mysql

Example :

The following MySQL statement will show the current database.

view plainprint?

1. SHOW databases;  

The list of databases shown bellow by the statement may be different to the other user's machine. SHOW DATABASES does not show databases for those you don't have SHOW DATABASES privilege.

Output

MySQL select database

MySQL select database statement is used to see which database is currently selected.

Syntax

SELECT [expression];

Arguments

Name Description

expression Keyword DATABASE followed by ().

Example :

Page 17: Mysql

The following MySQL statement will show the current database.

view plainprint?

1. SELECT DATABASE();  

Output

MySQL show tables statement

MySQL 'show tables' statement displays a list of the tables in the database in use. If there is no table in the database, it returns empty rows.

Syntax

SHOW [expression];

Arguments

Name Description

expression The key word tables.

The following statement displays the list of tables in the database 'bookinfo'.

view plainprint?

1. SHOW tables;   

Output

Page 18: Mysql

MySQL SHOW CREATE DATABASE

Shows the CREATE DATABASE statement that creates the given database. If the SHOW statement includes an IF NOT EXISTS clause, the output too includes such a clause. SHOW CREATE SCHEMA is a synonym for SHOW CREATE DATABASE.

Syntax

SHOW CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name

Arguments

Name Description

db_name The name of the database.

The following statement shows the create database statement of 'world' database.

view plainprint?

1. SHOW create database world;  

Output

Page 19: Mysql

Description

MySQL CREATE TABLE is used to create a table within a database.

MySQL represents each table by an .frm table format (definition) file in the database directory. The storage engine might create other files as well for the table. The storage engine creates data and index files. The table for this files are as follows

File Purpose

table_name.frm Table format (definition) file.

table_name.MYD Data file.

table_name.MYI Index file.

Syntax

CREATE TABLE [table_name data_type([size]) ...

Arguments

Name Description

table_name Name of the table.

data_type Type of data the column can hold.

size Storage capacity of the said column.

Page 20: Mysql

Example :

The following statement will create 'NewPublisher' table which have columns like following -

view plainprint?

1. CREATE TABLE  publisher(  2. pub_id      varchar(8),  3. pub_name        varchar(50),  4. pub_city        varchar(25),  5. country         varchar(25),  6. country_office  varchar(25)  7. no_of_branch    int(3),  8. estd            date);  

PHP script

view plainprint?

1. <?php  2. include('dbopen.php');  3. $result = mysql_query("CREATE TABLE NewPublisher(  4. pub_id varchar(8),  5. pub_name varchar(50),  6. pub_city varchar(25),  7. country varchar(25),  8. country_office  varchar(25),  9. no_of_branch int(3),  10. estd date)");  11. $sql1 = "SHOW TABLES FROM bookinfo";  12. $result1 = mysql_query($sql1);  13. while($row1=mysql_fetch_array($result1))  14. {  15. echo "<table>";  16. echo "<tr>";  17. echo "<td align='center'>" . $row1['Tables_in_bookinfo'] . "</

td>";  18. echo "</tr>";  19. echo "</table>";  20. }  21. ?>  

View the example in browser

MySQL DESCRIBE statement

Page 21: Mysql

MySQL DESCRIBE statement is used to show the structure of the created table.

Syntax

DESCRIBE [table_name];

Arguments

Name Description

table_name Name of the table.

Example :

The following statement will display the structure of a given table.

view plainprint?

1. DESCRIBE  publisher;  

Sample table : publisher

Output

PHP script

view plainprint?

1. <?php  2. include('dbopen.php');  

Page 22: Mysql

3. $sql = "DESCRIBE publisher";  4. $result = mysql_query($sql);  5. echo "<table>";  6. echo "<h2>Structure of publisher table : </h2>";  7. echo "<table border='1' style='border-collapse: collapse;border-

color: silver;'>";  8. echo "<tr style='font-weight: bold;'>";  9. echo "<td width='100' align='center'>Field</td>";  10. echo "<td width='100' align='center'>Type</td>";  11. echo "<td width='100' align='center'>Null</td>";  12. echo "<td width='100' align='center'>key</td>";  13. echo "<td width='100' align='center'>Default</td>";  14. echo "<td width='100' align='center'>Extra</td>";  15. echo "</tr>";  16. while($row = mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center'>" . $row['Field'] . "</td>";  20. echo "<td align='center'>" . $row['Type'] . "</td>";  21. echo "<td align='center'>" . $row['Null'] . "</td>";  22. echo "<td align='center'>" . $row['key'] . "</td>";  23. echo "<td align='center'>" . $row['Default'] . "</td>";  24. echo "<td align='center'>" . $row['Extra'] . "</td>";  25. echo "</tr>";  26. }  27. echo "</table>";  28. ?>  

View the example in browser

MySQL create table when not EXISTS

The keywords IF NOT EXISTS is used to prevent an error from occurring if the table exists. The keywords IF NOT EXISTS will not verify whether the existing table is of same structure indicated by the CREATE TABLE statement.

Example :

The following statement creates a table newauthor if the table 'newauthor' does not exist with the following column name, type, length and default value -

view plainprint?

1. CREATE TABLE IF NOT EXISTS newauthor  2. (aut_id         varchar(8),  3. aut_name        varchar(50),    4. country         varchar(25),    

Page 23: Mysql

5. home_city       varchar(25) NULL);   

MySQL LOAD statement

MySQL LOAD statement populates a table.

Suppose the user have a .txt file name 'pub.txt' in a folder of its own, containing 1 record per line and separated by tabs and arranged in order as the columns listed in the table. You can use LOAD statement to populate the table. For missing values user can use NULL values and that should be represented by ‘\N’ in the text file.

Syntax

LOAD DATA LOCAL INFILE '[path/][file_name]' INTO TABLE [table_name ];

Arguments

Name Description

path The address of the file.

file_name The name of the .txt file.

table_name The table where the data will be loaded.

Example :

In the following code, the content of the text file pub.txt will be loaded in the publisher table.

The path of the file should be mentioned.

The text file contain the row like -

P002<tab>BPP Publication<tab>Mumbai<tab>India<tab>New Delhi<tab>10<tab>1985-10-01

Code

view plainprint?

1. LOAD DATA LOCAL INFILE  'pub.txt' INTO TABLE publisher;  

Page 24: Mysql

Sample table : publisher

MySQL LOAD statement with line terminator

MySQL LOAD statement with ‘\r\n’ as a line terminator can also be used to populate a table.

Example :

The following code will load the records  from the pub.txt file in publisher table. The ‘\r\n’ can be used as a line terminator.

The text file contain the row like -

P002<tab>BPP Publication<tab>Mumbai<tab>India<tab>New Delhi<tab>10<tab>1985-10-01\r\n

Sample table : publisher

Code

view plainprint?

1. LOAD DATA LOCAL INFILE 'path/pub.txt' INTO TABLE publisher  2. LINES TERMINATED BY \r\n ;  

MySql loading data into a table with insert statement

To insert new records into a table INSERT statement can be used. The values will be supplied by the user in the same order as columns are listed  in the table. String and date values are needed to be specified within quoted string.

Syntax

INSERT INTO <table_name> values(value1,value2,....);

Arguments

Name Description

table_name Name of the table.

Page 25: Mysql

value1,value2,... Values which will be inserted against the sequence of columns.

Example :

The following statement insert one row into the table 'publisher' which contains the values according to the sequence of the columns.

Sample table : publisher

Code

view plainprint?

1. INSERT INTO  publisher   2. values(‘P010’,’ Novel Publisher Ltd.’,’   3. mumbai’,’ India’,’ hydrabad’); 

Introduction

MySQL is (as of July 2013) the world's most widely used open-source relational database management system (RDBMS), enabling the cost-effective delivery of reliable, high-performance and scalable Web-based and embedded database applications. It is widely-used as the database component of LAMP (Linux, Apache, MySQL, Perl/PHP/Python) web application software stack.MySQL tutorial of w3resource is a comprehensive tutorial to learn MySQL(5.6). We have hundreds of examples covered, often with PHP code. This helps you to learn how to create PHP-MySQL based web applications.

Table of contents

What is MySQL?

MySQL Editions

Who uses MySQL

Programming & Front ends tools

Key features of MySQL

Google Trends

Page 26: Mysql

w3resource MySQL tutorials

What is MySQL

MySQL was developed by Michael Widenius and David Axmark in 1994.

Presently MySQL is maintained by Oracle (formerly Sun, formerly MySQL AB).

Initial release : 23 May 1995

Current stable release : 5.6.13 / 30 July 2013

Written in : C, C++

Operating system : Cross-platform

Available in : English

License of MySQL is available under GNU General Public License (version 2) or proprietary EULA.

Go Top

MySQL Editions

There are five types MySQL editions.

MySQL Enterprise Edition : This edition includes the most comprehensive set of advanced features, management tools and technical support to achieve the highest levels of MySQL scalability, security, reliability, and uptime.

MySQL Standard Edition : This edition enables you to deliver high performance and scalable Online Transaction Processing (OLTP) applications. It provides the ease of use that has made MySQL famous along with industrial-strength performance and reliability.

Page 27: Mysql

MySQL Classic Edition : This edition is the ideal embedded database for ISVs, OEMs and VARs developing read-intensive applications using the MyISAM storage engine.

MySQL Cluster CGE : MySQL Cluster is a scalable, real-time, ACID-compliant database, combining 5 x 9s availability and open source technology. With a distributed, multi-master architecture and no single point of failure, MySQL Cluster scales horizontally on commodity hardware accessed via SQL and NoSQL APIs.

MySQL Embedded (OEM/ISV) : MySQL Database is a full-featured, zero-administration database that more than 3000 ISVs, OEMs, and VARs rely on to bring their products to market faster and make them more competitive.

Go Top

Who uses MySQL

Some of the most visited websites like Flickr, Facebook, Wikipedia, Google (not for search), YouTube.

Content Management Systems like WordPress, phpBB, Drupal, Joomla, TYPO3, MODx.

Last but not least, a large number of web developers across the world.

Programming

MySQL works on many system platforms, including AIX, BSDi, FreeBSD, HP-UX, eComStation, i5/OS, IRIX, Linux, Mac OS X, Microsoft Windows, NetBSD, Novell NetWare, OpenBSD, OpenSolaris, OS/2 Warp, QNX, Solaris, Symbian, SunOS, SCO OpenServer, SCO UnixWare, Sanos and Tru64. A port of MySQL to OpenVMS also exists.

Many programming languages with language-specific APIs include libraries access MySQL databases. These include Microsoft's Visual Studio, PHP, ASP, Cold Fusion, Java etc.

Go Top

Some of the widely used MySQL front ends (tools for

managing MySQL)

The MySQL GUI Tools Bundle is a cross-platform open source suite of desktop applications, building and manipulating the data within MySQL databases Development on the GUI Tools bundle has stopped, The GUI Tools bundle has been replaced by MySQL Workbench with the beta releases of MySQL Workbench 5.2. Currently MySQL Workbench Team are working on Version 6.0. The first public beta, labeled version 6.0.2, was released on June 14, 2013.There are lot of third-party free and proprietary graphical administration applications available that integrate with MySQL and users to work with database. Here are some third-party tools for managing MySQL :

Tools Description

Page 28: Mysql

phpMyAdmin Third party, Free, Web based

HeidiSQL Third party, Free, For Windows

Adminer Third party, Free

DBEdit Third party, Free

dbForge GUI Tools Third party, Free

Navicat Third party, Commercial

Maatkit Third party, Command line, free

MySQL Sandbox Third party, Command line, free

SQLBuddy A free Web-based front end, developed in PHP.

SQLyog Commercial, but a free 'community' edition is available.

Toad for MySQL Third party, free from Quest Software

Go Top

Key features of MySQL

MySQL follows ANSI SQL 99, the standard SQL.

Cross Platform.

Unicode support

ACID compliance

Stored procedures

Triggers

Cursors

Page 29: Mysql

Views

Information schema

Strict mode (ensures MySQL does not truncate or otherwise modify data to conform to an underlying data type, when an incompatible value is inserted into that type)

Independent storage engines

Transactions with the InnoDB and NDB Cluster storage engines; savepoints with InnoDB

SSL support

Query caching

Sub-SELECTs (i.e. nested SELECTs)

Replication support (i.e. Master-Master Replication & Master-Slave Replication) with one master per slave, many slaves per master

Full-text indexing and searching using MyISAM engine

Embedded database library

Shared-nothing clustering through MySQL Cluster

Support for hotbackup

Multiple storage engines, allowing one to choose the one that is most effective for each table in the application

Commit grouping, gathering multiple transactions from multiple connections together to increase the number of commits per second.

Description

The ALTER TABLE command is used  to change the structure of an existing table. It helps to add or delete columns, create or destroy indexes, change the type of existing columns, rename columns or the table itself. It  can also be used to change the comment for the table and type of the table.

Syntax

ALTER TABLE <table_name> ADD <column_name data_type(size)> ;

Arguments

Name Description

Page 30: Mysql

table_name Name of the table.

column_name Name of the column.

data_type Which type of data the column can hold.

size Storage capacity of the said column.

Example

Sample table : newbook_mast

Code

view plainprint?

1. ALTER TABLE newbook_mast  2. ADD id  INT;  

Explanation

The statement above will add a column 'id' of integer type in the table 'newbook_mast'.

MySQL ALTER TABLE insert column FIRST

Description

Here in the following we have discussed how to use MySQL ALTER TABLE command to insert column at the beginning of the table.

Syntax

ALTER TABLE <table_name> ADD <column_name data_type(size)>

Arguments

Page 31: Mysql

Name Description

table_name Name of the table.

data_type Which type of data the column can hold.

size Storage capacity of the said column.

Example

Sample table : newbook_mast

Code

view plainprint?

1. ALTER TABLE newbook_mast  2. ADD id  INT  FIRST ;  

Explanation

The statement above will add a column 'id' of integer type as first column in the table 'newbook_mast'.

MySQL ALTER TABLE to insert column AFTER a

column

Description

In this page we have discussed how to use MySQL ALTER TABLE command to insert a column after a specific column.

Example

Sample table : newbook_mast

Page 32: Mysql

Code

view plainprint?

1. ALTER TABLE newbook_mast  2. ADD pub_name  VARCHAR(35)  AFTER pub_id,  3. ADD pub_add   VARCHAR(50)  AFTER dt_of_pub;  

Explanation

The above statement will add  two specific columns 'pub_name' and 'pub_add' after 'pub_id' and 'dt_of_pub' columns respectively.

MySQL ALTER TABLE ADD INDEX

Description

In this page we have discussed how to use MySQL ALTER TABLE command to add an index.

Example

Sample table : newbook_mast

Code

view plainprint?

1. ALTER TABLE newbook_mast  2. ADD INDEX cate_id(cate_id);  

Explanation

The above statement will add  an index named 'cate_id' on 'cate_id' column for the table 'newbook_mast'.

MySQL ALTER TABLE ADD UNIQUE INDEX

Description

Page 33: Mysql

In this page we have discussed how to use MySQL ALTER TABLE command to add an UNIQUE INDEX to a table.

Example

Sample table : newbook_mast

Code

view plainprint?

1. ALTER TABLE newbook_mast  2. ADD UNIQUE INDEX cate_id(cate_id);  

Explanation

The above statement will add  an UNIQUE INDEX  named 'cate_id' on 'cate_id' column for the table 'newbook_mast'.

MySQL ALTER TABLE ADD PRIMARY KEY    

 MySql alter table add primary key has average rating 10 out of 10. Total 1 users rated.

<<Previous Next>>

Description

In this page we have discussed how to use MySQL ALTER TABLE command to add a PRIMARY KEY to a table.

Example

Sample table : newpurchase

Code

view plain print ?

1. ALTER TABLE newpurchase  

Page 34: Mysql

2. ADD PRIMARY KEY invoice_no (invoice_no);  

Explanation

The above statement will create a PRIMARY KEY on 'invoice_no' column for the table 'newpurchase'.

MySQL ALTER TABLE ADD FOREIGN KEY

Description

Here in the following we have discussed how to use MySQL ALTER TABLE command to add a FOREIGN KEY to a table.

Example

Sample table : newbook_mast

Code

view plain print ?

1. ALTER TABLE newbook_mast  2. ADD  FOREIGN KEY(ord_no,book_id)  3. REFERENCES   4. neworder(ord_no,book_id);  

Explanation

The above statement will create a FOREIGN KEY with the combination of 'ord_no' and 'book_id' columns of 'newbook_mast' table with a reference from 'neworder' table.

MySQL ALTER TABLE ADD and DROP column, INDEX, PRIMARY KEY and FOREIGN KEY    

 MySql alter table add and drop column, index, primary key and foreign key has average rating 8 out of 10. Total 25 users rated.

Page 35: Mysql

<<Previous Next>>

Description

In this page we have discussed how to use MySQL ALTER TABLE command to add and drop column, add PRIMARY KEY, FOREIGN KEY and INDEX into a table. This is an advanced use of ALTER TABLE.

Syntax

ALTER TABLE <table_name> [ADD | DROP] <column_name data_type(size)><column_name> ;

Arguments

Name Description

table_name Name of the table.

column_name Name of the column.

data_type Which type of data the column can hold.

size Storage capacity of the said column.

Example

Sample table : newpurchase

Code

view plain print ?

1. ALTER TABLE newpurchase  2. DROP id,  3. ADD id int NOT NULL DEFAULT 0,  4. ADD chano VARCHAR(10) NOT NULL,  5. ADD  chadt date,  

Page 36: Mysql

6. DROP  PRIMARY KEY,  7. ADD  PRIMARY KEY invoice_no (invoice_no),  8. DROP  INDEX cate_id,  9. ADD  INDEX cate_id(cate_id),  10. DROP  FOREIGN KEY ord_no,  11. ADD  FOREIGN KEY(ord_no,book_id) REFERENCES  12. neworder(ord_no,book_id);  

Explanation

The above statement modifies the structure of 'newpurchase' table in following manner -

1. Drop the 'id' column, existing primary key, index 'cate_id' and foreign key 'ord_no'. 2. Add an integer type column 'id' with default value 0.3. Add column 'chano' which is varchar type and size 10 and don't accept any NULL value.4. Add a date type column 'chadt'.5. Add a primary key named 'invoice_no' on 'invoice_no' column.6. Add an index named 'cate_id' on 'cate_id' column.7. Add a foreign key in combination of two columns 'ord_no' and 'book_id' which is referred by the same primary key of 'neworder' table.

MySQL INSERT INTO statement    

 MySql insert into statement has average rating 7 out of 10. Total 9 users rated.

<<Previous Next>>

Description

MySQL INSERT INTO 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 inserting multiple rows at a time.

Syntax

INSERT INTO table_name ([column_name],[...column_name],...)

VALUES( [column_value],[..column_value]);

Arguments

Name Description

Page 37: Mysql

table_name Name of the table.

column_name Name of the column.

column_value Value to be inserted.

Example with PHP code to insert data into a mysql

table

HTML code (say form.html)

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"  2. "http://www.w3.org/TR/html4/strict.dtd">  3. <html lang="en">  4. <head>  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  6. <title>form to insert data</title>  7. </head>  8. <body>  9. <form method="post" action="insert.php">  10. <input type="text" name="name" />  11. <input type="text" name="email" />  12. <input type="text" name="address" />  13. <input type="submit" value="Submit">  14. </form>  15. </body>  16. </html>  

PHP code (say insert.php)

view plain print ?

1. <?php  2. $host="localhost"; //yout host name  3. $username="root";  //yout user name  4. $password="";      // your password  

Page 38: Mysql

5. $db_name="test";  // your database name  6. $con=mysql_connect("$host", "$username", "$password")or die("cannot 

connect"); //mysql connection  7. mysql_select_db("$db_name")or die("can not select DB"); //select you

r database  8. $name = $_POST['name'];  9. $email = $_POST['email'];  10. $address = $_POST['address'];  11. $query = "INSERT INTO test (name,email,address) VALUES ('$name

', '$email', '$address')";  12. mysql_query($query) or die('Query "' . $query . '" failed: ' . 

mysql_error());  13. // name, email and address are fields of your fields; test you

r table. $name, $email and $address are values collected from the form  

14. ?>  

MySQL INSERT one row in a table

Description

Here we have discussed how to insert a single row into a table using MySQL INSERT INTO statement.

Example

Code

view plain print ?

1. INSERT INTO newcate   2. VALUES ("CA006","Sports");  

Explanation

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 effected.

To see the inserted record, write the following code -

view plain print ?

1. SELECT *  2. FROM newcate;  

Page 39: Mysql

Output

MySQL INSERT values for specific columns

Description

Here we have discussed how to insert values for specific columns using MySQL INSERT INTO statement.

Example

Sample table : newpurchase

Code

view plain print ?

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

Explanation

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

To see the inserted row here is the code below -

view plain print ?

1. SELECT  invoice_no,ord_no,book_name   2. FROM newpurchase;  

Page 40: Mysql

Output

MySQL INSERT NULL values

Description

Here we have discussed how to insert NULL values into one or more columns using MySQL INSERT INTO statement.

Example :

Sample table : newpurchase

Code

view plain print ?

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

Explanation

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.

To see the inserted row here is the code below -

select invoice_no,ord_no,book_name from newpurchase;

Output

Page 41: Mysql

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    

 MySql insert rows with select statement has average rating 10 out of 10. Total 3 users rated.

<<Previous Next>>

Description

In this page we have discussed how to insert 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.

Example

Sample table : purchase

Code

view plain print ?

1. INSERT INTO testpurchase   

Page 42: Mysql

2. SELECT *   3. FROM purchase;  

Explanation

The above statement will insert all the rows into  'testpurchase' table from the identical table 'purchase'.

To see some specific columns from inserted row here is the code below -

select invoice_no,ord_no,book_name from testpurchase;

Output

MySQL INSERT rows with SELECT statement and

WHERE

Description

Here in the following we have discussed how to insert 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.

Example

Sample table : purchase

Code

view plain print ?

Page 43: Mysql

1. INSERT INTO testpurchase   2. SELECT *   3. FROM purchase   4. WHERE YEAR(invoice_dt)='2008';  

Explanation

The above statement performs the following operations -

1. insert rows into  'testpurchase' table from the identical table 'purchase',2. the year of 'invoice_date' of 'purchase' table must be '2008' .

To see some specific columns from inserted rows, here is the code below -

select invoice_no,ord_no,book_name from testpurchase;

Output

MySQL INSERT rows with GROUP BY    

 MySql insert rows with group by and order by has average rating 8 out of 10. Total 1 users rated.

<<Previous Next>>

Description

In this page we have discussed how to insert 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 GROUP BY.

This way you can insert the rows of one table into another identical table for a specific group.

Example

Page 44: Mysql

Sample table : purchase

Code

view plain print ?

1. INSERT INTO testpurchase   2. SELECT *   3. FROM purchase   4. GROUP BY cate_id;  

Explanation

The above statement has performed the following -

1. the rows of 'purchase' table have grouped according to the 'cate_id',2. and inserted into the table 'testpurchase'.

To see some specific columns from inserted rows, here is the code below -

view plain print ?

1. SELECT  invoice_no,ord_no,book_name   2. FROM testpurchase;  

Output

MySQL INSERT records with ORDER BY

Description

Here in the following we have discussed how to insert values into a table using MySQL INSERT INTO statement, when the column names and values are collected from another identical table using MySQL SELECT, GROUP BY and ORDER BY.

This way you can insert the rows of one table into another identical table when columns are sorted by a specific column.

Page 45: Mysql

Example

Sample table : purchase

Code

view plain print ?

1. INSERT INTO testpurchase   2. SELECT * FROM purchase   3. GROUP BY cate_id   4. ORDER BY cate_id;  

Explanation

The above statement has performed the following -

1. the rows of 'purchase' table have grouped according to the 'cate_id',2. the group of 'purchase' table have arranged in ascending order 3. and inserted into the table 'testpurchase'.

To see some specific columns from inserted rows, here is the code below -

view plain print ?

1. SELECT  cate_id,ord_no,book_name FROM testpurchase;  

Output

MySQL INSERT with LEFT JOIN    

 MySql insert with left join has average rating 8 out of 10. Total 13 users rated.

Page 46: Mysql

<<Previous Next>>

Description

In this page we have discussed how to insert values of one table into another table using MySQL INSERT INTO statement and MySQL LEFT JOIN.

The MySQL LEFT JOIN will preserve the records of the "left" table. Mysql starts with the left table and scans to the right table and store the value in the left table which matches the condition. For unmatched rows it returns null. Each item in the left table will show up in a MySQL result, even if there isn't a match with the other table that it is being joined to.

Example

Sample table : book_mast

Sample table : author

Code

view plain print ?

1. INSERT INTO  authorinfo   2. SELECT book_mast.aut_id,book_mast.book_name,author.aut_name,author.c

ountry   3. FROM book_mast   4. LEFT JOIN author  5. ON book_mast.aut_id=author.aut_id;  

Explanation

The above statement has performed the following operations -

1. the 'aut_id' and 'book_name' of 'book_mast' table and 'aut_name' and 'country' of 'author' table will join together based upon 'aut_id' columns of both of the tables, 2. and inserted into the 'authorinfo' table.

To see some specific columns from inserted rows, here is the code below -

view plain print ?

1. SELECT   aut_id,book_name,aut_name    2. FROM authorinfo;  

Page 47: Mysql

Output

MySQL DELETE statement    

 MySql DELETE statement has average rating 8 out of 10. Total 1 users rated.

<<Previous Next>>

Description

MySQL DELETE statement removes records or rows from the table based on some given conditions.

If no conditions are specified, all rows of the table will be deleted.

Syntax

DELETE FROM  [table name]

WHERE [condition];

Arguments

Page 48: Mysql

Name Description

table_name Name of the table.

condition Conditions.

MySQL DELETE specific rows or records

Sample table : newcate

Code

view plain print ?

1. DELETE FROM newcate   2. WHERE cate_id='CA002';  

Explanation

The statement above will remove those records from the 'newcate' table which satisfies the condition -

1. 'cate_id' must be 'CA002'.

MySQL DELETE all rows or records

Description

If not accompanied by any condition about which rows are to be removed, MySQL DELETE statement removes all records or rows from a table.

Example

Sample table : Newcate

Code

Page 49: Mysql

view plain print ?

1. DELETE FROM Newcate;  

Explanation

The statement above will remove all the rows or records from 'Newcate' table.

MySQL DELETE with ORDER BY for limited number of

rows

Description

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.

Example

Sample table : newauthor

Code

view plain print ?

1. DELETE FROM newauthor   2. ORDER BY country DESC LIMIT  2;  

Explanation

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'.

MySQL DELETE rows using subqueries with alias and

EXISTS

Page 50: Mysql

Description

A subquery can be used with MySQL DELETE statement.

This is useful when you want to delete rows depending upon a complex condition.

Example

Sample table : newauthor

Sample table : book_mast

Code

view plain print ?

1. DELETE FROM newauthor   2. WHERE exists   3. (SELECT *   4. FROM  book_mast   5. WHERE no_page>300   6. AND newauthor.aut_id=book_mast.aut_id);  

Explanation

If we want to remove records from 'newauthor' table which satisfies the following conditions -

1. 'aut_id' of 'newauthor' table must exists 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 the above code will be executed.

MySQL TRUNCATE table

Description

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

Page 51: Mysql

TRUNCATE

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.

You can't use WHERE clause.

Faster than DELETE.

Syntax

TRUNCATE table<table_name>

Argument

Name Description

table_name Name of the table

Example

Sample table : newauthor

Code

view plain print ?

1. TRUNCATE TABLE newauthor;  

Explanation

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

Page 52: Mysql

MySQL UPDATE Statement    

 MySQL UPDATE has average rating 7 out of 10. Total 19 users rated.

<<Previous Next>>

MySQL UPDATE Table

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

Specific columns can be modified using the SET clause by supplying new values for those 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.

Syntax

UPDATE table_name SET ([column_name],[...column_name],...)

VALUES ( [column_value],[..column_value]);

Arguments

Name Description

table_name Table which is to be updated.

column_name Column which is to be updated.

column_value New value.

MySQL UPDATE column

MySQL UPDATE column can be used to update some specific columns.

Page 53: Mysql

Example :

The following MySQL statement will update the 'receive_qty' column of 'newpurchase' table with a new value 20.

Sample table : newpurchase

Code

view plain print ?

1. UPDATE newpurchase SET receive_qty=20;  

MySQL UPDATE with WHERE

MySQL UPDATE command can be used with WHERE clause to filter (against certain conditions) which rows will be updated.

Example :

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.

Code

view plain print ?

1. UPDATE newpurchase   2. SET receive_qty=25   3. WHERE purch_price>50;  

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.

Example :

The following MySQL statement will update pub_lang column with NULL if purch_price is more than 50. In the statement, other columns are also updated with respective new values.

Page 54: Mysql

Code

view plain print ?

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

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.

Example :

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.

Sample table : newpurchase

Code

view plain print ?

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

MySQL UPDATE with subqueries

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

Example :

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.

Page 55: Mysql

Sample table : newpurchase

Code

view plain print ?

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

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.

PHP Script

view plain print ?

1. <?php  2.  $dbhost = 'localhost';  3.  $dbuser = 'root';  4.  $dbpass = '';  5.  $connec = mysql_connect($dbhost, $dbuser, $dbpass);  6.  if(!$connec)  7.  {  8.  die('Could not connect: ' . mysql_error());  9.  }  

Page 56: Mysql

10.  $sql = "UPDATE item  11.  SET value = '112'  12.  WHERE item_code='item1'";  13.  mysql_select_db('mysql');  14.  $result = mysql_query($sql, $connec);  15.  if(!$result)  16.  {  17.  die('Could not update data: ' . mysql_error());  18.  }  19.  echo "Data successfully updated...";  20.  mysql_close($connec);  21.  ?>  

Output

Multiple Updates in MySQL

Sample table : table1

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.

Page 57: Mysql

Code

view plain print ?

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

Pictorial presentation :

Output

MySQL: Update with Join Statement

Sample tables

Page 58: Mysql

Problem

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

1). 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

view plain print ?

1. UPDATE table11, table12, table13   2. SET table11.aval1 = table12.bval1  3. WHERE table11.id = table13.id   4. AND table12.bval2 = table13.cval1  

Explanation

Page 59: Mysql

Output

MySQL select statement    

 MySQL select statement has average rating 8 out of 10. Total 1 users rated.

<<Previous Next>>

Page 60: Mysql

Description

MySQL SELECT statement retrieves zero or more rows from one or more tables or temporary tables in a database.

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

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables. 

Page 61: Mysql

* , ALL Indicating all columns.

column Columns or list of columns.

table Indicates the name of the table from where the rows will be retrieved.

DISTINCT DISTINCT clause is used to retrieve unique rows from a table.

DISTINCTROW DISTINCTROW is a synonym for DISTINCT.

HIGH_PRIORITY If used with SELECT, the associated query obtains higher priority than a 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 is part of a UNION, you can not use HIGH_PRIORITY along with.

STRAIGHT_JOIN If 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_RESULT Can be used with GROUP BY or DISTINCT. It tells the optimizer (a component of DataBase system which determines to 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_RESULT Can be used with GROUP BY or DISTINCT. It tells the optimizer (a component of DataBase system which determines to 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_RESULT It 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 long time. It can not be used for subqueries or following UNION.

SQL_CACHE It 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_CACHE It 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_ROWS It tells MySQL to calculate the number of would be 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().

Page 62: Mysql

select_expr An expression.

FROM This clause is used after SELECT and preceding tables or subqueries.

table_references Name of the tables used in a SELECT statement.

WHERE The conditions are supplied after this keyword (in a select statement).

where_condition Conditions placed after WHERE.

GROUP BY If used, the results returned from the field name used after GROUP BY clause is grouped together in result set.

col_name Name of the column or columns or fields.

expr An expression.

position Refers to the position of columns beginning with 1.

ASC If used, results are returned in ascending order.

DESC If used, results are returned in descending order.

WITH ROLLUP This modifier can be used with GROUP BY clause. If used, extra rows are added to the summary output.

HAVING This modifier can be used with GROUP BY clause and aggregate functions. Can not be used with WHERE clause.

ORDER BY MySQL ORDER BY clause specifies the order in which columns are sorted while retrieving data in a SELECT statement.

LIMIT It is always followed by one or two numeric arguments. The first argument is the offset of the first row to be returned and second argument is the maximum number of rows returned in the result set.

PROCEDURE This clause names a procedure that should process the data in the result set.

Page 63: Mysql

INTO OUTFILE Takes a backup of the associated table in a file specified.

INTO DUMPFILE If 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_name A variable name to store data temporarily.

FOR UPDATE If used with a storage engine that uses page or row locks, till the end of the transaction, rows checked by the query are write-locked.

LOCK IN SHARE MODE If 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.

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

Description

MySQL SELECT statement without any condition retrieves all records from a table.

Syntax

SELECT * FROM <table_name>

Arguments

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables. 

* Indicating all columns.

table_name Name of the table.

Example

Page 64: Mysql

Sample table : publisher

Code

view plain print ?

1. SELECT *  2. FROM publisher;  

Explanation

This SELECT statement will retrieve all data from publisher table.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  

Page 65: Mysql

4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />  

5. <title>example-select-all-data - php mysql examples | w3resource</title>  

6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the publishers with other detail : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's ID</td><td wi

dth='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>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT * FROM publisher");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "<td align='center' width='100'>" . $row['country'] . "</

td>";  23. echo "<td align='center' width='100'>" . $ro

w['country_office'] . "</td>";  24. echo "<td align='center' width='100'>" . $row['no_of_branch'] 

. "</td>";  25. echo "<td align='center' width='100'>" . $row['estd'] . "</

td>";  26. echo "</tr>";  27. }  28. echo "</table>";  29. ?>  30. </body>  31. </html>  

MySql select specific rows    

Page 66: Mysql

 MySQL select specific rows has average rating 6 out of 10. Total 3 users rated.

<<Previous Next>>

Description

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

Syntax

SELECT <column1,column2,...>

FROM <table_name>

Arguments

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables.

column1,column2,... List of columns to be retrieve.

table_name Name of the table.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT *  2. FROM publisher  3. WHERE country='USA'  

Explanation

Page 67: Mysql

This SELECT statement will retrieve those particular rows where 'country' is USA.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-rows - php mysql examples | w3resourc

e</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the publishers those who belong to USA : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's ID</td><td wi

dth='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>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT * FROM publisher WHERE country='

USA';");  

Page 68: Mysql

16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "<td align='center' width='100'>" . $row['country'] . "</

td>";  23. echo "<td align='center' width='100'>" . $ro

w['country_office'] . "</td>";  24. echo "<td align='center' width='100'>" . $row['no_of_branch'] 

. "</td>";  25. echo "<td align='center' width='100'>" . $row['estd'] . "</

td>";  26. echo "</tr>";  27. }  28. echo "</table>";  29. ?>  30. </body>  31. </html>   

View the example in browser

MySql select specific rows with and operator

Description

In the example included in this page we have shown how to use AND operator with SELECT statement to fetch specific rows of a table.

MySql AND operator is used to combine more than one conditions aiming to fetch records when both of the conditions are satisfied.

Syntax

SELECT *

FROM <table_name>

WHERE <expression>

Arguments

Page 69: Mysql

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables. 

* Indicating all columns.

table_name Name of the table.

expression It is one or more condition. Logical operators and various function can be used in a expression.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT *  2. FROM publisher  3. WHERE country='USA'  4. AND pub_city='New York';  

Explanation

This SELECT statement will retrieve those particular rows where country and city of the publisher are USA and New York.

Output

Page 70: Mysql

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-rows-with-and-operator - php mysql ex

amples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the publishers those who belong to USA as well as 

New York : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's ID</td><td wi

dth='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>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT * FROM publisher WHERE country='

USA' AND pub_city='New York'");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  

Page 71: Mysql

20. echo "<td align='center' width='200'>" . $row['pub_name'] . "</td>";  

21. echo "<td align='center' width='100'>" . $row['pub_city'] . "</td>";  

22. echo "<td align='center' width='100'>" . $row['country'] . "</td>";  

23. echo "<td align='center' width='100'>" . $row['country_office'] . "</td>";  

24. echo "<td align='center' width='100'>" . $row['no_of_branch'] . "</td>";  

25. echo "<td align='center' width='100'>" . $row['estd'] . "</td>";  

26. echo "</tr>";  27. }  28. echo "</table>";  29. ?>  30. </body>  31. </html>  

MySql select specific columns    

 MySQL select specific columns has average rating 10 out of 10. Total 1 users rated.

<<Previous Next>>

Description

To retrieve records from specific columns, you need to specify a list of comma separated columns.

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT book_name,aut_id,book_price  2. FROM book_mast;  

Page 72: Mysql

Explanation

The above MySQL statement returns name of the book, author id and price of the books from book_mast table.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns - php mysql examples | w3reso

urce</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the books along with author's id and price : </

h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  

Page 73: Mysql

12. echo "<td width='200' align='center'>Name of the book</td><td width='200' align='center'>Author's ID</td><td width='200' align='center'>Price of the book</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT book_name,aut_id,book_price FROM 

book_mast");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['book_name'] . "

</td>";  20. echo "<td align='center' width='200'>" . $row['aut_id'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['book_price'] . 

"</td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql select specific columns with distinct operator

Description

DISTINCT clause is used to retrieve unique rows from a table.

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT DISTINCT aut_id  2. FROM book_mast;  

Page 74: Mysql

Explanation

The above MySQL statement retrieves the unique author ids from book_mast table.

Output

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.

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns-with-distinct - php mysql exa

mples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the unique author ids'  : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  

Page 75: Mysql

12. echo "<td width='200' align='center'>Unique author ids'</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT DISTINCT aut_id FROM book_mast

");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['aut_id'] . "</

td>";  20. echo "</tr>";  21. }<br>  22. echo "</table>";  23. ?>  24. </body>  25. </html>  

View the example in browser

MySql select specific columns with logical and

operator

Description

In the following example included in this page we have shown how to use AND operator to fetch data from some specific columns of a table.

AND operator is used to combine more than one conditions aiming to fetch records when both of the conditions are satisfied.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. WHERE country='USA' AND pub_city='New York';  

Page 76: Mysql

Explanation

The above MySQL statement retrieves records from pub_name, country, pub_city columns of publisher table, if country and city of the publisher are USA and New York.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns-with-and - php mysql examples 

| w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of publisher's ( along with their country and city ) 

those who belong to USA as well as New York : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200'align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher WHERE country='USA' AND pub_city='New York'");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  

Page 77: Mysql

19. echo "<td align='center' width='200'>" . $row['pub_name'] . "</td>";  

20. echo "<td align='center' width='200'>" . $row['country'] . "</td>";  

21. echo "<td align='center' width='100'>" . $row['pub_city'] . "</td>";  

22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql select specific columns with logical or operator

Description

In the following example included in this page we have shown how to use OR operator to fetch data from some specific columns of a table.

OR operator retrieves records from a table if at least one of the given conditions is satisfied.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. WHERE country='USA' OR pub_city='New York';  

Explanation

The above 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.

Page 78: Mysql

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns-with-or - php mysql examples 

| w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of publisher's ( along with their country and city ) 

those who belong to USA as well as New York : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name,country,pub_city FROM p

ublisher WHERE country='USA' OR pub_city='New York'");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  

Page 79: Mysql

21. echo "<td align='center' width='100'>" . $row['pub_city'] . "</td>";  

22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

MySql sorting rows in ascending order    

 MySQL sorting rows in ascending order has average rating 6 out of 10. Total 2 users rated.

<<Previous Next>>

Description

In the example included in this page we have shown how to sort rows of a table in ascending order using ORDER BY clause.

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 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.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT pub_name, country,pub_city   2. FROM publisher  3. ORDER BY pub_name;  

Page 80: Mysql

Explanation

In the above 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.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-php-mysql-bit_count()</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Alphabetical list of publishers with their name, country a

nd city : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  

Page 81: Mysql

15. $result = mysql_query("SELECT pub_name,country,pub_city FROM publisher ORDER BY pub_name");  

16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql sorting rows in descending order

Description

In the example below included in this page we have shown how to sort rows of a table in descending order using ORDER BY clause.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. ORDER BY pub_name DESC;  

Explanation

Page 82: Mysql

In the above MySQL statement, all records of pub_name, country and pub_city columns of publisher table are being fetched and sorted against pub_name column in reverse order (since DESC is used ).

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-sorting-rows-in-descending-order - php mysql examples 

| w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Reverse alphabetical list of publishers with their name, c

ountry and city : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher ORDER BY pub_name DESC");  16. while($row=mysql_fetch_array($result))  

Page 83: Mysql

17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

MySql sorting rows on multiple columns    

 MySql sorting rows on multiple columns has average rating 7 out of 10. Total 2 users rated.

<<Previous Next>>

Description

In this page we have discussed how ORDER BY clause is used to perform sorting on multiple columns.

See the note for how sorting using ORDER BY works.

Note : 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.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  

Page 84: Mysql

3. ORDER BY country,pub_city;  

Explanation

In the above 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.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-sorting-rows-on-multiple-columns- php mysql examples 

| w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of publishers with their country and city, sorted agi

anst country and city : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  

Page 85: Mysql

12. echo "<td width='200' align='center'>Publisher's name</td><td width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher ORDER BY country,pub_city");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql sorting rows on multiple columns in

descending order

Description

Here in the following we have discussed how ORDER BY clause is used to perform sorting on multiple columns in descending order.

See how sorting on multiple columns work.

Example

Sample table : publisher

Code

view plain print ?

Page 86: Mysql

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. ORDER BY country,pub_city DESC;  

Explanation

In the above MySQL statement, all records of pub_name, country and pub_city columns of publisher table are being fetched and sorted first in ascending order against 'country' column and then another sorting is performed against values of 'pub_city' column for each country.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-sorting-rows-on-multiple-columns-in-descending-order- 

php mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of publishers with their country and city, sorted aga

inst countries and cities (in a descending order) : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  

Page 87: Mysql

12. echo "<td width='200' align='center'>Publisher's name</td><td width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher ORDER BY country,pub_city DESC");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

MySql select with NULL value    

 MySql select with NULL value has average rating 8 out of 10. Total 1 users rated.

<<Previous Next>>

Description

In this page we have discussed how to use NULL, IS NULL an IS NOT NULL with SELECT statement.

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

1. A value of NULL says that the value is unknown, not applicable or will be added later.

2. A value of NULL is not an empty or zero value.

3. No two null values are equal.

Page 88: Mysql

4. Since 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

view plain print ?

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

Output

Example of SELECT with IS NULL, IS NOT NULL

Code

view plain print ?

1. SELECT 1 IS NULL, 1 IS NOT NULL;  

Output

Mysql maximum value for a column    

 MySQL maximum value for a column has average rating 8 out of 10. Total 4 users rated.

Page 89: Mysql

<<Previous Next>>

Description

In this page we have discussed how to use MAX() with SELECT statement.

MySQL MAX() retrieves maximum value from the column(s) specified within MAX (), i.e. between "(" and ")".

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT MAX(no_page) AS Pages  2. FROM  book_mast;  

Explanation

In the above MySQL statement, maximum value from the column no_pages is retrieved aliased as Pages from book_mast table.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

Page 90: Mysql

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-maximum-value-for-a-column- php mysql examples | w3re

source</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Showing maximum number of pages in a book: </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Pages</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT MAX(no_page) AS Pages FROM  book

_mast");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['Pages'] . "</

td>";  20. echo "</tr>";  21. }  22. echo "</table>";  23. ?>  24. </body>  25. </html>  

View the example in browser

MySql row wise maximum value for a column

Description

Here in the following we have explained how to retrieve row wise maximum value for a column.

Example

Sample table : book_mast

Code

Page 91: Mysql

view plain print ?

1. SELECT book_name,isbn_no,book_price  2. FROM  book_mast  3. WHERE book_price=(  4. SELECT MAX(book_price) FROM book_mast);  

Explanation

The statement will show the most costly book (along with it's ISBN no and price) from book_mast table.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-row-wise-maximum-value-for-a-column- php mysql exampl

es | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>The most costly book in book_mast table is : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Name of the book</td><td 

width='200' align='center'>ISBN no</td><td width='200' align='center'>Price of the book</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  

Page 92: Mysql

15. $result = mysql_query("SELECT book_name,isbn_no,book_price  16. FROM  book_mast  17. WHERE book_price=(  18. SELECT MAX(book_price) from book_mast)");  19. while($row=mysql_fetch_array($result))  20. {  21. echo "<tr>";  22. echo "<td align='center' width='200'>" . $row['book_name'] . "

</td>";  23. echo "<td align='center' width='200'>" . $row['isbn_no'] . "</

td>";  24. echo "<td align='center' width='200'>" . $row['book_price'] . 

"</td>";  25. echo "</tr>";  26. }  27. echo "</table>";  28. ?>  29. </body>  30. </html>  

View the example in browser

MySql group wise maximum value for a column

Description

Here in the following we have discussed how to retrieve group wise maximum value for a column.

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT pub_lang,MAX(book_price) AS price  2. FROM  book_mast  3. GROUP BY pub_lang;  

Explanation

The statement will retrieve the most costly book for each language from book_mast table.

Page 93: Mysql

Output

Note : For a particular row, we have not inserted any value for pub_lang column. That is shown as NULL.

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-group-wise-maximum-value-for-a-column- php mysql exam

ples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>A list of Languages in which books have been published and 

their respective prices : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Language of the book</

td><td width='200' align='center'>Price</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_lang,MAX(book_price) AS pric

e  16. FROM  book_mast  17. GROUP BY pub_lang");  18. while($row=mysql_fetch_array($result))  19. {  20. echo "<tr>";  

Page 94: Mysql

21. echo "<td align='center' width='200'>" . $row['pub_lang'] . "</td>";  

22. echo "<td align='center' width='200'>" . $row['price'] . "</td>";  

23. echo "</tr>";  24. }  25. echo "</table>";  26. ?>  27. </body>  28. </html>  

Note : For a particular row, we have not inserted any value for pub_lang column. That is a NULL value. In the output you will find that as blank.

MySQL select statement    

 MySQL select statement has average rating 8 out of 10. Total 1 users rated.

<<Previous Next>>

Description

MySQL SELECT statement retrieves zero or more rows from one or more tables or temporary tables in a database.

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]]

Page 95: Mysql

[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

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables. 

* , ALL Indicating all columns.

column Columns or list of columns.

table Indicates the name of the table from where the rows will be retrieved.

DISTINCT DISTINCT clause is used to retrieve unique rows from a table.

DISTINCTROW DISTINCTROW is a synonym for DISTINCT.

HIGH_PRIORITY If used with SELECT, the associated query obtains higher priority than a 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 is part of a UNION, you can not use HIGH_PRIORITY along with.

STRAIGHT_JOIN If 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_RESULT Can be used with GROUP BY or DISTINCT. It tells the optimizer (a component of DataBase system which determines to most efficient way of executing a query) that the result set is small, so use fast

Page 96: Mysql

temporary tables to store the resulting table instead of using sorting.

SQL_BIG_RESULT Can be used with GROUP BY or DISTINCT. It tells the optimizer (a component of DataBase system which determines to 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_RESULT It 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 long time. It can not be used for subqueries or following UNION.

SQL_CACHE It 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_CACHE It 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_ROWS It tells MySQL to calculate the number of would be 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_expr An expression.

FROM This clause is used after SELECT and preceding tables or subqueries.

table_references Name of the tables used in a SELECT statement.

WHERE The conditions are supplied after this keyword (in a select statement).

where_condition Conditions placed after WHERE.

GROUP BY If used, the results returned from the field name used after GROUP BY clause is grouped together in result set.

col_name Name of the column or columns or fields.

expr An expression.

Page 97: Mysql

position Refers to the position of columns beginning with 1.

ASC If used, results are returned in ascending order.

DESC If used, results are returned in descending order.

WITH ROLLUP This modifier can be used with GROUP BY clause. If used, extra rows are added to the summary output.

HAVING This modifier can be used with GROUP BY clause and aggregate functions. Can not be used with WHERE clause.

ORDER BY MySQL ORDER BY clause specifies the order in which columns are sorted while retrieving data in a SELECT statement.

LIMIT It is always followed by one or two numeric arguments. The first argument is the offset of the first row to be returned and second argument is the maximum number of rows returned in the result set.

PROCEDURE This clause names a procedure that should process the data in the result set.

INTO OUTFILE Takes a backup of the associated table in a file specified.

INTO DUMPFILE If 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_name A variable name to store data temporarily.

FOR UPDATE If used with a storage engine that uses page or row locks, till the end of the transaction, rows checked by the query are write-locked.

LOCK IN SHARE MODE If 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.

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

Description

MySQL SELECT statement without any condition retrieves all records from a table.

Page 98: Mysql

Syntax

SELECT * FROM <table_name>

Arguments

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables. 

* Indicating all columns.

table_name Name of the table.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT *  2. FROM publisher;  

Explanation

This SELECT statement will retrieve all data from publisher table.

Output

Page 99: Mysql

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-all-data - php mysql examples | w3resource</

title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the publishers with other detail : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's ID</td><td wi

dth='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>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT * FROM publisher");  

Page 100: Mysql

16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "<td align='center' width='100'>" . $row['country'] . "</

td>";  23. echo "<td align='center' width='100'>" . $ro

w['country_office'] . "</td>";  24. echo "<td align='center' width='100'>" . $row['no_of_branch'] 

. "</td>";  25. echo "<td align='center' width='100'>" . $row['estd'] . "</

td>";  26. echo "</tr>";  27. }  28. echo "</table>";  29. ?>  30. </body>  31. </html>  

MySql select specific rows    

 MySQL select specific rows has average rating 6 out of 10. Total 3 users rated.

<<Previous Next>>

Description

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

Syntax

SELECT <column1,column2,...>

FROM <table_name>

Arguments

Page 101: Mysql

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables.

column1,column2,... List of columns to be retrieve.

table_name Name of the table.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT *  2. FROM publisher  3. WHERE country='USA'  

Explanation

This SELECT statement will retrieve those particular rows where 'country' is USA.

Output

Page 102: Mysql

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-rows - php mysql examples | w3resourc

e</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the publishers those who belong to USA : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's ID</td><td wi

dth='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>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT * FROM publisher WHERE country='

USA';");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "<td align='center' width='100'>" . $row['country'] . "</

td>";  23. echo "<td align='center' width='100'>" . $ro

w['country_office'] . "</td>";  24. echo "<td align='center' width='100'>" . $row['no_of_branch'] 

. "</td>";  25. echo "<td align='center' width='100'>" . $row['estd'] . "</

td>";  

Page 103: Mysql

26. echo "</tr>";  27. }  28. echo "</table>";  29. ?>  30. </body>  31. </html>   

View the example in browser

MySql select specific rows with and operator

Description

In the example included in this page we have shown how to use AND operator with SELECT statement to fetch specific rows of a table.

MySql AND operator is used to combine more than one conditions aiming to fetch records when both of the conditions are satisfied.

Syntax

SELECT *

FROM <table_name>

WHERE <expression>

Arguments

Name Descriptions

SELECT SELECT statement is used to fetch rows or records from one or more tables. 

* Indicating all columns.

table_name Name of the table.

expression It is one or more condition. Logical operators and various function can be used in a expression.

Example

Page 104: Mysql

Sample table : publisher

Code

view plain print ?

1. SELECT *  2. FROM publisher  3. WHERE country='USA'  4. AND pub_city='New York';  

Explanation

This SELECT statement will retrieve those particular rows where country and city of the publisher are USA and New York.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-rows-with-and-operator - php mysql ex

amples | w3resource</title>  6. </head>  

Page 105: Mysql

7. <body>  8. <?php  9. echo "<h2>List of the publishers those who belong to USA as well as 

New York : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's ID</td><td wi

dth='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>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT * FROM publisher WHERE country='

USA' AND pub_city='New York'");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "<td align='center' width='100'>" . $row['country'] . "</

td>";  23. echo "<td align='center' width='100'>" . $ro

w['country_office'] . "</td>";  24. echo "<td align='center' width='100'>" . $row['no_of_branch'] 

. "</td>";  25. echo "<td align='center' width='100'>" . $row['estd'] . "</

td>";  26. echo "</tr>";  27. }  28. echo "</table>";  29. ?>  30. </body>  31. </html>  

MySql select specific columns    

 MySQL select specific columns has average rating 10 out of 10. Total 1 users rated.

Page 106: Mysql

<<Previous Next>>

Description

To retrieve records from specific columns, you need to specify a list of comma separated columns.

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT book_name,aut_id,book_price  2. FROM book_mast;  

Explanation

The above MySQL statement returns name of the book, author id and price of the books from book_mast table.

Output

PHP script

Page 107: Mysql

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns - php mysql examples | w3reso

urce</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the books along with author's id and price : </

h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Name of the book</td><td 

width='200' align='center'>Author's ID</td><td width='200' align='center'>Price of the book</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT book_name,aut_id,book_price FROM 

book_mast");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['book_name'] . "

</td>";  20. echo "<td align='center' width='200'>" . $row['aut_id'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['book_price'] . 

"</td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql select specific columns with distinct operator

Description

Page 108: Mysql

DISTINCT clause is used to retrieve unique rows from a table.

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT DISTINCT aut_id  2. FROM book_mast;  

Explanation

The above MySQL statement retrieves the unique author ids from book_mast table.

Output

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.

PHP script

view plain print ?

Page 109: Mysql

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns-with-distinct - php mysql exa

mples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of the unique author ids'  : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Unique author ids'</td>"; 

 13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT DISTINCT aut_id FROM book_mast

");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['aut_id'] . "</

td>";  20. echo "</tr>";  21. }<br>  22. echo "</table>";  23. ?>  24. </body>  25. </html>  

View the example in browser

MySql select specific columns with logical and

operator

Description

In the following example included in this page we have shown how to use AND operator to fetch data from some specific columns of a table.

AND operator is used to combine more than one conditions aiming to fetch records when both of the conditions are satisfied.

Page 110: Mysql

Example

Sample table : publisher

Code

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. WHERE country='USA' AND pub_city='New York';  

Explanation

The above MySQL statement retrieves records from pub_name, country, pub_city columns of publisher table, if country and city of the publisher are USA and New York.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns-with-and - php mysql examples 

| w3resource</title>  6. </head>  7. <body>  8. <?php  

Page 111: Mysql

9. echo "<h2>List of publisher's ( along with their country and city ) those who belong to USA as well as New York : </h2>";  

10. echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";  

11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200'align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher WHERE country='USA' AND pub_city='New York'");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql select specific columns with logical or operator

Description

In the following example included in this page we have shown how to use OR operator to fetch data from some specific columns of a table.

OR operator retrieves records from a table if at least one of the given conditions is satisfied.

Example

Sample table : publisher

Code

Page 112: Mysql

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. WHERE country='USA' OR pub_city='New York';  

Explanation

The above 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.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-select-specific-columns-with-or - php mysql examples 

| w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>List of publisher's ( along with their country and city ) 

those who belong to USA as well as New York : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

Page 113: Mysql

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name,country,pub_city FROM p

ublisher WHERE country='USA' OR pub_city='New York'");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

MySql sorting rows in ascending order    

 MySQL sorting rows in ascending order has average rating 6 out of 10. Total 2 users rated.

<<Previous Next>>

Description

In the example included in this page we have shown how to sort rows of a table in ascending order using ORDER BY clause.

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 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.

Example

Sample table : publisher

Page 114: Mysql

Code

view plain print ?

1. SELECT pub_name, country,pub_city   2. FROM publisher  3. ORDER BY pub_name;  

Explanation

In the above 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.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-php-mysql-bit_count()</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Alphabetical list of publishers with their name, country a

nd city : </h2>";  

Page 115: Mysql

10. echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";  

11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name,country,pub_city FROM p

ublisher ORDER BY pub_name");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql sorting rows in descending order

Description

In the example below included in this page we have shown how to sort rows of a table in descending order using ORDER BY clause.

Example

Sample table : publisher

Code

view plain print ?

1. SELECT pub_name, country,pub_city  

Page 116: Mysql

2. FROM publisher  3. ORDER BY pub_name DESC;  

Explanation

In the above MySQL statement, all records of pub_name, country and pub_city columns of publisher table are being fetched and sorted against pub_name column in reverse order (since DESC is used ).

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-sorting-rows-in-descending-order - php mysql examples 

| w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Reverse alphabetical list of publishers with their name, c

ountry and city : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  

Page 117: Mysql

12. echo "<td width='200' align='center'>Publisher's name</td><td width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher ORDER BY pub_name DESC");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

MySql sorting rows on multiple columns    

 MySql sorting rows on multiple columns has average rating 7 out of 10. Total 2 users rated.

<<Previous Next>>

Description

In this page we have discussed how ORDER BY clause is used to perform sorting on multiple columns.

See the note for how sorting using ORDER BY works.

Note : 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.

Example

Sample table : publisher

Page 118: Mysql

Code

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. ORDER BY country,pub_city;  

Explanation

In the above 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.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-sorting-rows-on-multiple-columns- php mysql examples 

| w3resource</title>  6. </head>  7. <body>  

Page 119: Mysql

8. <?php  9. echo "<h2>List of publishers with their country and city, sorted agi

anst country and city : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher ORDER BY country,pub_city");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

View the example in browser

MySql sorting rows on multiple columns in

descending order

Description

Here in the following we have discussed how ORDER BY clause is used to perform sorting on multiple columns in descending order.

See how sorting on multiple columns work.

Example

Sample table : publisher

Page 120: Mysql

Code

view plain print ?

1. SELECT pub_name, country,pub_city  2. FROM publisher  3. ORDER BY country,pub_city DESC;  

Explanation

In the above MySQL statement, all records of pub_name, country and pub_city columns of publisher table are being fetched and sorted first in ascending order against 'country' column and then another sorting is performed against values of 'pub_city' column for each country.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-sorting-rows-on-multiple-columns-in-descending-order- 

php mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  

Page 121: Mysql

9. echo "<h2>List of publishers with their country and city, sorted against countries and cities (in a descending order) : </h2>";  

10. echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";  

11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Publisher's name</td><td 

width='200' align='center'>Country</td><td width='200' align='center'>Publisher's city</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_name, country,pub_city FROM 

publisher ORDER BY country,pub_city DESC");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='100'>" . $row['pub_city'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

MySql select with NULL value    

 MySql select with NULL value has average rating 8 out of 10. Total 1 users rated.

<<Previous Next>>

Description

In this page we have discussed how to use NULL, IS NULL an IS NOT NULL with SELECT statement.

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

Page 122: Mysql

1. A value of NULL says that the value is unknown, not applicable or will be added later.

2. A value of NULL is not an empty or zero value.

3. No two null values are equal.

4. Since 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

view plain print ?

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

Output

Example of SELECT with IS NULL, IS NOT NULL

Code

view plain print ?

1. SELECT 1 IS NULL, 1 IS NOT NULL;  

Output

Page 123: Mysql

Mysql maximum value for a column    

 MySQL maximum value for a column has average rating 8 out of 10. Total 4 users rated.

<<Previous Next>>

Description

In this page we have discussed how to use MAX() with SELECT statement.

MySQL MAX() retrieves maximum value from the column(s) specified within MAX (), i.e. between "(" and ")".

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT MAX(no_page) AS Pages  2. FROM  book_mast;  

Explanation

In the above MySQL statement, maximum value from the column no_pages is retrieved aliased as Pages from book_mast table.

Output

Page 124: Mysql

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-maximum-value-for-a-column- php mysql examples | w3re

source</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Showing maximum number of pages in a book: </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Pages</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT MAX(no_page) AS Pages FROM  book

_mast");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['Pages'] . "</

td>";  20. echo "</tr>";  21. }  22. echo "</table>";  23. ?>  24. </body>  25. </html>  

View the example in browser

MySql row wise maximum value for a column

Description

Here in the following we have explained how to retrieve row wise maximum value for a column.

Page 125: Mysql

Example

Sample table : book_mast

Code

view plain print ?

1. SELECT book_name,isbn_no,book_price  2. FROM  book_mast  3. WHERE book_price=(  4. SELECT MAX(book_price) FROM book_mast);  

Explanation

The statement will show the most costly book (along with it's ISBN no and price) from book_mast table.

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-row-wise-maximum-value-for-a-column- php mysql exampl

es | w3resource</title>  6. </head>  7. <body>  8. <?php  

Page 126: Mysql

9. echo "<h2>The most costly book in book_mast table is : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Name of the book</td><td 

width='200' align='center'>ISBN no</td><td width='200' align='center'>Price of the book</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT book_name,isbn_no,book_price  16. FROM  book_mast  17. WHERE book_price=(  18. SELECT MAX(book_price) from book_mast)");  19. while($row=mysql_fetch_array($result))  20. {  21. echo "<tr>";  22. echo "<td align='center' width='200'>" . $row['book_name'] . "

</td>";  23. echo "<td align='center' width='200'>" . $row['isbn_no'] . "</

td>";  24. echo "<td align='center' width='200'>" . $row['book_price'] . 

"</td>";  25. echo "</tr>";  26. }  27. echo "</table>";  28. ?>  29. </body>  30. </html>  

View the example in browser

MySql group wise maximum value for a column

Description

Here in the following we have discussed how to retrieve group wise maximum value for a column.

Example

Sample table : book_mast

Code

view plain print ?

Page 127: Mysql

1. SELECT pub_lang,MAX(book_price) AS price  2. FROM  book_mast  3. GROUP BY pub_lang;  

Explanation

The statement will retrieve the most costly book for each language from book_mast table.

Output

Note : For a particular row, we have not inserted any value for pub_lang column. That is shown as NULL.

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-group-wise-maximum-value-for-a-column- php mysql exam

ples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>A list of Languages in which books have been published and 

their respective prices : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Language of the book</

td><td width='200' align='center'>Price</td>";  

Page 128: Mysql

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_lang,MAX(book_price) AS pric

e  16. FROM  book_mast  17. GROUP BY pub_lang");  18. while($row=mysql_fetch_array($result))  19. {  20. echo "<tr>";  21. echo "<td align='center' width='200'>" . $row['pub_lang'] . "<

/td>";  22. echo "<td align='center' width='200'>" . $row['price'] . "</

td>";  23. echo "</tr>";  24. }  25. echo "</table>";  26. ?>  27. </body>  28. </html>  

Note : For a particular row, we have not inserted any value for pub_lang column. That is a NULL value. In the output you will find that as blank.

MySQL aggregate functions and grouping    

 MySQL aggregate function and grouping has average rating 8 out of 10. Total 14 users rated.

<<Previous Next>>

MySQL aggregate functions :

Description

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

Page 129: Mysql

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.

Page 130: Mysql

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 AVG() function    

 MySQL AVG() function has average rating 9 out of 10. Total 1 users rated.

<<Previous Next>>

Description

MySQL AVG() function retrieves the average value of a given expression.

If MySQL AVG() function does not find a matching row, it returns NULL.

Page 131: Mysql

Syntax

AVG(expr)

Where expr is a given expression.

Example : MySQL AVG() function

The following MySQL statement will return average number of pages (of books) from the book_mast table.

Sample table : book_mast

Code

view plainprint?

1. SELECT AVG(no_page)  2. FROM book_mast;  

Output

PHP script

view plainprint?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-avg-function- php mysql examples | w3resource</title> 

 6. </head>  

Page 132: Mysql

7. <body>  8. <?php  9. echo "<h2>Showing number of pages in average from a collection of bo

oks  :</h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Average number of pages</

td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT AVG(no_page)  16. FROM book_mast");  17. while($row=mysql_fetch_array($result))  18. {  19. echo "<tr>";  20. echo "<td align='center' width='200'>" . $row['AVG(no_page)'] 

. "</td>";  21. echo "</tr>";  22. }  23. echo "</table>";  24. ?>  25. </body>  26. </html>  

View the example in browser

Go Top

Example : MySQL AVG() function with group by

MySQL AVG() function retrieves average value of a given expression for each group, if it is used with group by option. The following statement will return the average number of pages for each group of 'pub_id' from book_mast table

Sample table : book_mast

Code

view plainprint?

1. SELECT pub_id,AVG(no_page)  2. FROM book_mast       3. GROUP BY pub_id;  

Page 133: Mysql

Output

PHP script

view plainprint?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-avg-with-group-by- php mysql examples | w3resource</

title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Publisher id and average number of pages of books publishe

d by them :</h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Publisher id</td><td widt

h='100' align='center'>Average     number of pages</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_id,AVG(no_page)  16. FROM book_mast  17. GROUP BY pub_id");  18. while($row=mysql_fetch_array($result))  19. {  20. echo "<tr>";  

Page 134: Mysql

21. echo "<td align='center' width='200'>" . $row['pub_id'] . "</td>";  

22. echo "<td align='center' width='200'>" . $row['AVG(no_page)'] . "</td>";  

23. echo "</tr>";  24. }  25. echo "</table>";  26. ?>  27. </body>  28. </html>  

View the example in browser

Go Top

Example : MySQL AVG() function with distinct

MySQL AVG() function retrieves the unique average value of a given expression when used with DISTINCT keyword. The following statement will return the average of unique receive_qty from the purchase table.

Sample table : purchase

Code

view plainprint?

1. SELECT AVG(DISTINCT(receive_qty))  2. FROM purchase;   

Output

PHP script

view plainprint?

Page 135: Mysql

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-avg-with-distinct- php mysql examples | w3resource</

title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Average of unique received quantity :</h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Average of unique receive

d quantity</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT AVG(DISTINCT(receive_qty))  16. FROM purchase");  17. while($row=mysql_fetch_array($result))  18. {  19. echo "<tr>";  20. echo "<td align='center' width='200'>" . $ro

w['AVG(DISTINCT(receive_qty))'] . "</td>";  21. echo "</tr>";  22. }  23. echo "</table>";  24. ?>  25. </body>  26. </html>  

View the example in browser

Go Top

Example : MySQL AVG() function decimal places

Here we have discussed how to use ROUND() along with AVG() to retrieve a value calculated upto a specific number of decimal places of a given value. The following statement will return the average number of pages up to 2 decimal places for each group of 'pub_id' from book_mast table.

Sample table : book_mast

Code

Page 136: Mysql

view plainprint?

1. SELECT pub_id,ROUND(AVG(no_page),2)  2. FROM book_mast            3. GROUP BY pub_id;  

Output

PHP script

view plainprint?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-avg-decimal-place- php mysql examples | w3resource</

title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Publisher id and average number of pages upto two decimal 

places of books published by them :</h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Publisher id</td><td widt

h='100' align='center'>Average number of pages up to two decimal places</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_id,ROUND(AVG(no_page),2)  

Page 137: Mysql

16. FROM book_mast  17. GROUP BY pub_id");  18. while($row=mysql_fetch_array($result))  19. {  20. echo "<tr>";  21. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  22. echo "<td align='center' width='200'>" . $ro

w['ROUND(AVG(no_page),2)'] . "</td>";  23. echo "</tr>";  24. }  25. echo "</table>";  26. ?>  27. </body>  28. </html>  

View the example in browser

Go Top

Example : MySQL AVG() function with COUNT()

function

Here we have discussed how to use MySQL AVG() function with COUNT() function to fetch suitable data. The following statement will return the average 'no_page' and number of publisher for each group of publisher from 'book_mast' table.

Sample table : book_mast

Code

view plainprint?

1. SELECT pub_id,COUNT(pub_id),AVG(no_page)  2. FROM book_mast  3. GROUP BY pub_id;  

Output

Page 138: Mysql

PHP script

view plainprint?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml"><br>  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-avg-and-count- php mysql examples | w3resource</

title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Publisher id, number of publishers against that id and ave

rage number of pages of the books published by them :</h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Publisher id</td><td widt

h='100' align='center'>Number of publishers</td><td width='100' align='center'>Average number of pages</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_id

,COUNT(pub_id),AVG(no_page)  16. FROM book_mast  17. GROUP BY pub_id");  18. while($row=mysql_fetch_array($result))  19. {  20. echo "<tr>";  21. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  

Page 139: Mysql

22. echo "<td align='center' width='200'>" . $row['COUNT(pub_id)'] . "</td>";  

23. echo "<td align='center' width='200'>" . $row['AVG(no_page)'] . "</td>";  

24. echo "</tr>";  25. }  26. echo "</table>";  27. ?>  28. </body>  29. </html>  

View the example in browser

Go Top

MySQL AVG() function with having

MySql AVG() function retrieves average value of a given expression against a condition specified after HAVING clause for each group specified after the GROUP BY clause. This way you can use HAVING and GROUP BY with MySQL AVG() function. The following statement will return the average no_page for those group whose 'pub_id' is 'P008' from the book_mast table.

Sample table : book_mast

Code

view plainprint?

1. SELECT pub_id, AVG(no_page)  2. FROM book_mast  3. GROUP BY pub_id  4. HAVING  pub_id='P008';  

Output

PHP script

Page 140: Mysql

view plainprint?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-avg-with-having- php mysql examples | w3resource</

title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Average number of pages of books published by the publishe

r whose publishing id is p008 :</h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Publisher id</td><td widt

h='100' align='center'>Average number of pages</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT pub_id, AVG(no_page)  16. FROM book_mast  17. GROUP BY pub_id  18. HAVING pub_id='P008'");  19. while($row=mysql_fetch_array($result))  20. {  21. echo "<tr>";  22. echo "<td align='center' width='200'>" . $row['pub_id'] . "</

td>";  23. echo "<td align='center' width='200'>" . $row['AVG(no_page)'] 

. "</td>";  24. echo "</tr>";  25. }  26. echo "</table>";  27. ?>  28. </body>  29. </html>  

MySQL BIT_AND() function    

 MySQL BIT_AND() function has average rating 8 out of 10. Total 3 users rated.

<<Previous Next>>

Page 141: Mysql

Description

MySQL BIT_AND() function returns the bitwise AND of all bits in a given expression.

The calculation is performed on 64 bit precession.

If this function does not find a matching row, it returns 18446744073709551615.

What is Bitwise AND operation

A logical AND operation is performed on each pair of corresponding bits of two binary expressions of equal length.

In each pair, it returns 1 if the first bit is 1 AND the second bit is 1. Else, it returns 0.

Syntax

BIT_AND(expr)

Where expr is a given expression.

MySQL Version : 5.6

Example : MySQL BIT_AND() function

The following MySQL statement performs Bitwise AND operation on the values of book_price column. A grouping on book_id column is also performed.

Sample table : book_mast

Code

view plain print ?

1. SELECT book_id, BIT_AND('book_price') AS BITS  2. FROM book_mast group by book_id;  

Output

Page 142: Mysql

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-of-bitwise-and- php mysql examples | w3resource</

title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Example of bitwise AND operation: </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='250' align='center'>Book ID</td><td width='20

0' align='center'>BIT</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT book_id, BIT_AND('book_price')AS 

BITS from book_mast group by book_id");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['book_id'] . "</

td>";  

Page 143: Mysql

20. echo "<td align='center' width='200'>" . $row['BITS'] . "</td>";  

21. echo "</tr>";  22. }  23. echo "</table>";  24. ?>  25. </body>  26. </html>  

MySQL BIT_OR() function    

 MySQL BIT_OR() function has average rating 10 out of 10. Total 1 users rated.

<<Previous Next>>

Description

MySQL BIT_OR() function returns the bitwise OR of all bits in a given expression.

The calculation is performed on 64 bit precession.

If this function does not find a matching row, it returns 0.

What is Bitwise OR operation

After taking two bit patterns of equal length, it performs logical OR operation on each pair of corresponding bits (the first of each; the second of each; and so on).

In each pair, the result is 1 if the first bit is 1 OR the second bit is 1 OR both bits are 1, and otherwise the result is 0.

Syntax

BIT_OR(expr)

Where expr is a given expression.

MySQL Version : 5.6

Example : MySQL BIT_OR() function

The following MySQL statement performs Bitwise OR operation on the values of book_price column. A grouping on book_id column is also performed.

Page 144: Mysql

Sample table : book_mast

Code

view plain print ?

1. SELECT book_id, BIT_OR('book_price') AS BITS  2. FROM book_mast group by book_id;  

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-bitwise-or- php mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Example of bitwise AND operation: </h2>";  

Page 145: Mysql

10. echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";  

11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='250' align='center'>Book ID</td><td width='20

0' align='center'>BIT</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT book_id, BIT_OR('book_price')AS 

BITS from book_mast group by book_id");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['book_id'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['BITS'] . "</

td>";  21. echo "</tr>";  22. }  23. echo "</table>";  24. ?>  25. </body>  26. </html>  

MySQL BIT_XOR() function    

 MySQL BIT_XOR() function has average rating 8 out of 10. Total 1 users rated.

<<Previous Next>>

Description

MySQL BIT_XOR() function returns the bitwise XOR of all bits in a given expression.

The calculation is performed on 64 bit precession.

If this function does not find a matching row, it returns 0.

What is Bitwise XOR operation

After taking two bit patterns of equal length, it performs logical XOR operation on each pair of corresponding bits (the first of each; the second of each; and so on).

The result in each position is 1 if the two bits are different, and 0 if they are same.

Page 146: Mysql

Syntax

BIT_XOR(expr)

Where expr is a given expression.

MySQL Version : 5.6

Example : MySQL BIT_XOR() function

The following MySQL statement performs Bitwise XOR operation on the values of book_price column. A grouping on book_id column is also performed.

Sample table : book_mast

Code

view plain print ?

1. SELECT book_id, BIT_XOR('book_price')   2. AS BITS from book_mast group by book_id;  

Output

PHP script

Page 147: Mysql

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-bitwise-xor- php mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Example of bitwise XOR operation: </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='250' align='center'>Book ID</td><td width='20

0' align='center'>BIT</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT book_id, BIT_XOR('book_price') A

S BITS from book_mast group by book_id");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['book_id'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['BITS'] . "</

td>";  21. echo "</tr>";  22. }  23. echo "</table>";  24. ?>  25. </body>  26. </html>  

MySQL COUNT() function    

 MySQL count() function has average rating 7 out of 10. Total 18 users rated.

<<Previous Next>>

Description

Page 148: Mysql

MySQL COUNT() function returns a count of number of non-NULL values of a given expression.

If it does not find any matching row, it returns 0.

Syntax

COUNT(expr);

Where expr is an expression.

MySQL Version : 5.6

Table of Contents

Example : MySQL COUNT() function

MySQL COUNT() with logical operator and example

MySQL COUNT() using multiple tables and example

Example : MySQL COUNT() function

The following MySQL statement will return the number of rows in author table.

Sample table : author

Code

view plain print ?

1. SELECT COUNT(*)  2. FROM author;  

Output

PHP script

Page 149: Mysql

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-aggregate-functions-and-grouping-count-function- php 

mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Counting how many authors are there in the authors table  

: </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Number of authors</td>";  13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT COUNT(*) FROM author");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['COUNT(*)'] . "<

/td>";  20. echo "</tr>";  21. }  22. echo "</table>";  23. ?>  24. </body>  25. </html>  

View the example in browser

Go Top

Example : MySQL COUNT() with logical operator

The following MySQL statement returns the number of publishers for USA and UK. The WHERE clause filters the rows for the country USA and UK. Grouping is performed on country and pub-city columns by GROUP BY and then COUNT() counts number of publishers for each groups.

Sample table : publisher

Page 150: Mysql

Code

view plain print ?

1. SELECT country,pub_city,COUNT(*)  2. FROM publisher  3. WHERE country='USA' OR country='UK' GROUP BY country,pub_city;  

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-aggregate-functions-and-grouping-count-with-logical-

operator- php mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Taking an account of how many authors are there in differe

nt cities of USA and UK : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Country</td><td width='20

0' align='center'>City</td><td width='200' align='center'>Number of authors</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  

Page 151: Mysql

15. $result = mysql_query("SELECT country,pub_city,COUNT(*)  16. FROM publisher WHERE country='USA' OR country='UK' GROUP BY co

untry,pub_city;");  17. while($row=mysql_fetch_array($result))  18. {  19. echo "<tr>";  20. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  21. echo "<td align='center' width='200'>" . $row['pub_city'] . "<

/td>";  22. echo "<td align='center' width='200'>" . $row['COUNT(*)'] . "<

/td>";  23. echo "</tr>";  24. }  25. echo "</table>";  26. ?>  27. </body>  28. </html>  

View the example in browser

Go Top

MySQL COUNT() using multiple tables

The following MySQL statement retrieves those rows from publisher table whose 'pub_id' in publisher table match the 'pub_id' in 'book_mast' table.

A grouping operation is performed on pub_id column of publisher table by GROUP BY and then number of times pub_id exists in publisher table is counted by COUNT().

Sample table : book_mast

Sample table : publisher

Code

view plain print ?

1. SELECT publisher.pub_name,COUNT(*)  2. FROM publisher,book_mast  3. WHERE publisher.pub_id=book_mast.pub_id  4. GROUP BY publisher.pub_id;  

Page 152: Mysql

Output

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-aggregate-functions-and-grouping-count-with-more-

tables- php mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Displaying the name of the publisher and their frequency i

n publisher table, whose publisher id present in both publisher and book_mast tables  :</h2>";  

10. echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";  

11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Publisher</td><td width

='100' align='center'>Frequency</td>  13. ";  14. echo "</tr>";  15. include("../dbopen.php");  16. $result = mysql_query("SELECT publisher.pub_name,COUNT(*)  17. FROM publisher,book_mast  18. WHERE publisher.pub_id=book_mast.pub_id  19. GROUP BY publisher.pub_id");  20. while($row=mysql_fetch_array($result))  

Page 153: Mysql

21. {  22. echo "<tr>";  23. echo "<td align='center' width='200'>" . $row['pub_name'] . "<

/td>";  24. echo "<td align='center' width='200'>" . $row['COUNT(*)'] . "<

/td>";  25. echo "</tr>";  26. }  27. echo "</table>";  28. ?>  29. </body>  30. </html>  

MySQL COUNT() function with group by    

 MySQL COUNT() function with group by has average rating 8 out of 10. Total 11 users rated.

<<Previous Next>>

Description

In this page we have discussed how to use MySQL COUNT() function with GROUP BY.

Example :

The following MySQL statement will show number of author for each country. The GROUP BY clause groups all records for each country and then COUNT() function in conjunction with GROUP BY counts the number of authors for each country.

Sample table : author

Code

view plain print ?

1. SELECT country,COUNT(*)  2. FROM author        3. GROUP BY country;  

Output

Page 154: Mysql

PHP script

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-aggregate-functions-and-grouping-count-with-group-by- 

php mysql examples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Taking an account of how many authors are there in differe

nt countries (in author table)  : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Country</td>";  13. echo "<td width='200' align='center'>Number of authors</td>";  14. echo "</tr>";  15. include("../dbopen.php");  16. $result = mysql_query("SELECT country,COUNT(*)  17. FROM author  18. GROUP BY country;");  19. while($row=mysql_fetch_array($result))  20. {  21. echo "<tr>";  22. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  23. echo "<td align='center' width='200'>" . $row['COUNT(*)'] . "<

/td>";  24. echo "</tr>";  

Page 155: Mysql

25. }  26. echo "</table>";  27. ?>  28. </body>  29. </html>  

View the example in browser

MySQL COUNT() function with group by on multiple

columns

The following MySQL statement returns number of publishers in each city for a country. Grouping operation is performed on country and pub_city column with the use of GROUP BY and then COUNT() counts the number of publishers for each groups.

Sample table : publisher

Code

view plain print ?

1. SELECT country,pub_city,COUNT(*)  2. FROM publisher    3. GROUP BY country,pub_city;   

Output

PHP script

view plain print ?

Page 156: Mysql

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-count-with-group-by-on-multiple-columns- php mysql ex

amples | w3resource</title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Taking an account of how many authors are there with respe

ct to countries and cities (in author table)  : </h2>";  10. echo "<table border='1' style='border-collapse: collapse;borde

r-color: silver;'>";  11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='200' align='center'>Country</td><td width='20

0' align='center'>City</td><td width='200' align='center'>Number of authors</td>";  

13. echo "</tr>";  14. include("../dbopen.php");  15. $result = mysql_query("SELECT country,pub_city,COUNT(*) FROM p

ublisher GROUP BY country,pub_city");  16. while($row=mysql_fetch_array($result))  17. {  18. echo "<tr>";  19. echo "<td align='center' width='200'>" . $row['country'] . "</

td>";  20. echo "<td align='center' width='200'>" . $row['pub_city'] . "<

/td>";  21. echo "<td align='center' width='200'>" . $row['COUNT(*)'] . "<

/td>";  22. echo "</tr>";  23. }  24. echo "</table>";  25. ?>  26. </body>  27. </html>  

MySQL COUNT(DISTINCT) function MySQL COUNT(DISTINCT) function has average rating 6 out of 10. Total 6 users rated.

<<Previous Next>>

Page 157: Mysql

Description

MySQL COUNT(DISTINCT) function returns a count of number rows with different non-NULL expr values.

Syntax

COUNT(DISTINCT expr,[expr...])

Where expr is a given expression.

MySQL Version : 5.6

Example : MySQL COUNT(DISTINCT) function

The following MySQL statement will count the unique 'pub_lang' and average of 'no_page' up to 2 decimal places for each group of 'cate_id'.

Sample table : book_mast

Code

view plain print ?

1. SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)  2. FROM book_mast  3. GROUP BY cate_id;  

Output

PHP script

Page 158: Mysql

view plain print ?

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  

2. <html xmlns="http://www.w3.org/1999/xhtml">  3. <head>  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" />  5. <title>example-count-with-distinct- php mysql examples | w3resource<

/title>  6. </head>  7. <body>  8. <?php  9. echo "<h2>Counting the unique language of publishing and average num

ber of pages up to two decimal places within each group of category id :</h2>";  

10. echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";  

11. echo "<tr style='font-weight: bold;'>";  12. echo "<td width='100' align='center'>Category id</td><td width

='100' align='center'>Unique language of publishing</td>  13. <td width='100' align='center'>Average number of pages up to t

wo decimal places</td>";  14. echo "</tr>";  15. include("../dbopen.php");  16. $result = mysql_query("SELECT cate_id

,COUNT(DISTINCT(pub_lang)),  17. ROUND(AVG(no_page),2)  18. FROM book_mast GROUP BY cate_id");  19. while($row=mysql_fetch_array($result))  20. {  21. echo "<tr>";  22. echo "<td align='center' width='200'>" . $row['cate_id'] . "</

td>";  23. echo "<td align='center' width='200'>" . $ro

w['COUNT(DISTINCT(pub_lang))'] . "</td>";  24. echo "<td align='center' width='200'>" . $ro

w['ROUND(AVG(no_page),2)'] . "</td>";  25. echo "</tr>";  26. }  27. echo "</table>";  28. ?>  29. </body>  30. </html>