Oracle Database SQL Basics

Similar documents
Join, Sub queries and set operators

Intermediate SQL: Aggregated Data, Joins and Set Operators

Database Foundations. 6-9 Joining Tables Using JOIN. Copyright 2014, Oracle and/or its affiliates. All rights reserved.

KORA. RDBMS Concepts II

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Retrieving Data from Multiple Tables

ÇALIŞMA TEST SORULARI

Manipulating Data. Copyright 2004, Oracle. All rights reserved.

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Data Manipulation Language

Introduction to Oracle9i: SQL

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

GIFT Department of Computing Science. [Spring 2016] CS-217: Database Systems. Lab-3 Manual. Single Row Functions in SQL

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

SQL Functions (Single-Row, Aggregate)

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Exam: 1Z Title : Introduction to Oracle9i: SQL. Ver :

What Are Group Functions? Reporting Aggregated Data Using the Group Functions. Objectives. Types of Group Functions

EXISTS NOT EXISTS WITH

Database Programming with SQL

CS Week 10 - Page 1

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Introduction to Oracle9i: SQL

Táblák tartalmának módosítása. Copyright 2004, Oracle. All rights reserved.

Additional Practice Solutions

Course Outline and Objectives: Database Programming with SQL

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Alkérdések II. Copyright 2004, Oracle. All rights reserved.

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Introduction to Computer Science and Business

Exam : 1Z Title : Introduction to Oracle9i: SQL

Oracle Syllabus Course code-r10605 SQL

Fravo.com. Certification Made Easy. World No1 Cert Guides. Introduction to Oracle9i: SQL Exam 1Z Edition 1.0

DEFAULT Values, MERGE, and Multi-Table Inserts. Copyright 2009, Oracle. All rights reserved.

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

@vmahawar. Agenda Topics Quiz Useful Links

Database Programming with SQL

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

Oracle Database 11g: SQL Fundamentals I

Conversion Functions

1Z0-007 ineroduction to oracle9l:sql

Oracle 1Z0-007 Introduction to Oracle9i: SQL 210 Q&A

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

SQL. - single row functions - Database Design ( 데이터베이스설계 ) JUNG, Ki-Hyun ( 정기현 )

Database Programming with SQL

Topics Fundamentals of PL/SQL, Integration with PROIV SuperLayer and use within Glovia

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

Chapter-14 SQL COMMANDS

Reporting Aggregated Data Using the Group Functions. Copyright 2004, Oracle. All rights reserved.

2. What privilege should a user be given to create tables? The CREATE TABLE privilege

ITCertMaster. Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way!

Oracle Database 12c SQL Fundamentals

What are temporary tables? When are they useful?

Exam Code: 1z Exam Name: Ineroduction to oracle9l:sql. Vendor: Oracle. Version: DEMO

Using the Set Operators. Copyright 2006, Oracle. All rights reserved.

HR Database. Sample Output from TechWriter 2007 for Databases

Oracle Database 11g: SQL and PL/SQL Fundamentals

RETRIEVING DATA USING THE SQL SELECT STATEMENT

Oracle Database 10g: SQL Fundamentals I

Using DDL Statements to Create and Manage Tables. Copyright 2006, Oracle. All rights reserved.

CONCAT SUBSTR LOWER (*) All three will be evaluated simultaneously. Correct

CS2 Current Technologies Lecture 2: SQL Programming Basics

1Z Oracle Database 11g - SQL Fundamentals I Exam Summary Syllabus Questions

Oracle Database: SQL Fundamentals I. Oracle Internal & Oracle Academy Use Only. Volume II Student Guide. D64258GC10 Edition 1.0 January 2010 D65028


SQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

Database Programming with SQL

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Oracle Database: SQL and PL/SQL Fundamentals NEW

AO3 - Version: 2. Oracle Database 11g SQL

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Database Programming - Section 7. Instructor Guide

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

Oracle Database 10g: SQL Fundamentals II

SQL Structured Query Language Introduction

SQL Structured Query Language (1/2)

Database Programming with PL/SQL

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113)

UNIT III INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL)

DUE: 9. Create a query that will return the average order total for all Global Fast Foods orders from January 1, 2002, to December 21, 2002.

Database Programming with SQL

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

Database Programming - Section 1. Instructor Guide

Oracle 1Z Oracle Database 11g SQL Fundamentals I. Download Full Version :

5. Single-row function

1 SQL Structured Query Language

Database Programming - Section 3. Instructor Guide

Using SQL with SQL Developer 18.2

Creating Other Schema Objects

Oracle Database: Introduction to SQL

Creating Other Schema Objects. Copyright 2004, Oracle. All rights reserved.

Testing Masters Technologies

CSC Web Programming. Introduction to SQL

Série n 6 Bis : Ateliers SQL Data Modeler (Oracle)

Oracle Database: Introduction to SQL Ed 2

Database Programming with PL/SQL

Transcription:

Oracle Database SQL Basics Kerepes Tamás, Webváltó Kft. tamas.kerepes@webvalto.hu 2015. február 26. Copyright 2004, Oracle. All rights reserved.

SQL a history in brief The relational database stores data in tables: rows and columns. The idea was suggested by Codd in 1970. Four years later, in 1974 the SQL language was proposed for managing data stored in relational database management systems. This form of storing data needs a special language for: Retrieving data Manipulating data (inserting, deleting and updating) Defining and modifying table structures (creating tables, dropping and modifying them). We need commands to define other structures also: indexes, views, synonyms, and so on. SQL Structured Query Language is used nowadays by the vast majority of relational database management systems as this language. Copyright 2004, Oracle. All rights reserved.

1-3 Copyright 2004, Oracle. All rights reserved. SQL Basics Operators Relational: <,>,=,!=,<> SQL: IN, LIKE, BETWEEN, IS NULL (NOT can be used) Functions Numeric: ROUND,TRUNC, FLOOR,CEIL,SQRT,SIN,etc. Character: SUBSTR, INSTR,REPLACE, UPPER, LOWER Date: SYSDATE,SYSTIMESTAMP, ADD_MONTHS Converson:TO_CHAR,TO_DATE, TO_NUMBER,TO_LOB Aggregate: MIN, MAX, SUM, AVG, COUNT, LISTAGG,COV Analytic: LAG, LEAD, WITH_BUCKET,NTILE, Other: XML, REGEXP, CHR,ASCII, DECODE, DUMP Statements DML: SELECT, INSERT, UPDATE,DELETE DDL: CREATE, DROP, ALTER, RENAME, TRUNCATE DCL: GRANT, REVOKE

CREATE TABLE Statement You must have: CREATE TABLE system privilege A storage area CREATE TABLE [schema.]table (column datatype [DEFAULT expr][,...]); You specify: Table name Column name, column data type, and column size 1-4 Copyright 2004, Oracle. All rights reserved.

1-5 Copyright 2004, Oracle. All rights reserved. Creating Tables Create the table. CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE); Table created. Confirm table creation. DESCRIBE dept

Data Manipulation Language A DML statement is executed when you: Add new rows to a table Modify existing rows in a table Remove existing rows from a table Merge rows into a table from source tables A transaction consists of a collection of DML statements that form a logical unit of work. 1-6 Copyright 2004, Oracle. All rights reserved.

INSERT Statement Syntax Add new rows to a table by using the INSERT statement: INSERT INTO table [(column [, column...])] VALUES (value [, value...]); With this syntax, only one row can be inserted at a time. Insert values into the table in the following order of the columns: INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (70, 'Public Relations', 100, 1700); 1 row created. 1-7 Copyright 2004, Oracle. All rights reserved.

1-8 Copyright 2004, Oracle. All rights reserved. Copying Rows from Another Table Write your INSERT statement with a subquery: INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct WHERE job_id LIKE '%REP%'; 4 rows created. Do not use the VALUES clause. Match the number of columns in the INSERT clause with the number of columns in the subquery.

1-9 Copyright 2004, Oracle. All rights reserved. UPDATE Statement Syntax Modify existing rows with the UPDATE statement: UPDATE table SET column = value [, column = value,...] [WHERE condition]; UPDATE employees SET department_id = 70 WHERE employee_id = 113; 1 row updated. Update more than one row at a time (if required). UPDATE copy_emp SET department_id = 110; 22 rows updated.

1-10 Copyright 2004, Oracle. All rights reserved. Updating Two Columns with a Subquery Update employee 206 s job id and salary to match that of employee 205. UPDATE employees SET (job_id, salary) = (SELECT job_id, salary WHERE employee_id = 205) WHERE employee_id = 206; 1 row updated.

1-11 Copyright 2004, Oracle. All rights reserved. DELETE Statement You can remove existing rows from a table by using the DELETE statement: DELETE [FROM] table [WHERE condition]; DELETE FROM departments WHERE department_name = 'Finance'; 1 row deleted. DELETE WHERE department_id = (SELECT department_id FROM departments WHERE department_name LIKE '%Public%'); 1 row deleted.

TRUNCATE Statement Removes all rows from a table, leaving the table empty and the table structure intact It is a data definition language (DDL) statement rather than a DML statement; cannot be easily undone Syntax: TRUNCATE TABLE table_name; Example: TRUNCATE TABLE copy_emp; 1-12 Copyright 2004, Oracle. All rights reserved.

1-13 Copyright 2004, Oracle. All rights reserved. Selecting All and specific Columns SELECT * FROM departments; SELECT department_id, location_id FROM departments;

1-14 Copyright 2004, Oracle. All rights reserved. Null Values in Arithmetic Expressions Arithmetic expressions containing a null value evaluate to null. Use the NVL function! SELECT last_name, 12*salary*commission_pct ; SELECT last_name, salary,commission_pct, 12*salary*(1+NVL(commission_pct,0)) ;

1-15 Copyright 2004, Oracle. All rights reserved. Limiting the Rows That Are Selected Restrict the rows that are returned by using the WHERE clause: SELECT employee_id, last_name, job_id, department_id WHERE department_id = 90 ; SQL Row Limiting Clause in Oracle 12c SELECT employee_id, last_name, salary ORDER BY salary DESC FETCH first 5 ROWS ONLY ;

1-16 Copyright 2004, Oracle. All rights reserved. Using Comparison operators SELECT last_name, salary WHERE salary <= 3000 ; SELECT last_name, salary WHERE salary BETWEEN 2500 AND 3500; SELECT last_name, job_id, department_id WHERE last_name = 'Whalen' ; SELECT * WHERE hire_date >= '31-dec-98' ; SELECT * WHERE hire_date >= DATE '1998-12-31' ;

1-17 Copyright 2004, Oracle. All rights reserved. Using the IN, LIKE and IS NULL operator SELECT employee_id, last_name, salary, manager_id WHERE manager_id IN (100, 101, 201) ; SELECT last_name WHERE last_name LIKE '_o%' ; SELECT last_name, manager_id WHERE manager_id IS NULL ;

1-18 Copyright 2004, Oracle. All rights reserved. Using logical operators SELECT employee_id, last_name, job_id, salary WHERE salary >=10000 AND job_id LIKE '%MAN%' ; SELECT employee_id, last_name, job_id, salary WHERE salary >= 10000 OR job_id LIKE '%MAN%' ; SELECT last_name, job_id WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP');

1-19 Copyright 2004, Oracle. All rights reserved. Using the ORDER BY Clause Sort the retrieved rows with the ORDER BY clause: ASC: ascending order, default DESC: descending order The ORDER BY clause comes last in the SELECT statement: SELECT last_name, job_id, department_id, hire_date ORDER BY hire_date ;

1-20 Copyright 2004, Oracle. All rights reserved. Two Types of SQL Functions Functions Single-row functions Return one result per row Multiple-row functions Return one result per set of rows

1-21 Copyright 2004, Oracle. All rights reserved. Case-Manipulation Functions These functions convert case for character strings: Function LOWER('SQL Course') UPPER('SQL Course') INITCAP('SQL Course') Result sql course SQL COURSE Sql Course SELECT employee_id, last_name, department_id WHERE last_name = 'higgins'; no rows selected SELECT employee_id, last_name, department_id WHERE LOWER(last_name) = 'higgins';

Character-Manipulation Functions These functions manipulate character strings: Function CONCAT('Hello', 'World') SUBSTR('HelloWorld',1,5) Result HelloWorld Hello LENGTH('HelloWorld') 10 INSTR('HelloWorld', 'W') 6 LPAD(salary,10,'*') *****24000 RPAD(salary, 10, '*') 24000***** REPLACE ('JACK and JUE','J','BL') TRIM('H' FROM 'HelloWorld') BLACK and BLUE elloworld 1-22 Copyright 2004, Oracle. All rights reserved.

Number Functions Function Result POWER(10,0.3010) 2 SQRT(121) 11 ROUND(45.926, 2) 45.93 TRUNC(45.926, 2) 45.92 CEIL, FLOOR POWER(10,2) 100 MOD(1600, 300) 100 SIN,COS,TAN LN,SINH,COSH SELECT SIN(1.57),COS(0),TAN(3.14/4), POWER(10,0.301),CEIL(1.1),FLOOR(1.9), LN(2.718282) FROM dual; 1-23 Copyright 2004, Oracle. All rights reserved.

Date Functions Function MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC Result Number of months between two dates Add calendar months to date Next day of the date specified Last day of the month Round date Truncate date Function Result MONTHS_BETWEEN ('01-SEP-95','11-JAN-94') 19.6774194 ADD_MONTHS ('11-JAN-94',6) '11-JUL-94' NEXT_DAY ('01-SEP-95','FRIDAY') '08-SEP-95' LAST_DAY ('01-FEB-95') '28-FEB-95' 1-24 Copyright 2004, Oracle. All rights reserved.

1-26 Copyright 2004, Oracle. All rights reserved. Using the TO_CHAR Function with Dates SELECT last_name, TO_CHAR(hire_date, 'fmdd Month YYYY') AS HIREDATE ;

1-27 Copyright 2004, Oracle. All rights reserved. Using the CASE Expression Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement: SELECT last_name, job_id, salary, CASE job_id WHEN 'IT_PROG' THEN 1.10*salary WHEN 'ST_CLERK' THEN 1.15*salary WHEN 'SA_REP' THEN 1.20*salary ELSE salary END "REVISED_SALARY" ; SELECT last_name,salary, CASE WHEN salary<5000 THEN 'Low' WHEN salary<10000 THEN 'Medium' WHEN salary<20000 THEN 'Good' ELSE 'Excellent' END qualified_salary ;

1-28 Copyright 2004, Oracle. All rights reserved. What Are Group Functions? Group functions operate on sets of rows to give one result per group. EMPLOYEES Maximum salary in the EMPLOYEES table

1-29 Copyright 2004, Oracle. All rights reserved. Using the AVG, SUM,MIN and MAX Functions You can use the AVG and SUM for numeric data. SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) WHERE job_id LIKE '%REP%'; SELECT MIN(hire_date), MAX(hire_date) ;

1-30 Copyright 2004, Oracle. All rights reserved. Creating Groups of Data EMPLOYEES 4400 9500 3500 6400 10033 Average salary in the EMPLOYEES table for each department

1-31 Copyright 2004, Oracle. All rights reserved. Using the GROUP BY Clause SELECT department_id, AVG(salary) GROUP BY department_id ; SELECT department_id dept_id, job_id, SUM(salary) GROUP BY department_id, job_id ;

1-32 Copyright 2004, Oracle. All rights reserved. Using the HAVING clause and inline view SELECT job_id, SUM(salary) PAYROLL WHERE job_id NOT LIKE '%REP%' GROUP BY job_id HAVING SUM(salary) > 13000 ORDER BY SUM(salary); SELECT T.qualified_salary, COUNT(*), SUM(SALARY) FROM (SELECT last_name, salary, CASE WHEN salary<5000 THEN 'Low' WHEN salary<10000 THEN 'Medium' WHEN salary<20000 THEN 'Good' ELSE 'Excellent' END qualified_salary ) T GROUP BY T.qualified_salary;

Displaying Data from Multiple Tables Copyright 2004, Oracle. All rights reserved.

1-34 Copyright 2004, Oracle. All rights reserved. Joining Column Names EMPLOYEES DEPARTMENTS Foreign key Primary key

1-35 Copyright 2004, Oracle. All rights reserved. Retrieving Records with the ON Clause SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id e JOIN departments d ON e.department_id = d.department_id;

1-36 Copyright 2004, Oracle. All rights reserved. Self-Joins Using the ON Clause EMPLOYEES (WORKER) EMPLOYEES (MANAGER) SELECT worker.last_name emp, manager.last_name mgr worker JOIN employees manager ON worker.manager_id = manager.employee_id;

1-37 Copyright 2004, Oracle. All rights reserved. Retrieving Records with Non-Equijoins SELECT e.last_name, e.salary, j.grade_level e JOIN job_grades j ON e.salary BETWEEN j.lowest_sal AND j.highest_sal;

1-38 Copyright 2004, Oracle. All rights reserved. LEFT,RIGHT and FULL OUTER JOIN SELECT e.last_name, e.department_id, d.department_name e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) ; SELECT e.last_name, e.department_id, d.department_name e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ; SELECT e.last_name, d.department_id, d.department_name e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ;

1-39 Copyright 2004, Oracle. All rights reserved. Using a subquery SELECT last_name 11000 WHERE salary > (SELECT salary WHERE last_name = 'Abel'); SELECT last_name, job_id, salary WHERE salary = (SELECT MIN(salary));

Example: IN versus Join 1-40 Copyright 2004, Oracle. All rights reserved. SELECT last_name, department_id, job_id WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = 1700); -- Versus (!?) SELECT last_name, e.department_id, job_id e, departments d WHERE e.department_id = d.department_id AND location_id = 1700; Set serveroutput on Exec sqlid('location_id = 1700')

Examine the execution plans 1-41 Copyright 2004, Oracle. All rights reserved.