mercredi 23 janvier 2013
SQL: subqueries
Do you like this story?
In this short post, I would like to introduce the concept of subqueries in SQL.
In SQL the principle is identical.
In order to explain what I'm saying, let's try an example.
Consider we have a table (rankingTable) with a column (rank) with numbers that indicates a ranking. The higher the number, the higher the rank.
We can get the highest rank with a query like:
SELECT MAX(rank) as highestRank
FROM rankingTable
Now we can use the above query and use it in a WHERE clause:SELECT *
FROM rankingTable
WHERE rank = (SELECT MAX(rank) FROM rankingTable)
First, the subquery is executed, then the main query is executed considering the results of the subquery.In general a subquery syntax can be explained like:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
The above is a SELECT statement, but subqueries can be used with INSERT, UPDATE and DELETE statements.Subqueries are really powerful and the above examples are just a way of using them. In fact the subquery is in the WHERE clause. However they can be used directly in the SELECT statement or in the FROM clause as well.
As an example for the SELECT statement:
SELECT (number/(SELECT SUM(number) FROM table)) as myNumber
FROM table
The result of the above is myNumber which represents each number divided by the sum of all numbers.That's all for today. I hope you find the above info interesting enough.
This post was written by: Franklin Manuel
Franklin Manuel is a professional blogger, web designer and front end web developer. Follow him on Twitter
Inscription à :
Publier les commentaires (Atom)
0 Responses to “SQL: subqueries”
Enregistrer un commentaire