Copyright 1998-2008 Curt Hill SQL Queries Yet Another Set of Query Features.

Slides:



Advertisements
Similar presentations
WHERE Clause Chapter 2. Objectives Limit rows by using a WHERE clause Use the LIKE operator Effect of NULL values Use compound conditions Use the BETWEEN.
Advertisements

© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Copyright © 2007, Oracle. All rights reserved Using Single-Row Functions to Customize Output Modified: October 21, 2014.
Structured Query Language - SQL Carol Wolf Computer Science.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
©Silberschatz, Korth and Sudarshan3.1Database System Concepts - 6 th Edition SQL Schema Changes and table updates instructor teaches.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
IFS Intro. to Data Management Chapter 6 Filtering your data.
Copyright © Curt Hill SQL The Data Definition Language.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
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.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Copyright © Curt Hill The Relational Algebra What operations can be done?
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
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.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Copyright © Curt Hill Query Evaluation Translating a query into action.
Copyright © 2013 Curt Hill Database Security An Overview with some SQL.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
WHAT IS A DATABASE? A DATABASE IS A COLLECTION OF DATA RELATED TO A PARTICULAR TOPIC OR PURPOSE OR TO PUT IT SIMPLY A GENERAL PURPOSE CONTAINER FOR STORING.
Chapter 3 Selected Single-Row Functions and Advanced DML & DDL.
Instructor: Craig Duckett Lecture 08: Thursday, October 22 nd, 2015 Patterns, Order of Evaluation, Concatenation, Substrings, Trim, Position 1 BIT275:
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Copyright © Curt Hill Queries in SQL More options.
Copyright © Curt Hill Joins Revisited What is there beyond Natural Joins?
IFS Intro to Data Management Chapter 5 Getting More Than Simple Columns.
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.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
Copyright 2003 Curt Hill Queries in SQL Syntax and semantics.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
6 Copyright © Oracle Corporation, All rights reserved. Subqueries.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
Web Programming MySql JDBC Web Programming.
Copyright © Curt Hill The Relational Calculus Another way to do queries.
2 Copyright © 2009, Oracle. All rights reserved. Restricting and Sorting Data.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Restrictions Objectives of the Lecture : To consider the algebraic Restrict operator; To consider the Restrict operator and its comparators in SQL.
SQL advanced select using Oracle 1 Multiple Tables: Joins and Set Operations Subqueries: Nested Queries.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
Gollis University Faculty of Computer Engineering Chapter Five: Retrieval, Functions Instructor: Mukhtar M Ali “Hakaale” BCS.
Copyright © Curt Hill SQL The Data Manipulation Language.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Relational Database Design
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL
Subqueries Schedule: Timing Topic 25 minutes Lecture
Database Systems: Design, Implementation, and Management Tenth Edition
Topics The if Statement The if-else Statement Comparing Strings
SQL: Structured Query Language DML- Queries Lecturer: Dr Pavle Mogin
Basic SQL Lecture 6 Fall
Topics The if Statement The if-else Statement Comparing Strings
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
The Java switch Statement
Subqueries Schedule: Timing Topic 25 minutes Lecture
Database Systems: Design, Implementation, and Management Tenth Edition
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

Copyright Curt Hill SQL Queries Yet Another Set of Query Features

Features to Consider Arithmetic operations Functions Set operations Nested queries Copyright Curt Hill

Arithmetic Numeric fields and constants may be part of an arithmetic expression –In Where or Select These include the standard: * / + - MySQL and SQL Server accept the % as modulo Standard precedence exists and parentheses may override There are also other many functions Copyright Curt Hill

Arithmetic Example Considering the age at which a faculty member started: select f_name, (f_age - f_years) "Starting age" from faculty where f_age - f_years > 40 The parentheses clarify the statement but are not needed Copyright Curt Hill

Functions There are a number of functions that may be used anywhere a field name be be used The classifications include: –Mathematical functions –String functions Copyright Curt Hill

Mathematical ABS – Absolute value –Takes one numeric parameter –Usually a field Round –See next screen Trig functions –Sin, cos, tan are available Others –Each DBMS may have others as well Copyright Curt Hill

Round The first parameter is a numeric expression –This is the only required parameter The second is the number of digits to right of decimal –This one is optional Thus: Round(s_balance) Round(avg(s_balance),2) Oracle has a Trunc, SQL Server Floor Copyright Curt Hill

String functions Substr(field,start,length) –SQL Server – SubString –Substr(f_name,1,4) gives first four characters of the name Length –Gives the length of a character field –Oracle gives field width for fixed length fields and actual length for variable length fields –MySQL disregards trailing blanks for fixed length –SQL Server: Len Copyright Curt Hill

More String Functions Instr – Find a string in an expression –Returns position –Instr(crs_title,’Econ’)>0 is true for titles containing this string –Oracle and MySQL Lower and Upper –Convert letters to lower or upper case Copyright Curt Hill

Word Operators for Where Between –Allows use of a range Null –Checks for missing value Like –A partial rather than full match In –Set Membership Copyright Curt Hill

Between Allows a range: Where s Between 25 And 50 The range is inclusive This is the same as: Where s >= 25 AND s <= 50 The values in the range could involve operators or other fields This can be negated as well Copyright Curt Hill

Example Between Find the mid-career faculty: select f_name, f_age from faculty where f_age between 30 and 50 This produces 13 rows Copyright Curt Hill

Negated Between Find those outside a range select f_name, f_age from faculty where f_age not between 30 and 50 Or select f_name, f_age from faculty where not f_age between 30 and 50 MySQL must have parentheses around range in last one Copyright Curt Hill

Null Special value that means there is no value for this field Not the same as: –Zero –Blank –Empty string Usually obtained by an Insert statement with fewer values than the maximum Possible to require a column have a value A Primary Key may not be null Copyright Curt Hill

Example Is there a value? select * from students where s_address is Null The Not may also be applied before Null or before s_address –MySQL requires: Where not (s_address is Null) in latter case Copyright Curt Hill

Like Expression Like Pattern Pattern allows two wild cards –% Any number of any character –_ Any one character –Most other characters appear as themselves –SQL Server also allows –[ ] contains allowables –[^ ] any but these Copyright Curt Hill

Example This will find any course with an I in title: select * from course where crs_title like '% I%' Results in 5 rows Leaving out the trailing % gives only 3 rows This should be examined in the demonstration! Copyright Curt Hill

Finally on Like The Not may precede the Like to negate the whole condition There is a trailing clause that allows selection of an escape character: crs_title like ‘%\_%’ escape ‘\’ Any character may be in the final string It is then used to precede one of the wild cards Copyright Curt Hill

Set Membership In is reserved word Produces a boolean S in (1,4,5,10) It is true if s is any of the items Much easier than many equal clauses connected with Ors The set items do not have to be numeric

Example of In Find faculty in Math, CIS or MGMT: select * from faculty where upper(f_dept) in ('MATH', 'CIS', 'MGMT') Results in 6 rows The Not may be applied before the In or before the Upper –MySQL requires parentheses if before upper Copyright Curt Hill

Sub-Queries or Nested Queries An in needs a set –Often a constant parenthesized set A query produces a set A nested query is a full query inside the Where clause of a Select Generally the sub-query produces a set of tuples with a single field used in an IN Query is inside parentheses

Copyright Curt Hill Example Sub-query MS Divisional classes Select * From course Where crs_dept IN (Select dp_acronym From depart Where dp_division = 'S')

Copyright Curt Hill Sub-Query Notes The sub-query is never seen –It is resource for the outer query The sub-query may not use any of the following clauses: –Into, order by, group by –Why is there need to use these? Besides IN there is also –All - All the sub-query meets some test The for all (  ) –Exists – One meets the test –These come from the relational calculus

Copyright Curt Hill Another example Student who got only As or Bs in CS classes select s_name, s_id from students where 80 <= ALL( Select g_score From grades WHERE s_id = g_naid AND g_dept = 'CS') The problem is that this gives way too many: 67

Problem: Nulls Any student who took no classes in CS gets an empty table The comparison becomes 80 <= Null The DBMS does not know what to do with this so calls it true –Which is not what we want How do we fix this? Copyright Curt Hill

Use an exists Disallow empty sub-query tables select s_name, s_id from students where 80 <= ALL( Select g_score From grades WHERE s_id = g_naid AND g_dept = 'CS') AND Exists (Select g_score From grades WHERE s_id = g_naid AND g_dept = 'CS') Copyright Curt Hill

What’s wrong with that? Lots of coding Will the two sub-queries cost more than one? If the query optimizer is good then no –It will recognize that the two sub- queries are the same and only do once Otherwise yes There may be other ways as well Copyright Curt Hill

Relationship of sub-query to main query The scope of names in the parentheses is just the parentheses Nothing but the set produced in the sub-query may be used outside Things in the outside query may be used inside The nested query may be independent It may be correlated

Copyright Curt Hill Examples Independent It has no values that are related to the main query Previous example of finding MS Divisional classes Correlated The main query injects values into the sub-query Previous example of finding students who got an A or B in a CS class