Introduction to Standard Query Language Erik Zeitler UDBL

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

SQL DESIGN AND IMPLEMENTATION CONTENT SOURCES: ELAMSARI AND NAVATHE, FUNDAMENTALS OF DATABASE MANAGEMENT SYSTEMSELAMSARI AND NAVATHE, FUNDAMENTALS OF.
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
COMPANY schema EMPLOYEE
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
The Relational Algebra
Basic Queries. 2 Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database; the SELECT statement This is not the.
Database technology Lecture 2: Relational databases and SQL
FEN More about SELECT, Nested selects GROUP BY, HAVING, ORDER BY Other joins Aggregate functions Views More about SQL.
Database Design -- Basic SQL
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
Database Systems Chapter 6 ITM Relational Algebra The basic set of operations for the relational model is the relational algebra. –enable the specification.
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:
- relation schema, relations - database schema, database state
CS 104 Introduction to Computer Science and Graphics Problems Introduction to Database (2) Basic SQL 12/05/2008 Yang Song.
관계 연산자 & SQL. Selection SELECT * FROM r WHERE A=B AND D>5.
SQL The relational DB Standard CS-450 Dr. Ali Obaidi.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1 CREATE/DROP/ALTER TABLE Data types : char, varchar, decimal, date CREATE TABLE DEPARTMENT.
Al-Imam University Girls Education Center Collage of Computer Science 1 ST Semester, 1432/1433H Chapter 8 Part 4 SQL-99 Schema Definition, Constraints,
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
Final Review Dr. Bernard Chen Ph.D. University of Central Arkansas.
CS609 Introduction. Databases Current state? Future?
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
1 CSE 480: Database Systems Lecture 11: SQL. 2 SQL Query SELECT FROM WHERE –In MySQL, FROM and WHERE clauses are optional –Example:
Relational Algebra - Chapter (7th ed )
CS 380 Introduction to Database Systems Chapter 7: The Relational Algebra and Relational Calculus.
Onsdag The concepts in a relation data model SQL DDL DML.
Oracle DML Dr. Bernard Chen Ph.D. University of Central Arkansas.
 Employee (fname, minit, lname, ssn, bdate, address, sex, salary, superssn, dno)  Department (dname, dnumber, mgrssn, mgrstartdate) 
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
莊裕澤資料庫基本概念 1 Yuh-Jzer Joung 莊 裕 澤 Dept. of Information Management National Taiwan University February, 2002 資料庫管理與資訊科技.
NOEA/IT - FEN: Databases/SQL1 SQL – part 1 SQL: DDL and DML.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
Structured Query Language
DatabaseIM ISU1 Fundamentals of Database Systems Chapter 6 The Relational Algebra.
1/18/00CSE 711 data mining1 What is SQL? Query language for structural databases (esp. RDB) Structured Query Language Originated from Sequel 2 by Chamberlin.
1 Chapter 5 The SQL Language Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Query Processing – Implementing Set Operations and Joins Chap. 19.
FEN Introduction to the database field:  SQL: Structured Query Language Seminar: Introduction to relational databases.
COMP163 Database Management Systems September 18, 2008 Lecture 8 – Sections SQL Queries.
1 Database Systems Basic SQL. 2Outline  SQL Data Definition and Data Types  Specifying Constraints in SQL  Basic Retrieval Queries in SQL  INSERT,
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
1 COMP 1100 Basic SQL David J. Stucki. Outline SQL Overview Retrievals Schema creation Table creation Constraints Inserts Updates 2.
Relational Algebra COMP3211 Advanced Databases Nicholas Gibbins
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
CS580 Advanced Database Topics Chapter 8 SQL Irena Pevac.
The SQL Database Grammar
CS580 Advanced Database Topics
SQL: SchemaDefinition, Constraints, and Queries and Views
Chapter 4 Basic SQL.
6/22/2018.
Database Systems Basic SQL
Retrieval Queries in SQL(DML)
SQL: Structured Query Language DML- Queries Lecturer: Dr Pavle Mogin
376a. Database Design Dept. of Computer Science Vassar College
Subject Name: DATA BASE MANAGEMENT SYSTEM Subject Code: 10cs54
376a. Database Design Dept. of Computer Science Vassar College
11/9/2018.
Company Requirements.
Session - 6 Sequence - 2 SQL: The Structured Query Language:
SQL-99: Schema Definition, Constraints, and Queries and Views
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
SQL Grouping, Ordering & Arithmetics Presented by: Dr. Samir Tartir
SQL: Set Operations & Nested Queries. Presented by: Dr. Samir Tartir
Presentation transcript:

Introduction to Standard Query Language Erik Zeitler UDBL

Why a query language? Given some data, how should users and computer programs communicate with it? we need an interface to the data

SQL does the job Data Definition Language (DDL) Define/re-define database structure Data Manipulation Language (DML) Updates Queries Additional facilities Views Security, authorization Integrity constraints Transaction constraints Rules for embedding SQL statements into other languages

Outline Overview What can SQL do for you? Background and a simple example SQL and the relational data model Example queries NULL values and 3-valued logic Example queries

Background History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SQL (ANSI 1986), SQL1 or SQL86 SQL2 or SQL92 SQL3 or SQL99 Core specification and optional specialized packages SQL consists of ~20 basic commands A lot of research money for each SQL command… Standard language for all commercial DBMS Each DBMS has features outside standard

Terminology Theoretical foundation: The relational data model relation–table tuple–row attribute–column column 1 …column n …

Example database Schema diagram, datbase state (E/N ch 5, p ) (c) Addison Wesley Longman Inc

CREATE TABLE employee ( fname varchar(100), minit char(1), lname varchar(100), ssn int(10) unsigned NOT NULL, bdate date, address varchar(100), sex char(1), salary int(10), superssn int(10), dno int(10), PRIMARY KEY (ssn) ) ;

unix$ mysql –u root –p >CREATE DATABASE comp; >CONNECT comp; >CREATE TABLE emp ( fname varchar(100), lname varchar(100), ssn bigint unsigned NOT NULL PRIMARY KEY (ssn) ); >INSERT INTO emp VALUES( ’Erik’, ’Zeitler’, ); >SELECT * FROM emp; > SELECT fname FROM emp; ##

Recommendation Download & install on your PC Excellent reference manuals on the web sites

Basic query statement: select – from – where SELECT A 1, A 2, …, A n FROM r 1, r 2, …, r m WHERE P; A 1, A 2, …, A n – list of attribute names to be retrieved r 1, r 2, …, r m – List of tables required to process the query P – Conditional expression identifying the tuples to be retrieved AND, OR, NOT, =, > Result of the query is a table

SQL and the relational data model Projection Cartesian product Selection Set operations Union Difference Intersection Assignment operator Rename relations Join  join Equijoin Natural join

Relation algebra projection Projection is done in the SELECT clause: Ex 1, Look at interesting fields > select * from employee; > select fname from employee; > select fname, bdate from employee; The star (*) denotes ”all attributes” Ex 2, projection! > select x,y,z from vectors; > select x,y from vectors;

The SQL SELECT clause Projection Remove duplicates: distinct > select plocation from project; > select distinct plocation from project; Arithmetic expressions > select x/10, (y*z)/2, z+3 from vectors; > select ssn, salary, salary*.327 from employee; # #

Relational algebra selection SELECT A 1, A 2, …, A n FROM r 1, r 2, …, r m WHERE P; P is the selection predicate operates on attributes in relations r 1, r 2, …, r m Selects tuples to be returned selection  filtering Selection in SQL: The WHERE clause  

The SQL WHERE clause Ex 1, Look for employee info >select * from employee where fname=’John’; Ex 3, vector length! >select x,y,z from vectors where x > 10 and x*x+y*y+z*z < 200; Ex 2, Look for employee info >select * from employee where bdate > ’ ’ and salary between and 50000;

Rel. algebra Cartesian product Similar to Cartesian product of two vectors The Cartesian product forms all possible pairs of the elements of the operands

The SQL FROM clause Similarly, given two database tables persons Alex John Mike cars Audi BMW Mercedes select * from persons, cars; AlexAudi JohnAudi MikeAudi AlexBMW JohnBMW MikeBMW AlexMercedes JohnMercedes MikeMercedes, this SQL query generates all possible persons-cars combinations. x= More… ##

Select … from … where revisited Relational algebra Cartesian product Selection Projection Basic SQL query: three clauses select from where

Select – from – where Ex 1: Find all employees working at research dept SELECTEMPLOYEE.LNAME, ADDRESS FROMEMPLOYEE, DEPARTMENT WHEREDEPARTMENT.NAME=‘Research’ AND DNUMBER=DNO; Ex 2: SELECTE.FNAME, E.LNAME, S.FNAME, S.LNAME FROMEMPLOYEE E, EMPLOYEE S WHEREE.SUPERSSN=S.SSN; All employees and their managers

SQL and the relational data model SELECT … FROM … WHERE …  projection, cartesian product, selection Set operations Union Difference Intersection Assignment operator Rename relations Join  join Equijoin Natural join Operands must be union compatible

Examples of set operations Retrieve all first names in the database >select fname from employee union select dependent_name from dependent; Are there any projects in a town without departments? >select plocation FROM project p except select dlocation FROM dept_locations; #

SQL and the relational data model Assignment operator Rename relations Join  join Equijoin Natural join SELECT … FROM … WHERE …  projection, cartesian product, selection Set operations Union – union Difference – except Intersection – intersect

Rename, assignment Rename: as >select distinct superssn as ’manager social security number’ from employee; Assignment: create table … as select … >create table names as select fname from employee union select dependent_name from dependent;

SQL and the relational data model Assignment operator Rename relations Join  join Equijoin Natural join SELECT … FROM … WHERE …  projection, cartesian product, selection Set operations Union – union Difference – except Intersection – intersect

Join Relational algebra notation: R C S C – join condition C is on the form A R  A S  is one of {=,, ≤, ≥,  } Several terms can be connected as C 1 C 2 …C K. Special cases Equijoin:  is = Natural join: All identically named attributes in relations R and S have matching values

SQL join Recall this query SELECTEMPLOYEE.LNAME, ADDRESS FROMEMPLOYEE, DEPARTMENT WHEREDEPARTMENT.NAME=‘Research’ AND DNUMBER=DNO; Equijoin of employee and department tables w.r.t. employee.dnumber and department.dno. Joins are cartesian products with some selection criteria

SQL join Another way: alter table project change pnumber pno int(10);

One more example Show the resulting salaries if every employee working on the ‘ProductX’ project is given a 10 percent raise SELECTFNAME, LNAME, 1.1*SALARY AS INC_SAL FROMEMPLOYEE, WORKS_ON, PROJECT WHERESSN=ESSN AND PNO=PNUMBER AND PNAME=‘ProductX’;

Special comparison Matching string patterns Use LIKE % for any number of arbitrary symbol _ for any symbol select * from employee where address like ’%Houston%’; Approx math equality Use abs(x-x 1 ) <  select * from employee where abs(salary-30000) < 8000; Use BETWEEN: select * from employee where salary between and 38000;

NULL values Sometimes an attribute is Unknown(date of birth unknown) Unavailable/withheld(refuses to list home phone #) Not applicaple(last college degree) Need to represent these cases in a DB! Solution: NULL. What about logical operations involving NULL?  Need to extend logic…

3-valued logic ANDTRUEFALSEUNKNOWN TRUE FALSEUNKNOWN FALSE UNKNOWN FALSEUNKNOWN ORTRUEFALSEUNKNOWN TRUE FALSETRUEFALSEUNKNOWN TRUEUNKNOWN NOTTRUEFALSEUNKNOWN FALSETRUEUNKNOWN

Comparison of NULL values =, , >, <, LIKE, … won’t work. NULL is UNDEFINED! SQL check for NULL IS NULL IS NOT NULL JOIN operations Tuples with NULL values in the join columns  Not included in result Exception: OUTER JOIN (E/N 8.5.6)

NULL Find out who is The Big Boss select fname, lname from employee where superssn is NULL;

Aggregate functions Avg–average value Min–minimum value Max–maximum value Sum–sum of values Count–number of values

Aggregate functions – group by Average salary select avg(salary) from employee; Average salary at each department select dname, avg(salary) from employee, department where dno=dnumber group by dno;

Aggregate functions – HAVING Find the projects that more than two employees are assigned to: retrieve the project number, its name, and the number of its employees SELECT project.pnumber, pname, count(*) FROM project, works_on WHERE project.pnumber = works_on.pno GROUP BY project.pnumber, pname HAVING count(*)>2;

Summary Clauses: SELECT FROM [WHERE ] [GROUP BY [HAVING ] [ORDER BY ] More Than One Way To Do It™…

Views Frequently posed queries should be expressed as views. >create view tax_view as select ssn, salary, salary*.327 from employee; >select * from tax_view;

Views Creating a view will not result in a new table. Views are not tables themselves – they are views of the underlying tables. A view query will return the state of the underlying tables. Consequence: underlying tables are changed  the view will change

Views Ex 1: >update table employee set salary = where ssn = ; >select * from tax_view; Ex 2: We are removing one column! >alter table employee drop salary; The view will not work any more >select * from tax_view;