Select To Order By
-
Upload
krizia-capacio -
Category
Technology
-
view
111 -
download
2
description
Transcript of Select To Order By
Introduction to SQL SQL Definition SQL Manipulation SQL Query SQL Control
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
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
Statements for defining database or table
◦CREATE◦ALTER◦DROP
Statements to add, modify and remove rows intables.
◦INSERT◦UPDATE◦DELETE
Statements used to retrieve data.
◦SELECT
Statements used for database security.
◦GRANT◦REVOKE
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,
.......
)
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
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
Create a database named DREAMHOMECREATE DATABASE Dreamhome
Create these tables in Dreamhome: ◦ Branch◦ Viewing ◦ Registration
Branch TableCREATE TABLE Branch
(branchNo char(10) NOT NULL, Street char(20),
City char(10),Postcode char(10)
)
Viewing tableCREATE TABLE Viewing(clientNo char(10) NOT NULL, propertyNo char(10), viewDate datetime, comment char(20))
Registration TableCREATE TABLE Registration(clientNo char(10) NOT NULL, branchNo char(10), staffNo char(10), dateJoined datetime)
ALTER Statement
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>
Add a column in Viewing named NoOfViews
ALTER TABLE ViewingADD NoOfViews int
Delete the column comment in ViewingALTER TABLE ViewingDROP comment char
DROP Statement
Used to delete a database or table. Deleting a database
DROP DATABASE <database_name> Deleting a table
DROP TABLE <table_name>
Delete the tables Viewing and RegistrationDROP TABLE ViewingDROP TABLE Registration
Delete the Dreamhome databaseDROP DATABASE Dreamhome
INSERT Statement
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>,…)
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’)
Insert the following values in Viewing:clientNo – CR74propertyNo – PL94viewDate – 12-Dec-01
INSERT INTO Viewing (clientNo, propertyNo, viewDate)VALUES (‘CR74’, ‘PL94’, ‘12-Dec-01’)
UPDATE Statement
Used to modify a row in a table
UPDATE <table_name>SET <column_name> = <value>WHERE <column_name> = <some_value>
In the Viewing table, change the comment of all rows with clientNo = CR56 to “Big rooms”
UPDATE ViewingSET comment=‘Big rooms’WHERE clientNo = ‘CR56’
DELETE Statement
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>
From Branch table, delete rows where city = LondonDELETE FROM BranchWHERE City = ‘London’
Delete all rows in Branch tableDELETE FROM Branch
SELECT Statement
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
Display all columns in PrivateOwner tableSELECT * from PrivateOwner
Display all columns in Viewing where clientNo is CR56SELECT * from ViewingWHERE clientNo = ‘CR56’
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’
After completing this lesson, you should be able to do the following:
◦ List the capabilities of SQL SELECT statements
◦ Execute a basic SELECT statement
SelectionSelection ProjectionProjection
Table 1Table 1 Table 2Table 2
Table 1Table 1 Table 1Table 1JoinJoin
◦ SELECT identifies what columns.◦ FROM identifies which table.
SELECT [DISTINCT] {*, column [alias],...}FROM table;
SELECT [DISTINCT] {*, column [alias],...}FROM table;
◦ 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.
DEPTNO DNAME LOC--------- -------------- ------------- 10 ACCOUNTING MALOLOS 20 RESEARCH HAGONOY 30 SALES CALUMPIT 40 OPERATIONS PULILAN
SQL> SELECT * 2 FROM dept;
DEPTNO LOC--------- ------------- 10 MALOLOS 20 HAGONOY 30 CALUMPIT 40 PULILAN
SQL> SELECT deptno, loc 2 FROM dept;
Create expressions on NUMBER and DATE data by using arithmetic operators.
Operator
+
-
*
/
Description
Add
Subtract
Multiply
Divide
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.
◦ 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.
**** //// ++++ ____
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.
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.
◦ 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;
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
◦ 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
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
------------- -------------
...
◦ Concatenates columns or character strings to other columns
◦ Is represented by Plus sign (+)◦ Creates a resultant column that is a
character expression
SQL> SELECT ename + job AS "Employees" 2 FROM emp;
Employees-------------------ROMELPRESIDENTJOISALES MANAGERJANESALES REPRESENTATIVEANDYSALES REPRESENTATIVERANDYHEAD ACCOUNTANT...10 rows selected.
◦ 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.
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
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.
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
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
"…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 . . .
◦ 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)];
SQL> SELECT ename, deptno 2 FROM emp 3 WHERE deptno=10;
ENAME DEPTNO---------- --------- ---------RANDY 10MARK 10JESSA 10
Operator
=
>
>=
<
<=
<>
Meaning
Equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Not equal to
SQL> SELECT ename,comm 2 FROM emp 3 WHERE comm>=700;
ENAME COMM---------- --------- MARTIN 1000
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
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
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
• 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%';
◦ 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
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
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