Structured Query Language ( 結構化查詢語言 ) Database Programming CREATE TABLE … ALTER TABLE… ADD/DROP/MODIFY (…) DESC … DROP TABLE … RENAME … TO … INSERT INTO.

Slides:



Advertisements
Similar presentations
SQL – Lesson II Grade 12.
Advertisements

Virtual training week 4 structured query language (SQL)
SQL Review Sections 1 - SQL and other basic statements.
Session 4 SQL Structured Query Language. SQL Modes of use –Interactive –Embedded Purpose –Create database –Create, Read, Update, Delete.
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 9 Structured Query Language.
Restricting and Sorting Data. Consider the table employee(employee_id,last_name,job_id, department_id ) assume that you want to display all the employees.
Structured Query Language Part I Chapter Three CIS 218.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Design Sections 16 & 17 – Columns, Characters, Rows, Concatenations, DISTINCT, DESCRIBE, Logical Operators, Order of Operations, Sorting 9/26/2011.
Microsoft Access 2010 Chapter 7 Using SQL.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
Structured Query Language Introduction to SQL What is SQL? – –When a user wants to get some information from a database file, he can issue a query.1.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
Introduction to SQL J.-S. Chou Assistant Professor.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
Restricting and Sorting Data. ◦ Limiting rows with:  The WHERE clause  The comparison conditions using =,
2 Copyright © Oracle Corporation, All rights reserved. Restricting and Sorting Data.
2 Copyright © 2004, Oracle. All rights reserved. Restricting and Sorting Data.
4 Copyright © 2006, Oracle. All rights reserved. Restricting and Sorting Data.
LECTURE 8.  Consider the table employee(employee_id,last_name,job_id, department_id )  assume that you want to display all the employees in department.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
SQL (DDL & DML Commands)
Using Special Operators (LIKE and IN)
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
STRUCTURED QUERY LANGUAGE SQL-II IST 210 Organization of Data IST210 1.
Comp12 cont…. Using Quotes Note that we have used single quotes around the conditional values in the examples. SQL uses single quotes around text values.
Structured Query Language ( 結構化查詢語言 ) Lesson Review What is S Q L?L? When a user wants to get some information from a database file, he can issue a _______.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Database Design Sections 17 & 18 – Concatenations, DISTINCT, DESCRIBE, Logical Operators, Order of Operations, Sorting.
Copyright © 2004, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement Satrio Agung Wicaksono, S.Kom., M.Kom.
Copyright © 2004, Oracle. All rights reserved. Lecture 4: 1-Retrieving Data Using the SQL SELECT Statement 2-Restricting and Sorting Data Lecture 4: 1-Retrieving.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
IS6146 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure robgleasure.com.
Hassan Tariq INTRODUCTION TO SQL What is SQL? –When a user wants to get some information from a database file, he can issue a query. – A query is a user–request.
# 1# 1 QueriesQueries How do we ask questions of the data? What is SELECT? What is FROM? What is WHERE? What is a calculated field? Spring 2010 CS105.
SQL BY MR.PRASAD SAWANT INDIA Introduction to SQL What is SQL? –When a user wants to get some information from a database file, he can issue a query.1.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
Database Design Sections 17 & 18 – Columns, Characters, Rows, Concatenations, DISTINCT, DESCRIBE, Logical Operators, Order of Operations, Sorting.
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.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
Oracle 10g Retrieving Data Using the SQL SELECT Statement.
1 Copyright © 2009, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Restricting and Sorting Data
MySQL DML Commands By Prof. B.A.Khivsara
Writing Basic SQL SELECT Statements
The Database Exercises Fall, 2009.
Structured Query Language
Structured Query Language (II) (結構化查詢語言)
SQL.
Introduction To Structured Query Language (SQL)
Introduction To Structured Query Language (SQL)
CSC 453 Database Systems Lecture
Shelly Cashman: Microsoft Access 2016
Restricting and Sorting Data
Presentation transcript:

Structured Query Language ( 結構化查詢語言 )

Database Programming CREATE TABLE … ALTER TABLE… ADD/DROP/MODIFY (…) DESC … DROP TABLE … RENAME … TO … INSERT INTO … VALUES (…) SELECT * FROM … Lesson Review:

Updating Data in a Table UPDATE TableName SET Column1 = NewValue1, Column2 = NewValue2 WHERE Condition(s) The WHERE clause is optional.

Delete Records from a Table DELETE FROM TableName WHERE Condition(s) The WHERE clause is optional.

What is S Q L?L? When a user wants to get some information from a database file, he can issue a _______. A query is a user–request to retrieve data or information with a certain ___________. Structured Query Language(SQL) ( 結構化查詢語言 ) Most ___________________________ (DBMS) support SQL. e.g. Oracle query condition Database Management System

Basic structure of an SQL query SELECT * / Column1, Column2, … FROM TableNames

Retrieve data with specified selection criteria SELECT Column1, Column2, … FROM TableNames WHERE Conditions OperatorDescription =Equal to <> or != or ^= Not Equal to >Greater/ Larger than <Less/ Smaller than >=Greater or equal to <=Less or equal to BETWEENWithin the range LIKEMatch the pattern

Comparison operators Examples WHERE event_date = ' 01-JAN-04' WHERE rental_fee >=2000 WHERE cd_title = ' White Rose' You may also see the <> (not equal to) symbol written as != or ^ = In the example shown from the DJ on Demand database, which rows will be selected? Will salaries of 3000 be included in the results set? SELECT last_name, salary FROM employees WHERE salary <= 3000

table Aliases – Column Headings

Concatenation – Link columns

Retrieve value(s) without Duplication SELECT DISTINCT Column1, Column2, … FROM TableNames WHERE Conditions

SELECT title, year FROM d_cds WHERE year BETWEEN '1999' AND '2001‘ Comparison Operators BETWEEN…AND

SELECT title, type_code FROM d_songs WHERE type_code IN ( 77, 12 ) IN

LIKE The % symbol is used to represent any sequence of zero or more characters. The underscore (_ ) symbol is used to represent a single character. In the example shown below, all employees with last names beginning with any letter followed by an "o" and then followed by any other number of letters will be returned. SELECT last_name FROM employees WHERE last_name LIKE '_o%' Which of the following last names could have been returned from the above query? 1. Sommersmith 2. Oog 3. Fong 4. Mo If you said 1, 2, 3, and 4, you're correct!

IS NULL, IS NOT NULL The IS NULL condition tests for unavailable, unassigned, or unknown data. IS NOT NULL tests for data that is present in the database. In this example, the WHERE clause is written to retrieve all the last names and manager IDs of those employees who do not have a manager. SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL Read the following and explain what you expect will be returned: SELECT first_name, last_name, auth_expense_amt FROM d_partners WHERE auth_expense_amt IS NOT NULL

LOGICAL CONDITIONS Logical conditions combine the result of two component conditions to produce a single result based on them. For example, to attend a rock concert, you need to buy a ticket AND have transportation to get there. If both conditions are met, you go to the concert. AND In the query below, the results returned will be rows that satisfy BOTH conditions specified in the WHERE clause. SELECT id, title, duration, type_code FROM d_songs WHERE id > 40 AND type_code = 77

OR If the WHERE clause uses the OR condition, the results returned from a query will be rows that satisfy either one of the OR conditions. In other words, all rows returned have an ID greater than 40 OR they have a type_code equal to 77. SELECT id, title, duration, type_code FROM d_songs WHERE id > 40 OR type_code = 77

SELECT title, type_code FROM d_songs WHERE type_code NOT IN 77 NOT

SELECT title, year FROM d_cds ORDER BY year ORDER BY

e.g. ROUND(45.926, 2) -> TRUNC (45.926, 2) -> MOD( 1600 / 300) -> 100

Tutorial Exercise Example: Database (stud.dbf)

General Structure I List the names and ages (1 d.p.) of 1B girls. List the names and ages (1 d.p.) of 1B girls. 1B Girls ?

Condition for "1B Girls": 1)class = "1B" 2)sex = "F" 3)Both ( AND operator) General Structure I List the names and ages (1 d.p.) of 1B girls.

General Structure I List the names and ages (1 d.p.) of 1B girls. List the names and ages (1 d.p.) of 1B girls. What is "age"?

Functions: # days :SYSDATE – dob # years :(SYSDATE – dob) / d.p.:ROUND(__, 1) General Structure I List the names and ages (1 d.p.) of 1B girls. List the names and ages (1 d.p.) of 1B girls.

List the names and ages (1 d.p.) of 1B girls. SELECT class, sex, name, ROUND((SYSDATE-dob)/365,1) AS "age" FROM stud WHERE class='1B' AND sex='F' General Structure I

Tutorial Exercise Time

SELECT last_name, specialty, auth_expense_amt FROM d_partners WHERE specialty ='All Types' OR specialty IS NULL AND auth_expense_amt = SELECT last_name, specialty, auth_expense_amt FROM d_partners WHERE (specialty ='All Types' OR specialty IS NULL) AND auth_expense_amt =

ComparisonII expr IN ( value1, value2, value3) expr BETWEEN value1 AND value2 expr LIKE "%_"

ComparisonII eg. 6 List the 1A students whose Math test score is between 80 and 90 (incl.) SELECT name, mtest FROM student ; WHERE class="1A" AND ; mtest BETWEEN 80 AND 90 Result

ComparisonII eg. 7 List the students whose names start with "T". SELECT name, class FROM student ; WHERE name LIKE "T%" Result

ComparisonII eg. 8 List the Red house members whose names contain "a" as the 2nd letter. eg. 8 List the Red house members whose names contain "a" as the 2nd letter. SELECT name, class, hcode FROM student ; WHERE name LIKE "_a%" AND hcode="R" Result

GroupingIII SELECT FROM WHERE condition ; GROUP BY groupexpr [HAVING requirement] Group functions: COUNT( ), SUM( ), AVG( ), MAX( ), MIN( ) COUNT( ), SUM( ), AVG( ), MAX( ), MIN( ) –groupexpr specifies the related rows to be grouped as one entry. Usually it is a column. –WHERE condition specifies the condition of individual rows before the rows are group. HAVING requirement specifies the condition involving the whole group.

GroupingIII eg. 11 List the number of students of each class. eg. 11 List the number of students of each class.

COUNT( ) Group By Class 1A1A1A1A COUNT( ) 1B1B1B1B 1C1C1C1C 1A1A1A1A 1B1B1B1B 1C1C1C1C Student class 1A1A1A1A 1A1A1A1A 1A1A1A1A 1B1B1B1B 1B1B1B1B 1B1B1B1B 1B1B1B1B 1B1B1B1B 1B1B1B1B 1C1C1C1C 1C1C1C1C 1C1C1C1C

GroupingIII SELECT class, COUNT(*) FROM student ; GROUP BY class eg. 11 List the number of students of each class. eg. 11 List the number of students of each class. Result

GroupingIII eg. 12 List the average Math test score of each class. eg. 12 List the average Math test score of each class.

Group By Class AVG( ) 1A1A1A1A 1B1B1B1B 1C1C1C1C Student class 1A1A1A1A 1A1A1A1A 1A1A1A1A 1B1B1B1B 1B1B1B1B 1B1B1B1B 1B1B1B1B 1B1B1B1B 1B1B1B1B 1C1C1C1C 1C1C1C1C 1C1C1C1C

GroupingIII eg. 12 List the average Math test score of each class. eg. 12 List the average Math test score of each class. SELECT class, AVG(mtest) FROM student ; GROUP BY class Result

GroupingIII eg. 13 List the number of girls of each district. eg. 13 List the number of girls of each district. SELECT dcode, COUNT(*) FROM student ; WHERE sex="F" GROUP BY dcode Result

GroupingIII eg. 14 List the max. and min. test score of Form 1 students of each district. eg. 14 List the max. and min. test score of Form 1 students of each district. SELECT MAX(mtest), MIN(mtest), dcode ; FROM student ; WHERE class LIKE "1_" GROUP BY dcode Result

GroupingIII eg. 15 List the average Math test score of the boys in each class. The list should not contain class with less than 3 boys. eg. 15 List the average Math test score of the boys in each class. The list should not contain class with less than 3 boys. SELECT AVG(mtest), class FROM student ; WHERE sex="M" GROUP BY class ; HAVING COUNT(*) >= 3 Result

Display Order IV SELECT FROM WHERE GROUP BY..... ; ORDER BY colname ASC / DESC

Display Order IV SELECT name, id FROM student ; WHERE sex="M" AND class="1A" ORDER BY name eg. 16 List the boys of class 1A, order by their names. eg. 16 List the boys of class 1A, order by their names. ORDER BY dcode Result

Display Order IV SELECT name, id, class, dcode FROM student ; WHERE class="2A" ORDER BY dcode eg. 17 List the 2A students by their residential district. eg. 17 List the 2A students by their residential district. Result

Display Order IV SELECT COUNT(*) AS cnt, dcode FROM student ; GROUP BY dcode ORDER BY cnt DESC eg. 18 List the number of students of each district eg. 18 List the number of students of each district (in desc. order). Result

Display Order IV SELECT name, class, hcode FROM student ; WHERE sex="M" ORDER BY hcode, class eg. 19 List the boys of each house order by the classes. (2-level ordering) eg. 19 List the boys of each house order by the classes. (2-level ordering)

Display Order IV Result Order by class Blue House Green House : : Order by hcode

Union, Intersection and Difference of Tables Union, Intersection and Difference of Tables3 AB The union of A and B (A  B) A table containing all the rows from A and B.

Union, Intersection and Difference of Tables Union, Intersection and Difference of Tables3 The intersection of A and B (A  B) A table containing only rows that appear in both A and B. AB

Union, Intersection and Difference of Tables Union, Intersection and Difference of Tables3 The difference of A and B (A–B) A table containing rows that appear in A but not in B. AB

3 Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: The Situation: Bridge Club & Chess Club field typewidth contents id numeric 4 student id number name character 10 name sex character 1 sex: M / F class character 2 class

Union, Intersection and Difference of Tables 3

Union, Intersection and Difference of Tables Union, Intersection and Difference of Tables3 SELECT * FROM bridge ; UNION ; SELECT * FROM chess ; ORDER BY class, name INTO TABLE party eg. 22 The two clubs want to hold a joint party. Make a list of all students. (Union) eg. 22 The two clubs want to hold a joint party. Make a list of all students. (Union) SELECT FROM WHERE ; UNION ; SELECT FROM WHERE Result

Union, Intersection and Difference of Tables Union, Intersection and Difference of Tables3 SELECT * FROM bridge ; WHERE id IN ( SELECT id FROM chess ) ; TO PRINTER eg. 23 Print a list of students who are members of both clubs. (Intersection) eg. 23 Print a list of students who are members of both clubs. (Intersection) SELECT FROM table1 ; WHERE col IN ( SELECT col FROM table2 ) Result

Union, Intersection and Difference of Tables Union, Intersection and Difference of Tables3 SELECT * FROM bridge ; WHERE id NOT IN ( SELECT id FROM chess ) ; INTO TABLE diff eg. 24 Make a list of students who are members of the Bridge Club but not Chess Club. (Difference) eg. 24 Make a list of students who are members of the Bridge Club but not Chess Club. (Difference) SELECT FROM table1 ; WHERE col NOT IN ( SELECT col FROM table2 ) Result