Learning Objectives – after this chapter you will be able to:
  • Create a table with CREATE TABLE following Oracle’s naming rules.
  • Choose suitable Oracle datatypes for columns.
  • Display a table definition with DESCRIBE.
  • Insert rows (all columns or selected columns) and understand NULL.
  • Retrieve rows with SELECT using projection, expressions, aliases, WHERE, ORDER BY, special operators and DISTINCT.
  • Edit the SQL buffer with SQL*Plus commands.
Creating a Table

Before creating a table, decide: what data it stores, its name (which should depict its content), its columns, the name, datatype and maximum length of each column, and the integrity rules to be implemented.

Creating the COURSES table
create table COURSES
( ccode         varchar2(5),
  name          varchar2(30),
  duration      number(3),
  fee           number(5),
  prerequisite  varchar2(100)
);
Output
Table created.
Rules for naming tables and columns
  • The name must begin with a letter (A–Z or a–z).
  • Letters, digits and the special characters _ $ # are allowed.
  • Maximum length is 30 characters.
  • It must not be an SQL reserved word, and no other object in your account may have the same name.
A table can contain up to 1000 columns in Oracle8 and above (Oracle7: 254 columns).
Oracle Datatypes
DatatypeDescription (as given in the notes)
VARCHAR2(len)Variable-length string of up to len characters; maximum 4000.
VARCHAR(len)Same as VARCHAR2, but use VARCHAR2 because Oracle may change the usage of VARCHAR in future.
CHAR(len)Fixed-length string, padded on the right with spaces; default width 1, maximum 2000.
NUMBER / NUMBER(p,s)Numbers (up to 40 digits plus decimal point and sign). p = maximum significant digits, s = digits to the right of the decimal point.
DATEDates from 1-1-4712 B.C. to 31-12-4712.
LONGVariable-length character data up to 2 GB; only one LONG column per table; cannot be used in functions, WHERE clause, indexing or subqueries.
RAW / LONG RAWLike VARCHAR2 / LONG but for binary data (sound, images).
CLOB, BLOB, NCLOBLarge character and binary objects, up to 4 GB each (see Chapter 21).
BFILEPointer to an external file; only the file name is stored in the column.
ROWIDUnique number used by Oracle to identify each row.
NCHAR / NVARCHAR2Same as CHAR / VARCHAR2 but support national language characters.
DESCRIBE and INSERT

DESC[RIBE] objectname is a SQL*Plus command that shows each column’s name, datatype and whether it can hold NULL. It works for tables, views, synonyms, functions and procedures.

Inserting rows
insert into courses
values ('ora','Oracle database',25,4500,'Knowledge of Windows');

insert into courses
values ('c','C Programming',25,3000,null);          -- NULL for an unknown value

insert into courses (ccode,name)
values ('odba','Oracle Database Administration');  -- other columns get NULL / default

commit;                                              -- make the changes permanent
  • Character and date values are enclosed in single quotes.
  • One INSERT ... VALUES inserts one row; repeat it for more rows (or use a subquery – Chapter 11).
  • DATE values are given as DD-MON-YY or DD-MON-YYYY. With a two-digit year the current century is used, so give four digits when needed.
  • NULL means a value that is not available or not known – it is neither 0 nor blank.
  • Issue COMMIT after inserting; uncommitted rows may be lost, e.g. on power failure.
SELECT: Projection, Expressions and Aliases
SELECT [DISTINCT | ALL] {* | expr [alias], ...} FROM [schema.]table [WHERE condition] [ORDER BY {expr | position | alias} [ASC | DESC], ...]
Projection with an expression and a column alias
select name, fee, fee * 0.15 discount
from courses;
Output
NAME                  FEE   DISCOUNT
-------------------- ----- ---------
Oracle database       4500       675
VB.NET                5500       825
C programming         3500       525
ASP.NET               5000       750
Java Language         4500       675
XML Programming       4000       600
  • Projection – selecting only some of the columns. * selects all columns.
  • Arithmetic operators + − * / may be used in expressions.
  • A column alias replaces the expression as the column heading.
  • A schema prefix (owner name) is needed only for tables of another account.
ORDER BY
  • Sorts the retrieved rows; the rows stored in the table are not changed.
  • Default order is ascending; use DESC for descending. Several columns may be given.
  • You can sort by column name, by column position in the select list (not in the table) or by alias.
  • ORDER BY must be the last clause of SELECT.
  • NULLs come last in ascending order and first in descending order.
Sorting on two columns and by column position
select name, duration, fee from courses
order by duration, fee desc;

select name, fee, fee * 0.15 from courses
order by 3;
Selection with WHERE and SQL Operators

The WHERE clause implements the selection operator – only rows satisfying the condition are returned.

OperatorMeaning
=   != or <>   >   >=   <   <=Relational (comparison) operators
AND, OR, NOTCombine conditions / negate a condition
BETWEEN v1 AND v2Value in the range, inclusive of both values (works with dates too)
IN (list)Value matches any value in the comma-separated list
LIKE pattern% = zero or more characters, _ = exactly one character
IS NULL / IS NOT NULLTests for null values
Using the special operators
select name from courses where duration between 20 and 25;
select name from courses where duration in (20,30);
select * from courses where ccode like '_b%' and prerequisite like '%programming%';
select * from courses where fee is null;      -- correct
select * from courses where fee = null;       -- never true: use IS NULL
String comparison and LIKE are case sensitive: 'ora' does not match 'ORA'. Oracle treats two NULLs as different values, so = NULL never matches.

SELECT DISTINCT fee FROM courses; returns each fee value only once.

Editing the SQL Buffer

The last SQL command entered is kept in the SQL buffer. SQL*Plus commands (such as DESCRIBE) are not stored in the buffer.

CommandPurpose
A[PPEND] textAdds text to the end of the current line
DELDeletes the current line
I[NPUT] [text]Adds line(s) after the current line
L[IST]Displays the buffer
R[UN] / /Runs the buffer (“/” does not display the command)
SAVE / GET filenameSaves the buffer to a file / loads a file into the buffer
START filenameExecutes the commands in a file (start file / command file)
EDIT [filename]Opens the host editor
HOST commandRuns an operating-system command
EXITQuits SQL*Plus
Key Takeaways
  • Column list = projection; WHERE = selection; ORDER BY = sorting of the result only.
  • Use IS NULL, never = NULL; BETWEEN is inclusive; LIKE uses % and _.
  • COMMIT makes inserted rows permanent.
Chapter 3 Notes (PDF)
ch3.pdf 15 pages 352 KB Open in PDF Viewer (Free Tool)

Your browser cannot show this PDF here. Open Chapter 3 Notes (PDF)

ch3.pdfKeys: ← → page · + − zoom · F full screen
Question / Answer (15 questions)

Moderate-level questions based on the Chapter 3 notes (PDF). Click a question to see the answer.

Answer : What data the table is supposed to store; the name of the table (which should depict its content); the columns of the table; the name, datatype and maximum length of each column; and the rules to be implemented to maintain the data integrity of the table.

Answer : The name must begin with a letter (A–Z or a–z); letters, digits and the special characters underscore (_), $ and # are allowed; the maximum length is 30 characters; it must not be an SQL reserved word; and no other object in the account may have the same name.

Answer : VARCHAR2(len) stores variable-length strings of up to len characters (maximum 4000). CHAR(len) stores fixed-length data: the string is padded on the right with spaces up to len characters; the default width is 1 and the maximum is 2000.

Answer : p is the maximum number of significant digits allowed and s is the number of digits to the right of the decimal point.

Answer : LONG stores variable-length character values up to 2 gigabytes, but only one LONG column is allowed per table, and LONG columns cannot be used in functions, in the WHERE clause of SELECT, in indexing or in subqueries.

Answer : DESCRIBE (abbreviated DESC) is an SQL*Plus command that displays the structure of an object – the name, datatype and whether the column can store null values for each column. The object may be a table, view, synonym, function or procedure.

Answer : List the columns after the table name, e.g. INSERT INTO courses (ccode, name) VALUES ('odba', 'Oracle Database Administration'). The remaining columns take a NULL value, or the default value if the column has a default.

Answer : COMMIT makes the changes permanent. Without COMMIT, the inserted rows might be lost if there is a power failure.

Answer : NULL means a value that is not available or not known. It is neither 0 nor blank nor any other known value. Oracle stores NULL when NULL is given as a value or when a column is omitted from an INSERT and has no default.

Answer : DATE values are entered in the format DD-MON-YY or DD-MON-YYYY, where MON is the first three letters of the month. If only two digits are given for the year, the current century is used (e.g. 99 is taken as 2099 when the current century is 2000), so four digits should be given when required.

Answer : A column alias is a name given to a column or expression in the select list, displayed as the column heading instead of the expression (e.g. fee * 0.15 DISCOUNT). The alias can be used in the ORDER BY clause, e.g. ORDER BY discount.

Answer : ORDER BY sorts the retrieved rows on the given column(s) in ascending (default) or descending (DESC) order; the rows in the table are not changed. It must be the last clause of SELECT. A column position refers to the position in the select list, not in the table. NULL values are placed at the end in ascending order and at the beginning in descending order.

Answer : BETWEEN checks whether a value is in a range including both limits, e.g. duration BETWEEN 20 AND 25. IN checks whether a value matches any value in a list, e.g. duration IN (20, 30). LIKE matches a pattern where % stands for zero or more characters and _ for exactly one character, e.g. name LIKE '%.NET%'.

Answer : Oracle treats two null values as two different values, so a condition such as fee = NULL is always false. To test for null, the IS NULL (or IS NOT NULL) operator must be used, e.g. WHERE fee IS NULL.

Answer : The SQL buffer is a memory area where SQL*Plus stores the last SQL command entered (SQL*Plus commands such as DESCRIBE are not stored). Commands include APPEND (add text to the current line), DEL (delete current line), INPUT (add lines), LIST (display buffer), RUN or / (execute), SAVE, GET, START and EDIT.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which operator is used to compare a column with a NULL value?

Show Answer

Correct Answer : D. IS NULL
NULL is never equal to anything, so the IS NULL / IS NOT NULL operators must be used.

Q2. What is the maximum number of characters that can be stored in a CHAR column (as per the notes)?

Show Answer

Correct Answer : A. 2000
CHAR is fixed-length with a maximum width of 2000; VARCHAR2 allows up to 4000.

Q3. How many LONG columns can a table contain?

Show Answer

Correct Answer : B. One
Only one LONG column is allowed per table.

Q4. In the LIKE operator, what does % stand for?

Show Answer

Correct Answer : C. Zero or more characters
% matches zero or more characters, whereas _ (underscore) matches exactly one character.

Q5. Which clause must always be the last clause of a SELECT command?

Show Answer

Correct Answer : D. ORDER BY
ORDER BY must always be the last of all clauses used in the SELECT command.

Bibliography/References

The chapter notes PDF is the course study material and is credited to its author below. The explanations, questions and MCQs on this page are original study aids written for this course from the topics covered in that PDF. The other works are cited for verification and further reading. Oracle, SQL*Plus and PL/SQL are trademarks of Oracle Corporation; other names belong to their respective owners.

  1. Srikanth, P. (n.d.). Oracle For Beginners (chapter notes – the PDF shown on each chapter page). Srikanth Technologies. http://www.srikanthtechnologies.com/
  2. Oracle Corporation. (n.d.). Oracle Database SQL Language Reference, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/
  3. Oracle Corporation. (n.d.). SQL*Plus User’s Guide and Reference, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/sqpug/
  4. Oracle Corporation. (n.d.). Oracle Database Concepts, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/cncpt/
  5. Elmasri, R., & Navathe, S. B. (2016). Fundamentals of Database Systems (7th ed.). Pearson.