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

Similar documents
Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL

The SQL data-definition language (DDL) allows defining :

QQ Group

Explain in words what this relational algebra expression returns:

CS 582 Database Management Systems II

SQL. Lecture 4 SQL. Basic Structure. The select Clause. The select Clause (Cont.) The select Clause (Cont.) Basic Structure.

CS425 Fall 2017 Boris Glavic Chapter 4: Introduction to SQL

Lecture 6 - More SQL

1) Introduction to SQL

Database Systems SQL SL03

Unit 2: SQL AND PL/SQL

Lecture 3 SQL. Shuigeng Zhou. September 23, 2008 School of Computer Science Fudan University

Database Systems SQL SL03

Chapter 4: SQL. Basic Structure

Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations Views Modification of the Database Data Definition

SQL (Structured Query Language)

Database System Concepts, 5th Ed.! Silberschatz, Korth and Sudarshan See for conditions on re-use "

DATABASE TECHNOLOGY - 1MB025

DATABASE TECHNOLOGY - 1MB025

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

DATABASTEKNIK - 1DL116

Chapter 3: SQL. Database System Concepts, 5th Ed. Silberschatz, Korth and Sudarshan See for conditions on re-use

Chapter 3: SQL. Chapter 3: SQL

Silberschatz, Korth and Sudarshan See for conditions on re-use

DATABASE DESIGN I - 1DL300

The SQL database language Parts of the SQL language

Relational Algebra. Procedural language Six basic operators

An Introduction to Structured Query Language

An Introduction to Structured Query Language

DATABASE TECHNOLOGY. Spring An introduction to database systems

An Introduction to Structured Query Language

Set theory is a branch of mathematics that studies sets. Sets are a collection of objects.

CSCB20 Week 3. Introduction to Database and Web Application Programming. Anna Bretscher Winter 2017

An Introduction to Structured Query Language

An Introduction to Structured Query Language

Relational Algebra and SQL

SQL. Char (30) can store ram, ramji007 or 80- b

Principles of Data Management

Simple SQL Queries (2)

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Database Management Systems,

CSC Web Programming. Introduction to SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

UNIT III INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL)

CSEN 501 CSEN501 - Databases I

Database Management Systems,

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

QUIZ 1 REVIEW SESSION DATABASE MANAGEMENT SYSTEMS

CMPT 354: Database System I. Lecture 3. SQL Basics

CSCB20 Week 4. Introduction to Database and Web Application Programming. Anna Bretscher Winter 2017

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Database design process

Midterm Review. Winter Lecture 13

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Slides by: Ms. Shree Jaswal

CMPT 354: Database System I. Lecture 2. Relational Model

Database Management Systems,

Structured Query Language (SQL)

Querying Data with Transact SQL

CS3DB3/SE4DB3/SE6M03 TUTORIAL

SQL STRUCTURED QUERY LANGUAGE

Chapter 6: Formal Relational Query Languages

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

STRUCTURED QUERY LANGUAGE (SQL)

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Database Technology. Topic 3: SQL. Olaf Hartig.

Relational Database: The Relational Data Model; Operations on Database Relations

Database Languages. A DBMS provides two types of languages: Language for accessing & manipulating the data. Language for defining a database schema

Review. Objec,ves. Example Students Table. Database Overview 3/8/17. PostgreSQL DB Elas,csearch. Databases

Introduction SQL DRL. Parts of SQL. SQL: Structured Query Language Previous name was SEQUEL Standardized query language for relational DBMS:

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

SQL functions fit into two broad categories: Data definition language Data manipulation language

CSIE30600 Database Systems Basic SQL 2. Outline

SQL - Data Query language

Oracle Database SQL Basics

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table

SQL Functions (Single-Row, Aggregate)

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

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Tables From Existing Tables

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

Querying Data with Transact-SQL

CSCC43H: Introduction to Databases. Lecture 4

Unit 1 - Chapter 4,5

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Introduction to Oracle9i: SQL

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

Unit Assessment Guide

Exam code: Exam name: Database Fundamentals. Version 16.0

A subquery is a nested query inserted inside a large query Generally occurs with select, from, where Also known as inner query or inner select,

Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

SQL Overview. CSCE 315, Fall 2017 Project 1, Part 3. Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch

Chapter 4: Intermediate SQL

Transcription:

SQL KEREM GURBEY

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

DATA DEFINITION Data-definition language (DDL) provides commands for: Defining relation schemas, Determine the domain for each attribute (char, int, etc.) Determine integrity constraints (not null, primary key etc.) Deleting them, Modifying them

BASIC RELATION DEFINITION CREATE TABLE <name_of_relation> ( <attribute_name> <data_type> <constraint>*, <attribute_name> <data_type> <constraint>*, <integrity_constraint>, <integrity_constraint>, ); E.g: CREATE TABLE department ( dept_name varchar (20), building varchar (15), budget numeric (12,2), PRIMARY KEY (dept_name));

DATA TYPES char(n): A fixed-length character string with user-specified length n. The full form, character, can be used instead. varchar(n): A variable-length character string with user-specified maximum length n. The full form, character varying, is equivalent. int: An integer (a finite subset of the integers that is machine dependent). The full form, integer, is equivalent. smallint: A small integer (a machine-dependent subset of the integer type). numeric(p, d): A fixed-point number with user-specified precision. The number consists of p digits (plus a sign), and d of the p digits are to the right of the decimal point. Thus, numeric(3,1) allows 44.5 to be stored exactly, but neither 444.5 or 0.32 can be stored exactly in a field of this type. real, double precision: Floating-point and double-precision floating-point numbers with machine-dependent precision. float(n): A floating-point number, with precision of at least n digits.

INTEGRITY CONSTRAINTS PRIMARY KEY(<attribute_name>, <attribute_name>, ): Given attributes form primary key of relation nonnull and unique E.g: CREATE TABLE teachers ( teacher_id int, first_name varchar(50), last_name varchar(50), PRIMARY KEY (teacher_id) ) OR E.g: CREATE TABLE teachers ( teacher_id int PRIMARY KEY, first_name varchar(50), last_name varchar(50) )

INTEGRITY CONSTRAINTS FOREIGN KEY(<attribute_name>, <attribute_name>, ) REFERENCES <table_name>: Given attributes must be a primary key in the given table E.g: CREATE TABLE teachers ( teacher_id int, first_name varchar(50), last_name varchar(50), department_id int, PRIMARY KEY (teacher_id), FOREIGN KEY (department_id) REFERENCES departments )

INTEGRITY CONSTRAINTS NOT NULL E.g: CREATE TABLE teachers ( teacher_id int, first_name varchar(50) NOT NULL, last_name varchar(50), department_id int, PRIMARY KEY (teacher_id), FOREIGN KEY (department_id) REFERENCES departments )

INSERT/DELETE CREATE TABLE teachers ( teacher_id int PRIMARY KEY, first_name varchar(50), last_name varchar(50) ) INSERT INTO teachers VALUES( 1, Stan, Zdonik ) DELETE WHERE <condition> INSERT INTO teachers(teacher_id, last_name) VALUES( 1, Zdonik )

ALTER/DROP TABLE CREATE TABLE teachers ( teacher_id int PRIMARY KEY, first_name varchar(50), last_name varchar(50) ) ALTER TABLE teachers ADD department_id int; ALTER TABLE teachers DROP department_id; DROP TABLE teachers;

DATA MANIPULATION Data-manipulation Language (DML) provides commands for: Querying information about data Insert/Delete/Update tuples Commands are usually like: SELECT <attribute_name>* FROM <relation>* WHERE <condition> ; Result of a SQL query is always a relation!

SELECT Projection operation E.g: SELECT first_name SELECT first_name, last_name SELECT * Relational algebra does not allow duplicates, SQL does! SELECT DISTINCT first_name Can contain arithmetic operations (+, -, *, /) on attributes of tuples or constants E.g: SELECT first_name, weight / height, salary * 12

FROM Indicates the relations involved Cartesian product: R 1 X R 2 E.g: Find every possible pair of left and right socks SELECT * FROM left_socks, right_socks Will contain all the attributes of the given relations

WHERE Selection operation SELECT teacher_id WHERE age > 50 AND NOT department_name = computer science The condition can contain AND, OR, and NOT BETWEEN Clause: SELECT teacher_id WHERE age <= 50 AND age >= 30 = SELECT teacher_id WHERE age BETWEEN 30 AND 50

NULL VALUES Any arithmetic operation involving null results in null. (E.g: 2 + null = null) To check for null values, you can use IS NULL predicate --E.g: SELECT first_name WHERE last_name IS NULL Any comparison with null returns unknown (E.g: 2 < null) AND true false unknown unknown unknown false unknown OR true false unknown unknown true unknown unknown NOT unknown = unknown <Condition> IS UNKNOWN evaluates to true if <Condition> evaluates to unknown WHERE clause treats conditions resulting in unknown as false

<ATTRIBUTE> LIKE <PATTERN> Used for pattern matching in strings % for matching any substring _ for matching any character E.g: Find all student names starting with A SELECT name FROM students WHERE name LIKE A% E.g: Find all student names consisting of 3 letters SELECT name FROM students WHERE name LIKE Patterns are case sensitive!

JOINS Find the first and last name of the students who work under a department SELECT first_name, last_name FROM students, departments WHERE students.departmentid = departments.departmentid SELECT first_name, last_name FROM students JOIN departments ON students.departmentid = departments.departmentid OR SELECT first_name, last_name FROM students NATURAL JOIN departments OR

<RELATION1> NATURAL JOIN <RELATION2> Relational algebra: <relation1> <relation2> Merges tuples with the same values for all the attributes that have the same name and type. Keeps only 1 copy of each common attribute SELECT * FROM students NATURAL JOIN departments I D FirstNam e LastNam e 1 A B 10 2 C D 11 DepartmentI D DepartmentI D 10 CSCI 20 MUSC DepartmentName I D FirstNam e LastNam e DepartmentI D 1 A B 10 CSCI DepartmentName

SELECT * <RELATION1> JOIN <RELATION2> ON <CONDITION> FROM students JOIN departments ON students.departmentid = departments.departmentid I D FirstNam e LastNam e 1 A B 10 2 C D 11 DepartmentI D DepartmentI D 10 CSCI 20 MUSC DepartmentName I D FirstNam e LastNam e DepartmentI D 1 A B 10 CSCI DepartmentName

<RELATION1> LEFT JOIN <RELATION2> ON <CONDITION> Relational algebra: <relation1> <relation2> SELECT * FROM students LEFT JOIN departments ON students.departmentid = departments.departmentid I D FirstNam e LastNam e 1 A B 10 2 C D 11 DepartmentI D DepartmentI D 10 CSCI 20 MUSC DepartmentName I D FirstNam e LastNam e DepartmentI D 1 A B 10 CSCI 2 C D null null DepartmentName

RENAME Relational algebra: <old_name> AS <new_name> E.g: SELECT name, salary/12 AS montly_salary FROM employees SELECT first_name, last_name FROM students AS S, departments AS D WHERE S.DepartmentID = D.DepartmentID

ORDER BY <ATTRIBUTE> E.g: List every student s name and height by ordering them in height from shortest to tallest SELECT name, height FROM students ORDER BY height E.g: List every student s name and height by ordering their names alphabetically. The students with the same name should be ordered by their heights in descending order SELECT name, height FROM students ORDER BY name, height DESC ORDER BY <attribute> ASC/DESC Default is ASC

SET OPERATIONS UNION (U operation), INTERSECT ( operation), EXCEPT ( operation) E.g. The relations these operations work on must have same attributes with same domain (SELECT course_id FROM section WHERE sem = Fall AND year = 2009) UNION (SELECT course_id FROM section WHERE sem = Spring AND year = 2010) Above operations automatically eliminates duplicates In order to retain the duplicates, use ALL (E.g. UNION ALL)

AGGREGATE FUNCTIONS Provide more information about an attribute AVG: average value MIN: minimum value MAX: maximum value SUM: sum of values COUNT: number of values

AGGREGATE FUNCTIONS E.g. Find the average salary of teachers in computer science department SELECT AVG(salary) WHERE department = Computer Science E.g. Find the total number of teachers in computer science department SELECT COUNT(ID) WHERE department = Computer Science E.g. How many different classes do teachers in computer science department teach? SELECT COUNT( DISTINCT class_name ) WHERE department = Computer Science

GROUP BY <ATTRIBUTE> Enables you to use aggregate functions on certain groups E.g. Find the average salary of teachers in every department SELECT department, AVG(salary) GROUP BY department Attributes inside of SELECT clause and outside of aggregate function must be included in GROUP BY E.g. False query SELECT department, department_id, AVG(salary) GROUP BY department

HAVING WHERE clause of aggregate functions Difference: Predicates in WHERE clause are applied BEFORE formation of groups, unlike GROUP BY E.g. Find the departments who are employing more than 20 teachers SELECT department, COUNT( DISTINCT teacher_id ) GROUP BY department HAVING COUNT( DISTINCT teacher_id ) > 20

NULLS IN AGGREGATES All aggregate operations except COUNT(*) ignore null values on aggregated attributes E.g. SELECT SUM( salary ) FROM people Will return 22 If an attribute has only null values: COUNT will return 0 others will return null I D FirstNam e LastNam e 1 A B 10 2 C D 12 Salary 3 E F Null

NESTED SUBQUERIES Common usage: checking set membership, set comparisons, set cardinality E.g. Find teachers who work in both math and cs department SELECT DISTINCT teacher_id WHERE department = Computer Science AND teacher_id IN (SELECT DISTINCT teacher_id WHERE department = Mathematics )

NESTED SUBQUERIES E.g. Find teachers who work in cs department and NOT a student SELECT DISTINCT teacher_id WHERE department = Computer Science AND teacher_id NOT IN (SELECT DISTINCT student_id FROM students)

NESTED SUBQUERIES E.g. Find students who gain more than at least one teacher SELECT student_name FROM working_students WHERE salary > SOME (SELECT salary ) E.g. Find students who gain more than ALL teachers SELECT student_name FROM working_students WHERE salary > ALL (SELECT salary )

NESTED SUBQUERIES E.g. Find students who gain more than at least one teacher SELECT student_name FROM working_students AS W WHERE EXISTS (SELECT salary AS T WHERE W.salary > T.salary) EXISTS returns true if the given subquery does not result in an empty relation NOT EXISTS performs in the opposite way

NESTED SUBQUERIES E.g. Find all students who have taken all courses offered in the Biology department SELECT DISTINCT S.ID, S.name FROM student AS S WHERE NOT EXISTS ( (SELECT course_id FROM course WHERE dept_name = Biology ) EXCEPT (SELECT T.course_id FROM takes AS T WHERE S.ID = T.ID));