As you can see from the title, what we’re exploring here are the basics of SQL – Structured Query Language. Naturally, this won’t, then, be an exhaustive tutorial on SQL – that would require a book – and there are many already out there.
With SQL, we can query databases. It doesn’t matter whether the database is SQL Server, MS Access, MySQL, Oracle or any other. It just requires that the database is sql compliant, which, naturally, most commercially available databases these days, are.
The recommended methd for querying databases, in order to stop injection attacks, is parameterized queries….we won’t go into that in this tutorial, since a tutorial on that subject already exists.
The 4 basic types of queries we’re going to explore are:
Select
Insert
Update
Delete
Along with these 4 types, we’ll address a couple of clause types (Where and Order by)
Select Statement
I’d say that arguably, the most common use of SQL on the web is the SELECT statement. With the SELECT statement, we select data from the database and return the results to the user. The two most common forms are what I call the pure Select statement, and the qualified Select Statement. Here’s an example of a Select Statement in it’s purest, or most simple form:
Select FirstName, LastName, Phone from TableName
This query will return all the Firstname, LastName and Phone number for each record in the database, no matter how many records are in the database.
The other Select Statement I listed is the ‘qualified’ Select Statement. An example of this would use a ‘Where’ clause, like this:
Select FirstName, LastName, Phone from TableName’ Where LastName=’Jones’
As you probably expected, this will only return the FirstName, LastName and Phone for those records where the LastName is ‘Jones’.
Where clauses can contain multiple filtering sections also, using either ‘OR’ or ‘AND’. An example would be
Select FirstName, LastName, Phone from TableName’ Where LastName=’Jones’ OR LastName=’Smith’ OR FirstName=’Jim’
Another example would be:
Select FirstName, LastName, Phone from TableName’ Where LastName=’Jones’ AND FirstName=’Jim’
Insert Statement
Here, we would take user input and INSERT it into the table. We’ve all filled out forms with TextBoxes, RadioButtons, Checkboxes, etc.
Continues…