Querying A Single Table

Overview

WHERE conditions

ORDER-BY: Sorting Data

Single Row Functions


Overview

       SELECT [DISTINCT] <column name, ...> FROM <table name,...>;

SELECT identifies what columns to retrieve; FROM identified which table to retrieve.

For example,

    SQL> SELECT id FROM employee;

         SELECT [DISTINCT] <column name, ...> FROM <table name> WHERE <conditions>;

           WHERE identifies condition(s). Multiple conditions are joined by operators such as AND  and OR.

             For example,

             SQL> SELECT id FROM employee WHERE name='scott' AND title='CFO';

        For example,

             SQL> SELECT * FROM employee WHERE name='scott';

        For example,

                SQL> SELECT id, name, salary * 12 + 100 FROM employee;

        For example,

        SQL> SELECT id, name AS "Name", salary * 12 AS "Annual salary" FROM employee;

        For example,

       SQL> SELECT name || ' is a ' || jobtitle AS 'Employee Detaisl' FROM employee;

   The output looks like:

                Employee Details

             ----------------------

                KING is a PRESIDENT

                SCOTT is a CFO

                JANE is a CTO

                ....

                12 rows selected.

 

        For example,

        SQL> SELECT DISTINCT dept_id FROM employee;


WHERE conditions

In WHERE conditions, the comparison operators are  >, >=, <, <=, =, <>, BETWEEN ... AND... , IN(list), LIKE, and IS NULL.   The logical operators are NOT, AND, and OR.

For example,

SQL> SELECT ename, sal FROM employee WHERE sal BETWEEN 1000 and 1500;

For example,

    SQL> SELECT ename, sal, dept_no FROM employee WHERE dept_no IN (10,20,30);

For example,

    SQL> SELECT ename FROM employee WHERE ename LIKE 'W_N%H';

For example,

    SQL> SELECT ename, sal FROM employee WHERE comment IS NOT NULL;

The rule of precedence is: all comparison operators are followed by NOT, then by AND, then followed by OR.


ORDER-BY: Sorting Data

Rows are sorted with the ORDER BY clause with two ordering options: ASC (ascending order, the default) and DESC (descending order).

The ORDER-BY clause comes last in the SELECT statements.

For example,

    SQL> SELECT ename, sal FROM employee ORDER BY sal DESC;


Single-Row Functions

Single row functions take zero or more number of  arguments and return only one value. They act on per data row. There are 4 types of SQL single-row functions:

1) string functions. Some are:

For example,

SQL> SELECT name, LENGTH(name) FROM EMPLOYEE

WHERE UPPER(name) = 'SCOTT';

2) number functions

3) date functions

For example,

SQL> SELECT name, (SYSDATE - hireDate) AS Days FROM EMPLOYEE;

WHERE UPPER(name) = 'SCOTT';

4) conversion functions