Queries Basics

queryThe most common operation in SQL is the query, which is performed with the SELECT statement. A typical query has the form:

SELECT Columns
FROM Tables
WHERE Conditions

The result of a SQL query is a new table called the result set. Let’s see how to use each clause of a query.

SELECT

Indicates a list of columns to be included in the result set.

  • Use comma to select more than one column.
  • Use asterisk (*) to select all the columns of the queried table(s).
    E.g. SELECT * FROM Students.
  • Use AS statement to name columns of the result set. This can be useful when column names are big or not very readable.
    E.g. SELECT StudentName AS Name
  • Use DISTINCT keyword to return only different values from queries that may contain duplicated values.
    E.g. SELECT DISTINCT Program FROM Students.

FROM

Indicates the table(s) from which data is to be retrieved. Tables can be named using aliases to make them easier to reference, especially when table names are long or when querying more than one table. For example:

SELECT * FROM Students AS S
or
FROM Students S

WHERE

Eliminates all rows from the result set that don’t meet a condition or a set of conditions. Conditions are expressed using column names from the tables queried and operators:

Operator Values Example
Arithmetic operations +, -, *, /
Comparison Operators =, <>, <, >, <=, >= WHERE Program = ‘MMOR’
Logical operators AND, OR, NOT WHERE Program = ‘MMOR’ AND Year = 2014
WHERE NOT Program = ‘MMOR’

ORDER BY

This optional clause sorts the results in a specific order, ASC for ascending order or DESC for descending order:

SELECT *
FROM Students
ORDER BY StudentName DESC

Ascending order is the default option and will be assumed if it’s not specified.

SELECT *
FROM Students
ORDER BY Year

You can state multiple columns separated by comma to sort by multiple columns.

SELECT *
FROM Students
ORDER BY Year, Age DESC

You can find other examples with these statements here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.