ImplementationUsing AND, OR, <, > and = operators

Structured Query Language is used to allow database developers to generate queries and interrogate the data held in a database. SELECT, FROM, WHERE, AND and OR are key areas of SQL.

Part ofComputing ScienceDatabase design and development

Using AND, OR, <, > and = operators

It is possible to use the AND, OR <, > and = operators with a WHERE clause. This will refine a search further.

AND

Using AND allows the database developer to specify more than one condition that must be met. In this example, two conditions are specified.

SELECT PupilID, First Name, Surname, Class FROM Pupil
WHERE Class = ‘1T1’ AND Surname = ‘McNamee’;

This would return:

PupilIDFirst NameSurnameClass
0004JamesMcNamee1T1
0007AmyMcNamee1T1
PupilID0004
First NameJames
SurnameMcNamee
Class1T1
PupilID0007
First NameAmy
SurnameMcNamee
Class1T1

OR

Using OR allows the database developer to specify a series of conditions, where only one of the conditions needs to be met.

SELECT PupilID, First Name, Merit Points
FROM Pupil
WHERE First Name = ‘Amy’ OR Merit Points > 60;

This would return:

PupilIDFirst NameMerit Points
0001Nisa74
0003Amy55
0004James88
0007Amy63
0009Beatrice77
0010Tom91
PupilID0001
First NameNisa
Merit Points74
PupilID0003
First NameAmy
Merit Points55
PupilID0004
First NameJames
Merit Points88
PupilID0007
First NameAmy
Merit Points63
PupilID0009
First NameBeatrice
Merit Points77
PupilID0010
First NameTom
Merit Points91

Even though one of the pupils named Amy has less than 60 merit points, the record is still returned because of the OR operator. The first condition means that all records containing ‘Amy’ in the First Name column/field will be returned regardless of whether the second condition is met.

Operators

<, > and = are all operators

<Less than
>Greater than
=Equals
<
Less than
>
Greater than
=
Equals

In the example above, > was used to return all results greater than a particular mark. < and = can be used in the same way

To show all records containing 'Amy' in the First Name column OR all records containing results less than 60 points in the Merit Points column, you would change the third line of code to:

WHERE First Name = ‘Amy’ OR Merit Points < 60;

To show all records containing 'Amy' in the First Name column OR all records containing results equal to 60 points in the Merit Points column, you would change the third line of code to:

WHERE First Name = ‘Amy’ OR Merit Points = 60;