SQL - Select
SQL - Select
SQL - Select
1
Structured Query Language (SQL)
COMMIT Transaction Control Manages the changes made by DML statements. Changes to
ROLLBACK Language (TCL) the data can be grouped together into logical transactions.
SAVEPOINT
GRANT Data Control Gives or removes access rights to both the Oracle database
REVOKE Language (DCL) and the structures within it
3
PL/SQL
4
Capabilities of SQL SELECT
• Retrieves information from the database
• Using a SELECT, you can do following:
• Selection: choose the rows
• Projection: choose the columns
• Joins: bring data together that is stored in different tables
5
Arithmetic Expressions
• Create expressions on NUMBER and DATE data
( Date data type is used with additions and subtractions only).
• you can use arithmetic operators in any clause except the FROM clause
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
6
Operator Precedence
• Multiplication and division take priority over addition and subtraction
• Operators of the same priority are evaluated from left to right
• Parentheses are used to force prioritized evaluation and to clarify
statements.
7
Defining a Null Value
• Columns that are defined as NOT NULL or PRIMARY KEY can
not contain a null value
8
Defining a table/column Alias
• An Alias is a temporary name assigned to a table or column.
• An Alias exists for the duration of query.
• “AS” keyword is optional
• By default, alias headings appear in uppercase
• Requires double quotation marks if it contains spaces or special characters or is case
sensitive
11
SQL and SQL*Plus
• SQL Statements are stored and remain in SQL Buffer until you enter a new statement
SELECT column_name, nullable, data_type SQL SQL*Plus
FROM user_tab_columns A language An environment
WHERE table_name = 'CUSTOMERS'; ANSI standard Oracle proprietary
Keyword can not be abbreviated Keywords can be abbreviated
Statements manipulate data and Commands do not allow manipulation
table definitions in the database of values in the database
DESC CUSTOMERS
DESCRIBE CUSTOMERS
12
Datatypes
• SQL Datatypes
Datatype Description
NUMBER(p, s) Number value having a maximum number of
digits p, the number of digits to the right of the
decimal point s
VARCHAR2(s) Variable-length character value of maximum
size s
DATE Date and time value
13
Limiting Rows Selected
SELECT [DISTINCT] { * | column [alias], …}
FROM table_name
[WHERE condition(s)];
14
Character Strings and Dates
• Character strings and date values are enclosed in single quotation
marks, Number constants should not
• Character values are case sensitive and date values are format
sensitive
• The default date format is YYYY/MM/DD
15
Comparison Operators
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
16
Other Comparison Operators
Operator Meaning
BETWEEN … AND … Between two values (inclusive)
IN(list) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
• Between condition can be used with character, number, and Date datatypes
• You must specify the lower limit first
SELECT ProductName, msrp
FROM products
WHERE msrp BETWEEN 100 AND 150;
SELECT *
FROM payments
WHERE paymentdate BETWEEN TO_DATE('2003/05/09','YYYY/DD/MM') AND
TO_DATE('2004/11/08','YYYY/DD/MM’);
17
Using the IN Operator (Membership Condition)
• The IN operator can be used by any datatype
SELECT *
FROM payments
WHERE paymentdate IN (TO_DATE('2003/05/09','YYYY/DD/MM'),
TO_DATE('2004/11/08','YYYY/DD/MM'));
18
Using the LIKE Operator
• Use the LIKE operator to perform wildcard searches of valid search string values
• Search conditions can contain either literal characters or numbers
• % denotes zero or many characters
• _ denotes one character
SELECT LastName
FROM employees
WHERE UPPER(LastName) LIKE '_A%';
• You can use the ESCAPE identifier to search for “%” or “_”
SELECT *
FROM products
WHERE ProductCode LIKE '%4\_3%' ESCAPE '\';
19
Using the IS NULL Operator
• You cannot use Comparison Operators with NULL values.
• Use IS operator with NULL values.
20
Logical Operators
• A logical operator combines the result of two simple conditions to
produce a single result or to invert the result of a single condition
Operator Meaning
21
Using the AND Operator
• Both simple conditions must return True
22
Using the OR Operator
• One of simple conditions must return True.
23
Using the NOT Operator
NOT TRUE FALSE UNKNOWN
FALSE TRUE UNKNOWN
24
Rules of Precedence
• Override rules of precedence by using parentheses
25
Rules of Precedence (cont’d)
• Use brackets to change the default order of Precedence
26
ORDER BY Clause
• Sort rows with the ORDER BY clause
• ASC: ascending order, default
• DESC: descending order
• NULLS FIRST: shows all null on top of the list
• NULLS LAST: shows all null values at the bottom of the list
SELECT expr
FROM table_name
[WHERE condition(s)]
[ORDER BY {column, column Number, expr} [ASC | DESC]
[NULLS FIRST | NULLS LAST]];
27
ORDER BY Clause (cont’d)
• Sorting by Column Alias
SELECT OrderNumber, ProductCode,
QuantityOrdered * PriceEach Total
FROM orderdetails
ORDER BY Total;
28
DUAL Table
• SYSDATE is a function returning date. DUAL is a dummy table
used to view SYSDATE
• The DUAL table is owned by the user SYS and can be accessed by
all users. DUAL table contains one column, DUMMY, and one row
with the value X.
• The DUAL table is useful when you want to return a value once only.
SELECT SYSDATE
FROM DUAL;
29
Top-N Queries
• Used to return top or bottom “N” number of rows.
• Use Row Limiting clause
SELECT *
FROM products
ORDER BY productname
FETCH NEXT 5 ROWS ONLY;
SELECT *
FROM products
ORDER BY productname DESC
FETCH NEXT 5 ROWS ONLY;
30
Top-N Queries – using ROWNUM
SELECT productname
FROM products
WHERE ROWNUM <= 5;
• Below TOP-N Query does not return 10 rows.
SELECT DISTINCT productvendor
FROM products
WHERE ROWNUM <= 10
ORDER BY productvendor;
31
Single-Row Functions
• Manipulate data items
• Accept arguments and return one value
• Act on each row returned
• Return one result per row
• May return a data value of a different type than that referenced
• Can be nested
• Can be used in SELECT, WHERE, and ORDER BY clause
32
Character Functions
33
Case Conversion Functions
• Character values in a WHERE clause are case sensitive
• Case Conversion Functions can be used in WHERE Clause
Function Purpose
LOWER (column | expression) Converts alpha character values to lowercase
UPPER (column | expression) Converts alpha character values to uppercase
INITCAP (column | expression) Converts alpha character values to uppercase for the first letter of
each word, all other letters in lowercase
34
Character Manipulation Functions
• Examples:
Function Result
SELECT CONCAT('Good', 'String') FROM DUAL; GoodString
SELECT SUBSTR('String', 1, 3) FROM DUAL; Str
SELECT LENGTH('String') FROM DUAL; 6
SELECT INSTR('String', 'r') FROM DUAL; 3
SELECT REPLACE('Good_String', '_', ' ') FROM DUAL; Good String
35
Number Functions
• Number functions accept numeric input and return numeric values
Function Purpose
ROUND(column|expression, n) Rounds the column, expression, or value to n decimal places or if n is
omitted, no decimal places(if n is negative, numbers to left of the
decimal point are rounded
36
NUMBER Functions – ROUND( )
• Rounds the column, expression, or value to n decimal places
37
NUMBER Functions – TRUNC( )
• Truncates the column, expression, or value to n decimal places
38