Showing posts with label select. Show all posts
Showing posts with label select. Show all posts

Wednesday, June 4, 2008

Using ORDER BY in SQL to sort data

Getting data sorted in advance is a wonderful feature of SQL. This means your program might not have to define it's own specific way to sort the information in your database, which can might life a lot simpler when programming in a complex language. Let's say we have a list of people.

Name,Age,Level,Job
"John Smith","39","Level 4","Computer Scientist"
"Jack Williams","22","Level 2","Mathemetician"
"John Black","29","Level 8","Artist"

You want to order them by age? Simple enough. SELECT Name,Age,Level,Job FROM People ORDER BY Age. This will return the lowest age first, and all the data with the person, etc, so you will get Williams, then Black, then Smith.

Wednesday, May 28, 2008

Searching through database with SELECT... WHERE

SELECT Name FROM Persons WHERE Age < 18

Let's say your website is now only for people 18 and older. You need to find everyone in your database that is under 18, so you can remove them or something. First, you use a select statement to return the information of all people under 18. How? With a WHERE age < 18. This returns anybody who's age is less than 18. You can also find other things, for example if you just want people named "John Smith" do this:

SELECT Name,Age,Level FROM Persons WHERE Name='John Smith'

Querying a database with SELECT

The thing done most often to databases is querying. This means asking the database for a row of information, called a 'record'. This contains one joined set of values, for example "John Smith" "19" "Level 5" would correspond to values such as "Name", "Age", "Rank" in the database.

SELECT Name FROM Persons

That select query would then return a 'result set' of all names within the database, such as "John Smith" "Jake Prower" and "Mike Huggabee".

SELECT Name,Age FROM Persons

If you need to get more information, such as Name and Age, then do something like the above, which will return a couple sets of data (arrays, you would probably call them), one set with the Names, and the other with the Ages (but they will be linked in those sets).

SELECT DISTINCT Name FROM Persons

If you use the DISTINCT keyword, sql will only return a set of unique names. You won't get two "John Smith"s.