SQL AND & OR

previous next


AND & OR

AND and OR join two or more conditions in a WHERE clause.

The AND operator displays a row if ALL conditions listed are true. The OR operator displays a row if ANY of the conditions listed are true.

Syntax

SELECT columnName(s) FROM tableName WHERE condition AND|OR condition;

 


Some Examples

The "Books" table:

Title

Author

Publisher

Year

الدورة الدموية

إبن النفيس

دار العلم

1650

Java 2

L. Johnston

Fast Press

2002

Linux and Unix

J. Sam

Fast Press

2004

Operating Systems

M. Stone

Coriolis

2005

Web Programming

K. Yariv

East Edition

2005

XML Language

M. Salim

Knowledge Press

2000

Example

Use AND to display each book with the year of publication is 2005 and the publisher is "East Edition":

SELECT * FROM Books WHERE Year = 2005 AND Publisher = 'East Edition';

The result is:

Title

Author

Publisher

Year

Web Programming

K. Yariv

East Edition

2005

Example

Use OR to display each book with the year of publication is 2005 or the publisher is "East Edition":

SELECT * FROM Books WHERE Year = 2005 OR Publisher = 'East Edition';

The result is:

Title

Author

Publisher

Year

Operating Systems

M. Stone

Coriolis

2005

Web Programming

K. Yariv

East Edition

2005

Example

You can also combine AND and OR (use parentheses to form complex expressions):

SELECT * FROM Books WHERE (Year = 2005 OR Year = 2004) AND Publisher = 'Fast Press';

The result is:

Title

Author

Publisher

Year

Linux and Unix

J. Sam

Fast Press

2004

 


Test your SQL Skills

To test your SQL skills click here.


previous next