SQL Tutorial - The Basics - Part I
The SQL SELECT statement is the fundamental building block used to retrieve data from a SQL database table.
The most basic uses of the SELECT statment are:
SELECT
*
FROM
table1
This retrieves all of the columns from table1, and:
SELECT
column1, column2, column3, column4
FROM
table1
Which retrieves only the named columns from table1.
The use of the wildcard symbol (*), to retrieve all of the columns should be used sparingly, there are significant performance benefits from explicitly specifying the colums to be returned.
The natural next step is to look at ways of filtering your results using the WHERE and AND commands, these allow you to return only the rows which match a certain criteria
The basic use of these commands is:
SELECT
column1, column2, column3, column4
FROM
table1
WHERE
column1 = 'abc'
The AND command can be used in conjunction with the WHERE command to add additional clauses to you query, you can use as many AND clauses as you wish:
SELECT
column1, column2, column3, column4
FROM
table1
WHERE
column1 = 'abc'
AND
column2 = 3
AND
column3 = 'yellow'
NB: As a general rule, numeric values should be placed within single quotation marks (') whereas number values are not.
The final keyword that we're going to cover in this introduction to the SQL SELECT commend is OR. The OR command is used to return rows from your database that match one of a number of different criteria, the OR command is used in conjuction with the WHERE command and can also be used alongside the AND command. The most basic use of the OR command is:
SELECT
column1, column2, column3, column4
FROM
table1
WHERE
column1 = 'abc'
OR
column1 = 'def'
The OR command can be used in conjunction with the AND command as follows:
SELECT
column1, column2, column3, column4
FROM
table1
WHERE
column1 = 'abc'
AND
column2 = 3
OR
column1 = 'abc'
AND
column2 = 3
Find out more in SQL Tutorial - The Basics - Part II.