0% found this document useful (0 votes)
4 views

Lecture 4 - Introduction to SQL I

This document provides an introduction to SQL SELECT statements, focusing on the structure and requirements of tables, as well as the syntax and capabilities of SELECT statements for querying data. It covers key concepts such as projection, selection, joining, and the use of various operators and clauses, including WHERE, DISTINCT, and LIKE. Additionally, it explains how to handle null values, create aliases, and perform arithmetic operations within SQL queries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 4 - Introduction to SQL I

This document provides an introduction to SQL SELECT statements, focusing on the structure and requirements of tables, as well as the syntax and capabilities of SELECT statements for querying data. It covers key concepts such as projection, selection, joining, and the use of various operators and clauses, including WHERE, DISTINCT, and LIKE. Additionally, it explains how to handle null values, create aliases, and perform arithmetic operations within SQL queries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

WORKING WITH TABLE

DATA: AN INTRODUCTION
TO SQL SELECT
STATEMENTS (PART 1)
OPIM 5272: BUSINESS PROCESS MODELING AND DATA
MANAGEMENT
UGO ETUDO PH.D
WHAT IS A TABLE?

• A 2-dimensional structure consisting of rows and columns


• The intersection of a row and a column is a field
• A field may contain an atomic value or it may be null
• Row, Record, Entity
Instance
WHAT IS A TABLE? • Column, Attribute
• Field
WHAT IS A TABLE?

• Under the relational model, a table (alternatively called a


relation) must meet strict requirements:
• It must have a unique name
• Each row must be unique
• It must contain only atomic values (no multivalued attributes)
• The order of rows must be irrelevant
• The order of columns must be irrelevant
SELECT STATEMENT DEFINITION

• SELECT statements are a set of instructions that result in the


creation of temporary tables using information stored in the
database.
• In the vast majority of cases, SELECT statements return one
of three types of structure:
• Table (matrix)
• Column (vector)
• Field (scalar)
SELECT STATEMENT CAPABILITIES

• SELECT statements provide the following high level


capabilities:
• Projection: defining the columns that will be returned by the query
• Selection: defining the rows that will be returned by the query
• Joining: specifying a condition by which two or may tables may be
brought together

• The precise ways in which a SELECT statement projects,


selects and joins can be finely tuned using several
specialized commands
BASIC SYNTACTICAL STRUCTURE

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


FROM table;
BASIC SYNTAX
• SELECT clause : used for projection
• FROM clause : used to identify the table(s) from which data is to be drawn (I refer to
the table(s) as the query’s table space
• DISTINCT keyword : eliminates duplicate rows (a form of selection)
• column | expression : specifies column names in the table space given by the FROM
clause or functions (expressions) that operate upon columns in the table space given
by the FROM clause
• * keyword : read as “all” this keyword projects all columns in the table space given by
the FROM clause
• alias : rename the projected columns or expressions in the resultant, temporary table
USING *

• SELECT * FROM departments;


PROJECTING SPECIFIC COLUMNS

SELECT cust_first_name, cust_last_name


FROM customers;
STYLE AND SYNTAX NOTES

• SQL Statements are case-insensitive


• SQL Statements ignore the new-line character (they can arbitrarily span multiple
lines)
• Keywords (e.g. clause names, column names, table names, function names) cannot be split
across lines

• You may notice that clause names, and SQL reserved keywords tend to be
capitalized – this is a stylistic choice, I advise that you follow it
• Try to place clauses on new lines
• Always terminate your SQL statements with a semicolon. This is especially import
when you are running SQL scripts (ordered collection of SQL statements)
PROJECTION ARITHMETIC (EXPRESSIONS)

• We can create expressions with number and date data


• The standard set of arithmetic operators apply:
• + : Add (works with date data)
• - : Subtract (works with date data)
• * : Multiply
• / : Divide
PROJECTION ARITHMETIC

• Lets find the monthly salary of all employees:


SELECT first_name, last_name, salary, ROUND(salary/12, 2)
FROM employees;
PROJECTION ARITHMETIC

• Note that the standard rules of arithmetic precedence apply:


multiplication and division are evaluated before addition and
subtraction
• Precedence can be enforced using parenthesis – expressions within
the parenthesis are evaluated first

• When operators are of the same priority, they are evaluated


from left to right (first come first serve)
ARITHMETIC PRECEDENCE

Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication,
division
+, -, || addition,
subtraction,
concatenation
comparison
NOT logical negation
AND conjunction
OR inclusion
PROJECTION ARITHMETIC

• Assume that the salary column is a monthly salary. Let us calculate annual
salary of employees plus a $100 bonus
SELECT last_name, first_name, salary, salary*12+100
FROM employees;
SELECT last_name, first_name, salary, salary*(12+100)
FROM employees;
SELECT last_name, first_name, salary, 12*(salary+100)
FROM employees;
NULL

• Null is the absence of a value


• It is not the same as a zero or a space
• It is a specific definition
• Any arithmetic performed on a field with a null value will result in null
The example below illustrates this last point:
SELECT last_name, salary+commission_pct
FROM employees;
ALIAS ON COLUMNS

• The longer our expressions become, the more unwieldy our column
headings (in the virtual table) become
• As a result, we may want to rename column headings in the output of a
SELECT statement
• We can use the AS operator or a space to indicate that the keyword
following an expression or column name is an alias
• When an alias contains reserved terms (for instance an alias USER),
spaces or needs to be case sensitive we can wrap it in double quotes
• Single and double quotes serve different purposes in Oracle
ALIAS ON COLUMNS

• No Alias
SELECT first_name, last_name, salary, ROUND(salary/12, 2)
FROM employees;
ALIAS ON COLUMNS

• With Alias
SELECT first_name "First", last_name "Last", salary,
ROUND(salary/12, 2) AS "Monthly Salary"
FROM employees;
ALIAS ON COLUMNS

• If you attempt the previous example without the double


quotes around “First” and “Last” you will encounter an error
• First and Last are reserved keywords in Oracle’s flavor of SQL.
They are used for cursor traversal, a topic for a much later
lecture!
• Attempt the query using single quotes – an error
• Single quotes in Oracle are used to pass literals and cannot be used to
name database objects
CONCATENATION

• At this point, I’m usually being asked “how do I put both the first and last
name of an employee in the same field”
• The concatenation operator, ||, allows us to define expressions that link
strings (and other data types) drawn from two or more columns into a single
column
• Let’s try to place the first and last names of employees, along with their
salaries into a single column
SELECT first_name || last_name || salary AS earnings
FROM employees;
CONCATENATION
SELECT first_name || last_name || salary AS earnings
FROM employees;
• What’s wrong with this picture?
• The concatenation operator also allows us to work with literals!
• We may rewrite the query above:
SELECT first_name ||' '|| last_name ||' earns a salary of '|| salary AS
earnings
FROM employees;
CONCATENATION

• You may want to format the output of your SELECT statements in


more natural language
• From the previous example, you may want each field to state
“Steven King’s Salary is 24000” note that we’ve included a single
quote, an apostrophe in the string.
Option 1
SELECT first_name || ' ' ||last_name || ''s Salary is ' || salary
FROM employees;
CONCATENATION

Option 2 Use the Quote operator (q)


SELECT first_name || ' ' ||last_name || q'<'s Salary is >' || salary
FROM employees;

• The angle brackets are delimiters of my choice. (other options include {}, []) You can
choose some other delimiter. Those delimiters enable the SQL interpreter
differentiate between a quote signifying a literal and a literal quote!
DISTINCT

• The DISTINCT keyword ensures that each record returned from the
query is unique. Say you would like to have a list of manager_ids and
you do not want this list to contain duplicates:
SELECT DISTINCT manager_id
FROM employees;
• The DISTINCT keyword must appear immediately after the SELECT
keyword. If you specify multiple columns after the DISTINCT keyword,
only unique combinations of those columns will be returned.
THE WHERE CLAUSE

• What if we wanted to retrieve all employees who earn above


a particular salary?

SELECT * | { [DISTINCT] column | expression


[alias],…}
FROM table
[WHERE condition(s)];
THE WHERE CLAUSE

• WHERE clause : a row-wise operation that checks each row returned by


the query against a Boolean condition
• condition : may include column names, expressions, constants
(literals), comparison and logical operators that evaluate to one of
TRUE or FALSE
• We construct a WHERE clause using conditions which consist of:
• Column name (or function) + comparison operator + column name, literal, or
vector of literals
• We can chain conditions together using logical operators e.g. AND, OR, etc…
COMPARISON OPERATORS

Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
BETWEEN ____ AND ____ Between two values (inclusive
IN (__ , __ , __) Matches any item within the list of
values
LIKE Contiguous match on character pattern
IS NULL Is a null value
LOGICAL OPERATORS

Operator Meaning
AND Evaluates as TRUE if both component conditions are true
OR Evaluates as TRUE if either component (or both) conditions is
true
NOT Evaluates as TRUE if the condition is false

AND & OR can be used to chain conditional expressions in the


WHERE clause. NOT cannot be used for the purpose, it is simply
negation.
You cannot
WHERE CLAUSE EXAMPLE use column
alias’ in
WHERE
Example 1: clause

SELECT first_name, last_name, salary, job_id, department_id


FROM employees
WHERE department_id = 90;
Example 2:
SELECT first_name, last_name, salary, job_id, department_id
FROM employees
WHERE job_id = 'AC_ACCOUNT';
A NOTE ON DATES
Before working with dates in our examples:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YY';

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';


COMPARISON OPERATORS

• Which employees were hired after January 13th 2006?


SELECT first_name, last_name, hire_date
FROM employees
WHERE hire_date > '13-JAN-06';
BETWEEN OPERATOR

• What is the difference between these two queries?


SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2000 AND 3000;

SELECT last_name, salary FROM employees


WHERE salary > 2000 AND salary < 3000;
LIKE OPERATOR & THE WILDCARDS (_,%)

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary >= 10000
OR job_id LIKE '%MAN%';

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE last_name LIKE '%ar';
LIKE OPERATOR & THE WILDCARDS (_,%)

SELECT last_name, salary


FROM employees
WHERE last_name LIKE ‘_o%’;
The above query matches employees with last names that
have as their second character, ‘o’ allowing for any number of
strings to be matched after ‘o’
IN OPERATOR

• Say we would like to return a list of employees who are


managed by a set of three managers (100, 101, 201):
SELECT employee_id, last_name, salary, manager_id
FROM employees
WHERE manager_id IN (100, 101, 201);
THE NULL OPERATOR

• Say we would like to know which employees have no managers:


SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL;
• Say, alternatively, we would like to know only those employees who have
managers:
SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NOT NULL;

You might also like