SQLPlus Commands. Oracle Account Server: libra.sfsu.edu Telnet: libra.sfsu.edu How to use Oracle: –http://www.sfsu.edu/~helpdesk/docs/using/usingoracle.htmhttp://www.sfsu.edu/~helpdesk/docs/using/usingoracle.htm.

Slides:



Advertisements
Similar presentations
Oracle 10g Express. Download Oracle 10g Express Oracle 10g Express Edition: – edition/overview/index.htmlhttp://
Advertisements

SQL Sub (or Nested ) Query. Examples Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student.
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
Structured Query Language Review ISYS 650. Language Overview Three major components: –Data definition language, DDL Create, Drop and Alter Tables or Views.
A Guide to Oracle9i1 Using SQL Queries to Insert, Update, Delete, and View Data Chapter 3.
Access - 1 Table Query (View) FormReport Database Application Basic Database Objects Relationships among Access Database Objects A saved SELECT query is.
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Aggregates.
Basic SQL Select Commands. Basic Relational Query Operations Selection Projection Natural Join Sorting Aggregation: Max, Min, Sum, Count, Avg –Total –Sub.
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Relational Algebra. Set operations: Union, intersection, difference, Cartesian product Relational operations: Selection, projection, join, division.
Writing Basic SQL statement 2 July July July Create By Pantharee Sawasdimongkol.
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
A Guide to MySQL 3. 2 Objectives Start MySQL and learn how to use the MySQL Reference Manual Create a database Change (activate) a database Create tables.
Other Joins ISYS 464. Outer Join Records in a relation that do not have matching values are included in the result relation. Missing values are set to.
Relational Operators, SQL, and Access Query ISYS 562.
Chapter 1 Writing Basic SQL Statements Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina,
Ceng 356-Lab1. Objectives After completing this lesson, you should be able to do the following: Get Familiar with the development environment List the.
Database Programming Sections 5– GROUP BY, HAVING clauses, Rollup & Cube Operations, Grouping Set, Set Operations 11/2/10.
Guide to Oracle10G1 Using SQL Queries to Insert, Update, Delete, and View Data Chapter 3.
SQL: Interactive Queries (1) John Ortiz Lecture 11SQL: Interactive Queries (1)2 Basic Select Statement  Basic form of the select statement: select target-attribute-list.
ASP.NET Programming with C# and SQL Server First Edition
Chapter 2 Basic SQL SELECT Statements Oracle 10g: SQL.
Relational Query Operators (ii). Other Joins Theta join: Apply any specified condition on the product of two relations. Example: BoyStudent: BID, Bname,
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
ITBIS373 Database Development
Oracle Database Administration Lecture 2 SQL language.
INLS 623– S QL Instructor: Jason Carter. SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;
CSC 405: Web Application And Engineering II7.1 Database Programming with SQL Aggregation and grouping with GROUP BY Aggregation and grouping with GROUP.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) Structured Query Language Introduction to SQL Structured Query Language.
Database control Introduction. The Database control is a tool that used by the database administrator to control the database. To enter to Database control.
Advanced SQL for Decision Support ISYS 650. Set Operators Union Intersect Difference Cartesian product.
Copyright  Oracle Corporation, All rights reserved. Writing Basic SQL Statements.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Oracle DML Dr. Bernard Chen Ph.D. University of Central Arkansas.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 5 © Akhilesh Bajaj, 2000, 2002, 2003, All.
Introduction to Access ISYS 363. Creating a New Database MS Office button/New –Blank database –New database name and location.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
1 Writing Basic SQL Statements. 1-2 Objectives At the end of this lesson, you should be able to: List the capabilities of SQL SELECT statements Execute.
Relational Query Operators (Algebra). Relational Query Operators Set operations: Union, intersection, difference, Cartesian product Relational operations:
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
Querying Database ISYS 363.
Introduction to Query Language and SQL. Basic Query Language Operators Selection Projection Join Aggregates –Sum, Count, Max, Min, Avg SubTotal Calculated.
Working with Columns, Characters, and Rows. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Apply the concatenation.
Introduction to Access BUS 782. Creating a New Database MS Office button/New –Blank database –New database name and location.
Introduction to Access ISYS 363. Access Objects Tables –Open –Design –New –Wizard Queries Forms Reports Pages.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
SQL Miscellaneous Topics. Views A database view is: – a virtual or logical table based on a query. – a stored query. CREATE VIEW viewname AS query; –CREATE.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
1-1 Copyright  Oracle Corporation, All rights reserved. Logging In to SQL*Plus From Windows environment:From Windows environment: From command line:From.
Introduction to Access ISYS 363. Access Objects Tables –Open a table: Double click the table name –Home/View: Datasheet view Design view Queries Forms.
Set Operators. Union Intersect Difference Cartesian product.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Copyright س Oracle Corporation, All rights reserved. 1 Writing Basic SQL Statements.
SQL in Oracle.
Lecture#7: Fun with SQL (Part 2)
ORACLE SQL Developer & SQLPLUS Statements
Querying Database ISYS 363.
Creating and Maintaining
Structured Query Language
Contents Preface I Introduction Lesson Objectives I-2
Presentation transcript:

SQLPlus Commands

Oracle Account Server: libra.sfsu.edu Telnet: libra.sfsu.edu How to use Oracle: – Basic Unix commands: – –PICO text editor

Commands at Oracle SQL> To list all commands: –SQL>help index To list all tables: –Select * from Cat; To display a table structure: –Describe tableName To run an Unix command from Oracle: –Host unixCommand Use Column command to change output format: –SQL>column empid format a5; –SQL>column salary format $9,999.99; –SQL>column empid heading EmpID; Commands related to SQL buffer: –List, Run, Clear, Del, Change

Working with SQL Buffer SQL Buffer remembers the last SQL command executed. List: list the SQL statement with line number correct the line with error: line number correct statement Run

Creating SQL Command Batch File Creating a batch file with.sql extension –Use Unix text editor (pico) to create the batch file, or –At SQL>Edit filename Ex: SQL>edit batch1.sql Use START command to execute the batch file. –SQL>START batch1.sql See the batch file contents at SQL> –SQL>host cat batch1.sql

Batch File Example Drop table hotel; Create table hotel (hotelno char(3), hotelname varchar(2 Insert into hotel values('h1', 'Grosvenor','CHICAGO'); Insert into hotel values('h2', 'Westin','SAN FRANCISCO') Insert into hotel values('h3', 'Hilton','London'); Drop table room; Create table room(roomno char(3),hotelno char(3),type char(6), price number(7,2)); Insert into room values('r1','h1','single', ); Insert into room values('r2','h1','single', ); Insert into room values('r3','h1','double', ); Insert into room values('r1','h2','single', ); Insert into room values('r2','h2','single', ); Insert into room values('r3','h2','double', ); Insert into room values('r1','h3','single', ); Insert into room values('r2','h3','single', ); Insert into room values('r3','h3','double', );

To display complete field name: –Ex. –column sex format a3 –Select * from student; To print output: –In computer lab: Spool anyFileName Run sql statements Spool off –Screen capture –Telnet window: Click the computer icon on the upper left corner Edit/Mark Edit/Copy Enter a date value: assume emp table has: eid, ename, hiredate and salary field: –Insert into emp values(‘e1’, ‘peter’,’10-Feb-04’, );

SQL Select

Selection SELECT * FROM tableName WHERE criteria; Criteria: –=, <>,, = –(), NOT, AND, OR –BETWEEN WHERE salary BETWEEN 1000 AND 10000; –LIKE, NOT LIKE: % WHERE ename LIKE ‘C%’ –Cannot say: WHERE ename = ‘C%’ –IN, NOT IN WHERE eid IN (‘e1’,’e3’) –IS NULL WHERE rating IS NULL –Arithmetic expression in criteria: WHERE salary*0.1 < 500

ROWNUM Field ROWNUM field is a pseudocolumn that applies to every table even though it is not displayed through a SELECT * command. SELECT ROWNUM, empid FROM emp; SELECT * FROM emp WHERE ROWNUM < = 3;

Projection SELECT fields FROM tableName WHERE criteria; SELECT DISTINCT fields FROM tableName WHERE criteria; Field name alias: AS Ex: SELECT eid AS empID, ename AS empName FROM emp; Calculated fields: –SELECT empid,ename,salary*0.1 AS tax FROM emp; Note: UNIQUE –SELECT UNIQUET fields FROM tableName WHERE criteria;

Oracle Functions Text functions: –UPPER, LOWER, INITCAP –SUBSTR(text,starting position, # of chars) –LPAD(text,length of text,padding symbol) LPAD(salary,10,’*”) –CONCAT(text1,text2) We can also use concatenation operator, || Date functions: –SYSDATE,NEXT_DAY Ex. NEXT_DAY(SYSDATE,’MONDAY’) –MONTHS_BETWEEN(date1,date2) –ADD_MONTHS(date,# of months added)

Product SELECT fields FROM table1, table2; table name alias: Ex: SELECT s.*, f.* FROM student s, faculty f; Take the product of a table itself. –SELECT * FROM emp e1, emp e2;

CROSS JOIN = Product select * from student cross join course;

Natural Join SELECT * FROM table1 NATURAL JOIN table2; –SELECT * FROM student NATURAL JOIN faculty; SELECT * FROM table1, table2 WHERE table1.JoinAttribute = table2.JoinAttribute; –SELECT * FROM student, faculty –WHERE student.fid = faculty.fid; Table name alias: –SELECT * FROM student s, faculty f WHERE s.fid = f.fid; Other forms: –FROM student s JOIN faculty f ON s.fid=f.fid; –FROM student s INNER JOIN faculty f ON s.fid=f.fid; –FROM student JOIN faculty USING fid; Not supported by Oracle Note: What if the FID in the student table is named AdvisorID?

Outer Join SELECT s.*, f.* FROM –student s FULL JOIN faculty f ON s.fid = f.fid; SELECT s.*, f.* FROM –student s RIGHT JOIN faculty f ON s.fid = f.fid; SELECT s.*, f.* FROM –student s LEFT JOIN faculty f ON s.fid = f.fid; Demo: Access’ SQL view.

Theta Join SELECT * FROM table1, table2 WHERE criteria; Example: match male students with female students who have higher GPA: –select m.sid, m.sname,f.sid,f.sname –from malestudent m, female f –where m.gpa < f.gpa;

Theta Join Example: match male employees with female employees who have higher salary: –SELECT e1.empid,e1.ename,e2.empid,e2.ename –FROM emp e1, emp e2 –WHERE e1.sex=‘M’ and e2.sex=‘F’ –AND e1.salary < e2.salary;

Sorting ORDER BY fieldName [DESC] –SELECT * FROM student ORDER BY sname; –SELECT * FROM student ORDER BY sname DESC; More than one field: –SELECT * FROM student ORDER BY major, sname; Note 1: Don’t name a table “ORDER” because ORDER is a SQL keyword. Note 2: If there is a WHERE clause, then the ORDER BY clause should be placed after the WHERE clause.

Set Operators Union compatible Union: –(SELECT * FROM table1) UNION (SELECT * FROM table2); Intersect: (SELECT * FROM table1) INTERSECT (SELECT * FROM table2); Minus: (SELECT * FROM table1) MINUS (SELECT * FROM table2);

Find students taking 263 and acct 101 select sid from registration where cid='ISYS263' intersect select sid from registration where cid='acct101‘; Note: How to get student name?

Aggregates SELECT AVG(fieldName) FROM tableName; –COUNT(fieldName), COUNT(*) –COUNT(DISTINCT fieldName) –MAX(fieldName) –MIN(fieldName) –SUM(fieldName) More than one aggregate: SELECT AVG(fieldName), MAX(fieldName), MIN(fieldName) FROM tableName; With alias: –SELECT AVG(gpa) AS avggpa, COUNT(sid) AS scount FROM student;

GROUP BY SELECT groupingFields, function(fieldname) FROM tablename GROUP BY groupingFields; –SELECT major, count(sid) FROM student GROUP BY major; –SELECT sex, major, count(sid) FROM student GROUP BY sex, major; Compute more than one subtotals: –SELECT major, count(sid), avg(gpa) FROM student –GROUP BY major Compute subtotals from a join Compute the number of courses taken by each student: –SELECT sid, sname, COUNT(cid) FROM student NATURAL JOIN registration GROUP BY sid, sname; Note 1: All grouping fields in the SELECT clause must be included in the GROUP BY clause). Note 2:WHERE clause must come before the GROUP BY: –SELECT major, count(sid) FROM student WHERE GPA > 3.0 GROUP BY major;

Adding a Criteria for the Sub Totals with HAVING SELECT major, count(sid) FROM student –GROUP BY major –HAVING count(sid) > 5; Sometime the aggregates are not required to display: –Find majors that have more than 5 students: –SELECT major FROM student GROUP BY major HAVING count(sid) > 5;

Sub (or Nested ) Query Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student WHERE gpa < (SELECT AVG(gpa) FROM student); Q: Find employees with higher than average salary.

Sub Query with IN Q: Display faculty’s ID and name if the faculty advises at least one student. –SELECT fid, fname FROM faculty –WHERE fid IN (SELECT DISTINCT fid FROM student); Q: Display faculty’s name and phone if the faculty does not advise any student. –SELECT fid, fname FROM faculty –WHERE fid NOT IN (SELECT DISTINCT fid FROM student);

Sub Query with IN Q: Find students who take at least one course and display their ID and name. –SELECT sid, sname FROM student NATURAL JOIN enroll GROUP BY sid HAVING COUNT(cid) > 1; –SELECT sid, sname FROM student WHERE sid IN (SELECT DISTINCT sid FROM enroll); Q: Find students who take more than 5 courses and display their ID and name. –SELECT sid, sname FROM student WHERE sid IN (SELECT sid FROM enroll GROUP BY sid –HAVING COUNT(cid) > 5);

Sub Query with Join Display students’ ID and name who owe university more than $2000. select sid,sname from student natural join (select * from account where balance > 2000);

Sub Query with ALL/SOME/ANY Q: Find students whose gpa is greater than all/some bus majors’ gpa: –SELECT sid, sname FROM student WHERE gpa > ALL(SELECT gpa FROM student WHERE major=‘bus’); –SELECT sid, sname FROM student WHERE gpa > SOME (SELECT gpa FROM student WHERE major=‘bus’); –SELECT sid, sname FROM student WHERE gpa > ANY (SELECT gpa FROM student WHERE major=‘bus’);

Comparing the Two SQL Statements Compute the number of courses taken by each student: (1) SELECT sid, sname, courses FROM student NATURAL JOIN (SELECT sid, COUNT(cid) AS courses FROM registration GROUP BY sid); (2) SELECT sid, sname, COUNT(cid) AS courses FROM student NATURAL JOIN registration GROUP BY sid);

Examples University database: –Student: SID, Sname, Sex, Major, GPA, FID –Account: SID, Balance –Faculty: FID, Fname –Course: CID, Cname, Credits –StudentCourse: SID, CID

Questions Q1: Display College of Business students’ ID and name. Q2: Display students’ ID and name who owe university more than $2000. Q3: Display faculty’s name and phone if the student’s GPA is lower than 2.0. Q4: Display faculty’s name and phone if the faculty advises at least one student. Q5: Display faculty’s name and phone if the faculty does not advise any student. Q6: Display students’ ID and name who are taking at least one course. Q7: Display students’ ID and name who do not take any course. Q8: Display students’ ID and name who are taking 464 and GPA < 2.0 Q9: Display students’ ID and name who are taking Chao’s courses. Q10: Display students’ ID and name who are taking 464 and 363.