Select To Order By

69

description

DBMS2

Transcript of Select To Order By

Page 1: Select  To  Order By
Page 2: Select  To  Order By

Introduction to SQL SQL Definition SQL Manipulation SQL Query SQL Control

Page 3: Select  To  Order By

SQL Order BySQL Order By

SQL AND & ORSQL AND & OR

SQL InSQL In

SQL BetweenSQL Between

SQL AliasesSQL Aliases

SQL JoinSQL Join

SQL ADVANCED

SQL CreateSQL Create

SQL DropSQL Drop

SQL AlterSQL Alter

SQL Group BySQL Group By

SQL Select IntoSQL Select Into

Page 4: Select  To  Order By

Stands for Stands for SStructured tructured QQuery uery LLanguageanguage

SQL is a standard computer language for SQL is a standard computer language for accessing and manipulating databases.accessing and manipulating databases.

Introduction to Introduction to SQLSQL

What What is is

SQL?SQL?

Defined by syntax and semantics.Defined by syntax and semantics.

SQL statements are not case SQL statements are not case sensitive.sensitive.

SQL statements can be one or more SQL statements can be one or more lines.lines.

SQL can retrieve, insert , delete or update SQL can retrieve, insert , delete or update records from a databaserecords from a database

SQL is easy to learnSQL is easy to learn

Page 5: Select  To  Order By

Statements for defining database or table

◦CREATE◦ALTER◦DROP

Page 6: Select  To  Order By

Statements to add, modify and remove rows intables.

◦INSERT◦UPDATE◦DELETE

Page 7: Select  To  Order By

Statements used to retrieve data.

◦SELECT

Page 8: Select  To  Order By

Statements used for database security.

◦GRANT◦REVOKE

Page 9: Select  To  Order By

SQL Create

The The CREATECREATE statement is used to statement is used to create a new database, table or index.create a new database, table or index.

Example 1:Example 1:

To create a database:To create a database:

CREATE DATABASE database_name

Example 2:Example 2:

To display the companies in reverse alphabetical To display the companies in reverse alphabetical order:order:

CREATE TABLE table_name

(

column_name1 data_type,

column_name2 data_type,

.......

)

Page 10: Select  To  Order By

Data Type Description

integer (size)int (size)smallint (size)tinyint (size)

Hold integers only. The maximum number of digits are specified in parenthesis.

Decimal (size, d)numeric (size, d)

Hold numbers with fractions. The maximum number of digits are specified in "size". The maximum number of digits to the right of the decimal is specified in "d".

Some Basic Data TypesSome Basic Data Types

SQL Create

Page 11: Select  To  Order By

char (size) Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis.

varchar (size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis.

date (yyyymmdd) Holds a date

Some Basic Data Types Some Basic Data Types (cont.)(cont.)

SQL Create

Page 12: Select  To  Order By

Create a database named DREAMHOMECREATE DATABASE Dreamhome

Create these tables in Dreamhome: ◦ Branch◦ Viewing ◦ Registration

Page 13: Select  To  Order By

Branch TableCREATE TABLE Branch

(branchNo char(10) NOT NULL, Street char(20),

City char(10),Postcode char(10)

)

Page 14: Select  To  Order By

Viewing tableCREATE TABLE Viewing(clientNo char(10) NOT NULL, propertyNo char(10), viewDate datetime, comment char(20))

Page 15: Select  To  Order By

Registration TableCREATE TABLE Registration(clientNo char(10) NOT NULL, branchNo char(10), staffNo char(10), dateJoined datetime)

Page 16: Select  To  Order By

ALTER Statement

Page 17: Select  To  Order By

Used to add or delete a column in an existing table

Adding columnALTER TABLE <table_name>ADD <column_name> <data_type>

Deleting columnALTER TABLE <table_name>DROP <column_name> <data_type>

Page 18: Select  To  Order By

Add a column in Viewing named NoOfViews

ALTER TABLE ViewingADD NoOfViews int

Delete the column comment in ViewingALTER TABLE ViewingDROP comment char

Page 19: Select  To  Order By

DROP Statement

Page 20: Select  To  Order By

Used to delete a database or table. Deleting a database

DROP DATABASE <database_name> Deleting a table

DROP TABLE <table_name>

Page 21: Select  To  Order By

Delete the tables Viewing and RegistrationDROP TABLE ViewingDROP TABLE Registration

Delete the Dreamhome databaseDROP DATABASE Dreamhome

Page 22: Select  To  Order By

INSERT Statement

Page 23: Select  To  Order By

Used to insert new rows into a table. The columns to be inserted with data can also be specified.

Insert new rowsINSERT INTO <table_name>VALUES (<value1,value2,value3,…>)

Specify columnsINSERT INTO <table_name>

(<column1>,<column2>,…)VALUES (<value1>, <value2>,…)

Page 24: Select  To  Order By

Add a new row in Branch with the following values: branchNo – B001Street – 4 New St.

City – New York Postcode – NYC11US

INSERT INTO BranchValues (‘B001’, ’4 New St.’, ’New York’, ‘NYC11US’)

Page 25: Select  To  Order By

Insert the following values in Viewing:clientNo – CR74propertyNo – PL94viewDate – 12-Dec-01

INSERT INTO Viewing (clientNo, propertyNo, viewDate)VALUES (‘CR74’, ‘PL94’, ‘12-Dec-01’)

Page 26: Select  To  Order By

UPDATE Statement

Page 27: Select  To  Order By

Used to modify a row in a table

UPDATE <table_name>SET <column_name> = <value>WHERE <column_name> = <some_value>

Page 28: Select  To  Order By

In the Viewing table, change the comment of all rows with clientNo = CR56 to “Big rooms”

UPDATE ViewingSET comment=‘Big rooms’WHERE clientNo = ‘CR56’

Page 29: Select  To  Order By

DELETE Statement

Page 30: Select  To  Order By

Used to delete a row in a tableDELETE FROM <table_name>WHERE <column_name> = <value>

Used to delete all rows from a tableDELETE FROM <table_name>

Page 31: Select  To  Order By

From Branch table, delete rows where city = LondonDELETE FROM BranchWHERE City = ‘London’

Delete all rows in Branch tableDELETE FROM Branch

Page 32: Select  To  Order By

SELECT Statement

Page 33: Select  To  Order By

Used to retrieve one or more columns from a tableSELECT [DISTINCT] <* | {column_name[,] }>FROM <table_name>

Used to retrieve one or more columns from a table based on a certain valueSELECT [DISTINCT] <* | {column_name[,] }>FROM <table_name> WHERE <column_name> = <value>

*DISTINCT – prevents display of duplicate values

Page 34: Select  To  Order By

Display all columns in PrivateOwner tableSELECT * from PrivateOwner

Display all columns in Viewing where clientNo is CR56SELECT * from ViewingWHERE clientNo = ‘CR56’

Page 35: Select  To  Order By

Display the first name, last name, and position of all Staff SELECT fName, lName, Position FROM Staff

Display the first name, last name, and position of all female Staff SELECT fName, lName, Position FROM StaffWHERE Sex = ‘F’

Page 36: Select  To  Order By

After completing this lesson, you should be able to do the following:

◦ List the capabilities of SQL SELECT statements

◦ Execute a basic SELECT statement

Page 37: Select  To  Order By

SelectionSelection ProjectionProjection

Table 1Table 1 Table 2Table 2

Table 1Table 1 Table 1Table 1JoinJoin

Page 38: Select  To  Order By

◦ SELECT identifies what columns.◦ FROM identifies which table.

SELECT [DISTINCT] {*, column [alias],...}FROM table;

SELECT [DISTINCT] {*, column [alias],...}FROM table;

Page 39: Select  To  Order By

◦ 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.◦ Tabs and indents are used to enhance

readability.

Page 40: Select  To  Order By

DEPTNO DNAME LOC--------- -------------- ------------- 10 ACCOUNTING MALOLOS 20 RESEARCH HAGONOY 30 SALES CALUMPIT 40 OPERATIONS PULILAN

SQL> SELECT * 2 FROM dept;

Page 41: Select  To  Order By

DEPTNO LOC--------- ------------- 10 MALOLOS 20 HAGONOY 30 CALUMPIT 40 PULILAN

SQL> SELECT deptno, loc 2 FROM dept;

Page 42: Select  To  Order By

Create expressions on NUMBER and DATE data by using arithmetic operators.

Operator

+

-

*

/

Description

Add

Subtract

Multiply

Divide

Page 43: Select  To  Order By

SQL> SELECT ename, sal, sal+300 2 FROM emp;

ENAME SAL SAL+300---------- --------- ---------ROMEL 20000 20300JOI 10000 10300JANE 5000 5300ANDY 5875 6175RANDY 11784 12084MARK 9775 10075...10 rows selected.

Page 44: Select  To  Order By

◦ 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.

**** //// ++++ ____

Page 45: Select  To  Order By

SQL> SELECT ename, sal, 12*sal+100 2 FROM emp;

ENAME SAL 12*SAL+100---------- --------- ----------ROMEL 20000 240100JOI 10000 120100JANE 5000 60100ANDY 5875 70600RANDY 11784 141508...10 rows selected.

Page 46: Select  To  Order By

SQL> SELECT ename, sal, 12*(sal+100) 2 FROM emp;

ENAME SAL 12*(SAL+100)---------- --------- -----------ROMEL 20000 241200JOI 10000 121200JANE 5000 61200ANDY 5875 71700RANDY 11784 142608...10 rows selected.

Page 47: Select  To  Order By

◦ A null is a value that is unavailable, unassigned, unknown, or inapplicable.

◦ A null is not the same as zero or a blank space.

ENAME JOB SAL COMM---------- --------- --------- ---------ROMEL PRESIDENT 20000 NULLJOI SALES MANAGER 10000 1000...RANDY HEAD ACCOUNTANT 11784 NULL

10 rows selected.

SQL> SELECT ename, job, sal, comm 2 FROM emp;

Page 48: Select  To  Order By

Arithmetic expressions containing a null value evaluate to null.

SQL> select ename, 12*sal+comm 2 from emp 3 WHERE ename=‘ROMEL';

ENAME 12*SAL+COMM ---------- -----------KING NULL

Page 49: Select  To  Order By

◦ Renames a column heading◦ Is useful with calculations◦ Immediately follows column name; optional

AS keyword between column name and alias

◦ Requires double quotation marks if it contains spaces or special characters or is case sensitive

Page 50: Select  To  Order By

SQL> SELECT ename AS name, sal salary 2 FROM emp;

NAME SALARY

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

...

SQL> SELECT ename "Name", 2 sal*12 "Annual Salary" 3 FROM emp;

Name Annual Salary

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

...

Page 51: Select  To  Order By

◦ Concatenates columns or character strings to other columns

◦ Is represented by Plus sign (+)◦ Creates a resultant column that is a

character expression

Page 52: Select  To  Order By

SQL> SELECT ename + job AS "Employees" 2 FROM emp;

Employees-------------------ROMELPRESIDENTJOISALES MANAGERJANESALES REPRESENTATIVEANDYSALES REPRESENTATIVERANDYHEAD ACCOUNTANT...10 rows selected.

Page 53: Select  To  Order By

◦ A literal is a character, a number, or a date included in the SELECT list.

◦ Date and character literal values must be enclosed within single quotation marks.

◦ Each character string is output once for each row returned.

Page 54: Select  To  Order By

Employee Details-------------------------

...10 rows selected.

Employee Details-------------------------

...10 rows selected.

SQL> SELECT ename + ' is a ‘ + job 2 AS "Employee Details" 3 FROM emp;

ROMEL is a PRESIDENTJOI is a SALES MANAGERJANE is a SALES REPRESENTATIVEANDY is a SALES REPRESENTATIVERANDY is a HEAD ACCOUNTANT

Page 55: Select  To  Order By

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

SQL> SELECT deptno 2 FROM emp;

SQL> SELECT deptno 2 FROM emp;

DEPTNO--------- 10 30 10 40...14 rows selected.

Page 56: Select  To  Order By

Eliminate duplicate rows by using the Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.DISTINCT keyword in the SELECT clause.

SQL> SELECT DISTINCT deptno 2 FROM emp;

DEPTNO--------- 10 30 40

Page 57: Select  To  Order By

SQLSQLstatementsstatements

SQL SQL

• A languageA language

• ANSI standardANSI standard

• Keyword cannot be Keyword cannot be abbreviatedabbreviated

• Statements manipulate Statements manipulate data and table data and table definitions in the definitions in the databasedatabase

SQL*PlusSQL*Plus

• An environmentAn environment

• Oracle proprietaryOracle proprietary

• Keywords can be Keywords can be abbreviatedabbreviated

• Commands do not Commands do not allow manipulation of allow manipulation of values in the databasevalues in the database

SQLSQLbufferbuffer

SQL*PlusSQL*Pluscommandscommands

SQL*PlusSQL*Plusbufferbuffer

Page 58: Select  To  Order By

"…retrieve all"…retrieve allemployeesemployees

in department 30"in department 30"

EMPEMP

EMPNO ENAME JOB ... DEPTNO

1001 ROMEL PRESIDENT 40 1002 JOI SALES M... 30 1003 JANE SALES REP 30. . . 1006 MARK ACCOUN.. 10 ...

EMPEMP

EMPNO ENAME JOB ... DEPTNO

1002 JOI SALES M... 30 1003 JANE SALES REP 30 . . .

Page 59: Select  To  Order By

◦ Restrict the rows returned by using the WHERE clause.

◦ The WHERE clause follows the FROM clause.

◦ Restrict the rows returned by using the WHERE clause.

◦ The WHERE clause follows the FROM clause.

SELECT [DISTINCT] {*| column [alias], ...}FROM table[WHERE condition(s)];

Page 60: Select  To  Order By

SQL> SELECT ename, deptno 2 FROM emp 3 WHERE deptno=10;

ENAME DEPTNO---------- --------- ---------RANDY 10MARK 10JESSA 10

Page 61: Select  To  Order By

Operator

=

>

>=

<

<=

<>

Meaning

Equal to

Greater than

Greater than or equal to

Less than

Less than or equal to

Not equal to

Page 62: Select  To  Order By

SQL> SELECT ename,comm 2 FROM emp 3 WHERE comm>=700;

ENAME COMM---------- --------- MARTIN 1000

Page 63: Select  To  Order By

Operator

BETWEEN

...AND...

IN(list)

LIKE

IS NULL

Meaning

Between two values (inclusive)

Match any of a list of values

Match a character pattern

Is a null value

Page 64: Select  To  Order By

Use the BETWEEN operator to display rows based on a range of values.

Use the BETWEEN operator to display rows based on a range of values.

ENAME SAL---------- ---------JOI 10000JANE 5000ANDY 5875MARK 9775RIZZA 9798DAVID 6897

SQL> SELECT ename, sal 2 FROM emp 3 WHERE sal BETWEEN 5000 AND 10000;

Lowerlimit

Higherlimit

Page 65: Select  To  Order By

Use the IN operator to test for values in a list.

Use the IN operator to test for values in a list.

SQL> SELECT ename, deptno 2 FROM emp 3 WHERE deptno IN (10, 40);

ENAME deptno--------- --------- ROMEL 40 RANDY 10 MARK 10 RIZZA 40

Page 66: Select  To  Order By

• 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.

• 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.

SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE ‘R%';

Page 67: Select  To  Order By

◦ You can combine pattern-matching characters.

◦ You can use the ESCAPE identifier to search for "%" or "_".

◦ You can combine pattern-matching characters.

◦ You can use the ESCAPE identifier to search for "%" or "_".

SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE '_O%';

ENAME---------- ROMELJOI

Page 68: Select  To  Order By

Test for null values with the IS NULL operator.

Test for null values with the IS NULL operator.

SQL> SELECT ename, mgr 2 FROM emp 3 WHERE mgr IS NULL;

ENAME MGR---------- ---------ROMEL NULL

Page 69: Select  To  Order By

Operator

AND

OR

NOT

Meaning

Returns TRUE if both component

conditions are TRUE

Returns TRUE if either component

condition is TRUE

Returns TRUE if the following condition is FALSE