Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SQL - Select

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

DBS211

STRUCTURED QUERY LANGUAGE (SQL)

1
Structured Query Language (SQL)

• Structured Query Language (SQL) is a database language designed for


managing data held in a RDBMS
• SQL Statements:
• SQL Statements are not case sensitive.
• SQL Statements can be on one or more lines.
• Keywords cannot be abbreviated or split across lines.
• Clauses are usually placed on separate lines.
• The order of clauses are important.
• Tabs and indents are used to enhance readability.
• A SQL statement is either completely succeeds or completely fails.
2
SQL Statements
SELECT Data retrieval Retrieves data from the database
SELECT Data manipulation Enters new rows, changes existing rows, and removes
INSERT language (DML) – unwanted rows from tables in the database
UPDATE Create/Insert,
DELETE Read/Select, Update,
Delete (CRUD)
CREATE Data definition Sets up, changes, and removes data structures from tables
ALTER language (DDL)
DROP

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

• Procedural Language is an Extension to SQL with


design features of programming language.

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

SELECT * | { [DISTINCT] column | expression [alias], …}


FROM table_name;

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.

SELECT FirstName, LastName, (5000 + 100) * 12


FROM Employees; = 61200

SELECT FirstName, LastName, 5000 + 100 * 12

FROM employees; = 6200

7
Defining a Null Value
• Columns that are defined as NOT NULL or PRIMARY KEY can
not contain a null value

• Arithmetic expressions containing a null value evaluate to null.

• Oracle converts a blank string ('') to 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

SELECT ProductName AS ProductName, msrp,


msrp * 1.1 AS MSRPIncrease
FROM products;

SELECT ProductName AS "Product Name",


msrp, msrp * 1.1 AS "MSRP Increase"
FROM products;
9
Concatenation
• Concatenation operator is represented by two vertical bars (||)
• Concat() concatenates two string values.
• You can use columns, arithmetic expressions, or constant values.
• Date and character literal values must be enclosed within single quotation
marks
SELECT FirstName || ' is ' || JobTitle AS "Employee"
FROM employees;

SELECT FirstName || ', It''s assigned Manager ID:' || ReportsTo


FROM employees;

SELECT concat(concat(FirstName, ' is '), JobTitle) AS "Employee"


FROM employees; 10
Eliminating Duplicate Rows

• The default display of queries is all rows, including duplicate rows.


• Use DISTINCT keyword to retrieve unique values.

SELECT DISTINCT ReportsTo


FROM employees;

SELECT DISTINCT JobTitle


FROM employees;

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

CHAR(s) Fixed-length character value of size s

13
Limiting Rows Selected
SELECT [DISTINCT] { * | column [alias], …}
FROM table_name
[WHERE condition(s)];

• The WHERE clause consists of three elements:


• Column name
• Comparison operator
• Column name, constant, or list of values

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

SELECT FirstName, LastName, JobTitle


FROM employees
WHERE FirstName = 'Jeff';

15
Comparison Operators
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to

< Less than


<= Less than or equal to
<>, !=, ^= Not equal to

…WHERE hiredate = '01-JAN-95'


…WHERE salary >= 1500
…WHERE lastname = 'SMITH'

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 OrderNumber, OrderDate, ShippedDate, Status


FROM orders
WHERE OrderNumber IN (10100, 10110, 10115);

SELECT EmployeeNumber, FirstName, LastName, ReportsTo


FROM employees
WHERE LOWER(LastName) IN ('jones', 'fixter');

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.

SELECT LastName, ReportsTo


FROM employees
WHERE ReportsTo IS NULL;

SELECT LastName, ReportsTo


FROM employees
WHERE ReportsTo IS NOT NULL;

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

AND Returns TRUE if both component conditions are TURE

OR Returns TRUE if either component condition is TRUE

NOT Returns TRUE if the following condition is FALSE

21
Using the AND Operator
• Both simple conditions must return True

SELECT EmployeeNumber, LastName, JobTitle, OfficeCode


FROM employees
WHERE OfficeCode >= 3 AND
LOWER(JobTitle) = 'sales rep';

AND TRUE FALSE UNKNOWN


TRUE TRUE FALSE UNKNOWN
FALSE FALSE FALSE FALSE
UNKNOWN UNKNOWN FALSE UNKNOWN

22
Using the OR Operator
• One of simple conditions must return True.

SELECT EmployeeNumber, LastName, JobTitle, OfficeCode


FROM employees
WHERE OfficeCode >= 3 OR
LOWER(JobTitle) = 'sales rep';

OR TRUE FALSE UNKNOWN


TRUE TRUE TRUE TRUE
FALSE TRUE FALSE UNKNOWN
UNKNOWN TRUE UNKNOWN UNKNOWN

23
Using the NOT Operator
NOT TRUE FALSE UNKNOWN
FALSE TRUE UNKNOWN

SELECT LastName, ReportsTo


FROM employees
WHERE ReportsTo NOT IN (1002, 1056, 1143);

…WHERE job NOT IN (10, 11)


…WHERE salary NOT BETWEEN 1000 AND 1500
…WHERE lastname NOT LIKE ‘%a%’
…WHERE commission_pct IS NOT NULL

24
Rules of Precedence
• Override rules of precedence by using parentheses

Order Evaluated Operator


1 Arithmetic operators
2 Concatenation Operator
3 Comparison Conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 NOT
7 AND
8 OR

25
Rules of Precedence (cont’d)
• Use brackets to change the default order of Precedence

SELECT LastName, JobTitle, ReportsTo


FROM employees
WHERE LOWER(jobtitle) = 'sales rep' OR
LOWER(JobTitle) LIKE 'sales manager%' AND
ReportsTo = 1056;

SELECT LastName, JobTitle, ReportsTo


FROM employees
WHERE (LOWER(JobTitle) = 'sales rep' OR
LOWER(JobTitle) LIKE 'sales manager%') AND
ReportsTo = 1056;

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;

• Sorting by Multiple Columns


SELECT CustomerName, State
FROM customers
ORDER BY State NULLS FIRST, 1 DESC;

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

[ OFFSET offset ROWS] FETCH NEXT [ row_count | percent PERCENT ]


ROWS [ ONLY | WITH TIES ]

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;

• Use TOP-N Query with an IN-LINE view to get correct result.


SELECT *
FROM (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

• Character functions can be:


• Case conversion functions
• Character manipulation 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

SELECT LOWER('SQL Course') FROM DUAL; sql course


SELECT UPPER('SQL Course') FROM DUAL; SQL COURSE
SELECT INITCAP('SQL Course') FROM DUAL; Sql Course

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

TRUNC(column|expression, n) Truncates the column, expression, or value to n decimal places or if n is


omitted, no decimal places(if n is negative, numbers left of the decimal
point are truncated to zero

• SELECT ROUND(45.926, 2) FROM DUAL; 45.93


• SELECT TRUNC(45.926, 2) FROM DUAL; 45.92

36
NUMBER Functions – ROUND( )
• Rounds the column, expression, or value to n decimal places

SELECT ROUND(45.923, 2),


ROUND(45.923, 0), ROUND(45.923, -1)
FROM DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)


45.92 46 50

37
NUMBER Functions – TRUNC( )
• Truncates the column, expression, or value to n decimal places

SELECT TRUNC(45.923, 2),


TRUNC(45.923, 0), TRUNC(45.923, -1)
FROM DUAL;

TRUNC(45.923,2) TRUNC(45.923,0) TRUNC(45.923,-1)


45.92 45 40

38

You might also like