Wednesday, 29 August 2012

Other SELECT commands

There are other commands that can be used with the SELECT statement, such as sorting distinct values, retrieving data from multiple tables and sub-queries. They can be used with or without the WHERE condition

Note: When using a sub-query in a WHERE condition, the sub-query must only return one result.

Format

Sorting query results in ascending order by attribute
SELECT  <attribute> FROM table ORDER BY attribute;

Sorting query results in descending order by attribute
SELECT  <attribute> FROM table ORDER BY attribute DESC;

Show only unique values of an attribute
SELECT DISTINCT attribute FROM table;

Show attributes from multiple tables (pk - primary key, fk - foreign key)
SELECT <attribute> FROM < list of tables> WHERE table1.pk=table2.fk;

Using sub-queries to retrieve results from another source
SELECT <attributes> FROM < SUB_QUERY>;
SELECT <attributes> FROM table WHERE attribute = < SUB_QUERY>;

No comments:

Post a Comment