Академический Документы
Профессиональный Документы
Культура Документы
SQL AND OR statement can be used with WHERE clause to list a set of records with
matching combination of a table. We can use AND OR SQL in query with NOT
combinationalso to filter out some records. This is our table
3 Arnold Three 55
We will apply AND command to display records of class Four with more than 70
mark.
WE can see the record returned is class= Four and mark is more than 70. Here both
the conditions are satisfied.
class avg_mark
Four 62.5000
Three 70.0000
Please see the SQL SUM command to know the details on uses of GROUP BY command and the
precautions.
We can add condition to the sql command to get our desired result. We can add one Where clause to the
query to consider records for which mark is more than some value ( say 55 )
SELECT avg( mark ) as avg_mark, class FROM student where mark > 55 GROUP BY class
avg_mark class
65.0000Four
85.0000Three
Please note that while changing the structure we must honor the existing constraints of the table. For
example if you decide to change a field to UNIQUE so it will not accept any duplicate records then if
some records with duplicate value are already there then system will not allow this and we will get error
message.
Same way we have to take care of other constraints
name varchar(50) No
class varchar(10) No
mark int(3) No 0
We will apply our alter table command to this table. We will change field name mark to student_mark
Here is the command
ALTER TABLE `student3` CHANGE `mark` `student_mark` INT( 3 ) DEFAULT '0' NOT NULL
With this alter table command the the field name mark will change to student_mark. This way we are
changing a field name only. Same way field type, default value and other properties of the field can be
changed. The new table structure is listed below.
name varchar(50) No
class varchar(10) No
student_mark int(3) No 0
Here in the message_table we already have one numeric filed msg_id and we have made it to UNIQUE
field so no duplicate data is allowed, if any duplicate data is there then we will receive error message.
This will display total records under the name total_record in the table student. Now we can add some
condition to this SQL to count the records with different conditions. Let us find out the number of students
in class Four in out table.
This will return the count of students in class four only. Here since we are displaying only one count for a
fixed class so we can use this way. We may require to display total of each class in a table so here we have
to use GROUP BY clause to display totals of all the tables
We can copy a table structure and records to another new table. The CREATE TABLE command will create a
table with same structure of the old table and add all the records. To export data to an existing table you can
use insert command.
This will create a new table class2 using the structure of the table class and will copy all the records from
table class to our new table class2.
This became more useful when we add conditions to this by using SQL WHERE command. This way
selectively we can transfer records to a new table. This is our table.
id name class mark
1 John Deo Four 75
3 Arnold Three 55
Related Tutorial
• Exporting data to table
• SQL Inner Join
• Number of Affected rows
• SQL Rename table
• PHP MySQL functions
With this command we will create a new table student2 of same structure of main table student and all the
records of class = Four will be copied to the new table. The new table student2 will have these records
CREATE TABLE IF NOT EXISTS student5 SELECT * FROM student WHERE class='Four'
Here the table will be created only if the table is not there before.
What we will do if we want to delete the old table and create a new table ?
The advantage of the above command over using a simple drop table command is here no error message
saying unknown table is generated even if the table is not there.
The above query will create a table sample_tb and add one column empno to it. But note that we have to
execute the above code. After execution we can find out whether the query has successfully executed or not
by using one if condition. If the query is not executed successfully then we will print the error message. If
table create process is successful then we will display a success message. Here is the code
As you can see we have created the table, with one column to store the data. Now what happens if the table
sample_tb already exists and we will try to create again? The system will generate an error message. So
before trying to create the table we will delete the table and then create again. ( Note: do this if your
requirement is there ). We also can't delete the table without checking the table is there or not. So we will
use one if exists command like this.
We can easily execute the create table query to generate the table. Note that this combination is used inside
many scripts where temporary tables are create and deleted at the end.
TRUNCATE `student`
This will remove all the records from the table. This is one way of deleting all the records from a table. Now
let us try to delete records based on some selection. Now let us delete records of the students who has got
mark less than 60. Here we are selectively deleting the records so we have to use WHERE clause to match
the selection.
Related Tutorial
• Number of Affected rows
• Copy data to new table
• SQL Left Join
• SQL Rename table
• PHP MySQL functions
DELETE FROM student WHERE mark < 60
This will delete records for which mark is less than 60. We can use all the WHERE clause we learned at SQL
WHERE page.
How to delete tabel or database ?
Here content is our table name and dt is one of the field of this table. By this command we can delete the
field dt of the table content.
Deleting a Table
We can use DROP command to remove a table inside the database. Now here is the code to delete the table
content.
The above command will remove the unique index associated with cat_id field of content_cat table
We can also use DROP command to delete a complete database. Here is the sample code
So using DISTINCT sql command we can avoid duplicate records in SELECT query
There is another related command sql group by which groups the data and brings the unique names. This
group by command is usually used along with count, average, minimum, maximum commands. Here we
will discuss sql distinct command only
We can also use WHERE command along with GROUP BY command in Mysql tables.
This will display the total records in each class. Like this
total_records class
1 Eight
3 Five
9 Four
2 Nine
10 Seven
7 Six
3 Three
Let us try to get the total number of girls records in each class by using GROUP BY query. Here we want to
filter our query for only girls so we have to use one WHERE clause to restrict the records using the sex
field. Here is the query.
Related Tutorial
• Copy data to new table
• SQL Left Join
• Number of Affected rows
• SQL Rename table
• PHP MySQL functions
SELECT count( * ) AS total_records, class FROM `student` WHERE sex='female' GROUP BY class
5 Four
1 Nine
5 Seven
5 Six
1 Three
We can use sql having command to add condition to the query. The advantage of using HAVING command
is it can be used in aggregate functions like count, max etc. We can't use SQL WHERE clause here. This
way we can add value to our select command as per requirement. Usually SQL HAVING command is used
in conjunction with group by command. Please read the sql group by command and SQL sub group by
command to know more about grouping the records.
Here is the full table with all the rows. On this we will apply the group by query
d_id name type category price stock
1Book1 Book Management 220 10
2Book2 CD Management 120 8
3Book3 Report Management 25 4
4Book4 Book Management 55 8
5Document1 Book Management 15 23
6Document2 CD Computers 80 45
7Document3 Report Computers 55 65
8Book5 Report Management 80 10
9Document4 CD Management 72 5
10Book 8 Book Computers 88 6
11Book 9 CD Computers 100 5
12Document5 Report Computers 85 8
13Book 10 Book Computers 150 5
Here is the SQL having command with group by command applied on the above table.
SELECT category, type , count( * ) as total FROM `documents` GROUP BY category, type
HAVING total < 3
This will display the total records in each group and sub group. Like this
category type total Related Tutorial
• SQL Group by
Computers Book 2 • Copy data to new table
Computers CD 2 • SQL Left Join
Computers Report 2 • SQL count
Management CD 2 • PHP MySQL functions
Management Report 2
Without the HAVING command you will get a result records like this below.
This will display the total records in each group and sub group. Like this
category type total
Computers Book 2
Computers CD 2
Computers Report 2
Management Book 3
Management CD 2
Management Report 2
Here the order of the fields need not be same as order in our MySQL table but the order we are specifying
by saying the filed names, that order we must maintain for values. We have to take care of the fields
where we have given NOT NULL or any other such requirements. Any violation of the field structure will
generate an error message.
Note that it is always a good practice to use filed name and value pairs while inserting records. If we
specify only the value by maintaining the order of the fields there will be problem in future once a new field
is added or removed from the table. So always write the query specifying field names and its values.
Here are some sql commands that will create a table and then add three records to it by using insert
command.
CREATE TABLE t1 (id int(11) NOT NULL default '0',name1 varchar(10) NOT NULL default '')
TYPE=MyISAM;
Related Tutorial
• SQL Insert using SET option
• SQL Select Query
• Copy data to new table
• SQL Left Join
In the table you can see every record has one manager id field known as m_id. We have used the unique
id of the employee in the m_id field to mark who is the manager for the employee.
To generate the manager table we have used this SQL
SELECT t1.id,t1.name as emp_name from emp as t1 INNER JOIN emp as t2 on t1.id=t2.m_id
Now let us use inner join to create one report on who is the manager of which employee. Check this SQL
SELECT t1.id, t1.name as emp_name, t2.name as manager FROM emp as t1 INNER JOIN emp as
t2 on t2.id = t1.m_id
10 Ronne John
--
-- Dumping data for table `emp`
--
INSERT INTO `emp` VALUES (1, 'John', 2);
INSERT INTO `emp` VALUES (2, 'Greek Tor', 1);
INSERT INTO `emp` VALUES (3, 'Alex John', 1);
INSERT INTO `emp` VALUES (4, 'Mike tour', 1);
INSERT INTO `emp` VALUES (5, 'Brain J', 3);
INSERT INTO `emp` VALUES (6, 'Ronald', 3);
INSERT INTO `emp` VALUES (7, 'Kin', 4);
INSERT INTO `emp` VALUES (8, 'Herod', 3);
INSERT INTO `emp` VALUES (9, 'Alen', 2);
INSERT INTO `emp` VALUES (10, 'Ronne', 1);
Here are two tables with some data. We will apply first sql where command to this table
The output of the above sql command will give records of MySQL table t1 for which there is a record
present in table t2 and linking is done by id field.
i n
d ame
1
1one1
2two1
We can display all the records of table t1 along with the (matching ) records of t2 if matching is found by
linking them in ID field. Here is the left join sql to display this and below that the output is listed.
SELECT t1.id, name1, t2.id, t2.name2 FROM t1 left join t2 on t1.id = t2.id
i n id n
d ame ame
1 2
1one1 1one1
2two1 2two2
3three1 NULLNULL
The above result shows a simple left join and its output. We may be interested to identify the the records
in table t1 for which there is no record present in table t2. Here we have to use left join and link the tables
by id field. Here is the query using left join and the out put is below that.
SELECT t1.id, name1 FROM t1 left join t2 on t1.id = t2.id where ISNULL(t2.id)
SELECT t1.id, name1 FROM t1 left join t2 on t1.id = t2.id where (t2.id) is null
i n
d ame
1
3three1
In the above result we have seen how the output works when we have to get records which are not
present in other table. Now let us find out the other way , we will get the record of table one for which
matching record exists in table 2. Here is the left join sql and below that the results of the query.
SELECT t1.id,name1,t2.id,t2.name2 FROM t1 left join t2 on t1.id = t2.id where NOT ISNULL(
t2.id )
SELECT t1.id,name1,t2.id,t2.name2 FROM t1 left join t2 on t1.id = t2.id where ( t2.id ) NOT is
null
i n i n
d ame d ame
1 2
1one1 1one1
2two1 2two2
We have specified here to return 10 records starting from 0 or from the first record. Same way we can ask
for 10 records starting from 20th record like this
SELECT * FROM `student` LIMIT 20, 10
This will return 10 records from 21st record. That is from 21st record to 30th record. Here is the output
This is quite useful for designing paging in any script. Paging is known as displaying records in page wise
with fixed number of records per page. There will be navigational menu to move between any pages and
go to next and previous pages. The best example of php paging is the way google display search results. It
display an easy navigational menu at the bottom of each search result page to go to next or previous page
or any other page.
Note that this is returning number of records and this has no connection with the id number field used
here. If the ID numbers are different then also the query will return 10 records starting from 21 record
( irrespective of the ID numbers ). If you want records with particular ID range specified then you have to
use sql between command.
Now let us apply this Locate query to our student table to search for the location of the string 'john'
The above command will return all the records of with the position of the searched string, if it is not found
then 0 is returned.
What happen if we apply MAX command to a non numeric field? We will get the record with highest alphabet.
But the best way to use MAX command is to apply it in a numeric field.
3 Arnold Three 55
We will apply the MAX command here like this to the field mark
max_mark
85
To display all fields like name, class, id along with the highest mark we can use like this. This will display one
record with all details of the highest mark
Using Group By
Now let us find out what is the maximum mark ( or highest ) in each class. Here we can use the Group By
command to find out the maximum mark obtained by each class
class max_mark
Four 75
Three 85
You can see above that maximum mark of each class is displayed. Since we have two class in our table so
the sql command has returned two class with highest mark in each of them. We have to use Group By clause
if we ask for the query to return any other field name other than the max. Otherwise system will generate
error.
Related Tutorial
• MySQL Min
• MySQL Avg
• MySQL Sum
We can add condition to the sql command to get our desired result. We can add one Where clause to the
query to consider records for a perticular class only ( say Four)
SELECT max( mark ) as maximu_mark, class FROM student where class ='Four' GROUP BY class
max_mark class
75 Four