SQL Simple Queries. Chapter 3.1 V3.01. Napier University

Similar documents
SQL JOINs and VIEWs. Chapter 3.3 V4.0. Napier University

Logical Operators and aggregation

SQL - Subqueries and. Schema. Chapter 3.4 V4.0. Napier University

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

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

The Relational Model

Solved MCQ on fundamental of DBMS. Set-1

Database Management System 9

The Relational Model Constraints and SQL DDL

Database Applications (15-415)

MTAT Introduction to Databases

Introduction to Relational Databases. Introduction to Relational Databases cont: Introduction to Relational Databases cont: Relational Data structure

SQL DATA DEFINITION LANGUAGE

CPS 510 Data Base I. There are 3 forms of database descriptions the ANSI/SPARK, 1975 and so on

CPS510 Database System Design Primitive SYSTEM STRUCTURE

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

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model

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

Database Systems CSE 303. Lecture 02

Database Systems CSE 303. Lecture 02

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

The Relational Model. Roadmap. Relational Database: Definitions. Why Study the Relational Model? Relational database: a set of relations

Chapter 1 SQL and Data

Part I: Structured Data

King Fahd University of Petroleum and Minerals

Chapter 4. The Relational Model

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

The Relational Model

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

G64DBS Database Systems. Lecture 7 SQL SELECT. The Data Dictionary. Data Dictionaries. Different Sections of SQL (DDL) Different Sections of SQL (DCL)

Database Modelling. Lecture 4 (b): Database Integrity, Keys & Constraints. Akhtar Ali 10/14/2014 1

Database Management Systems,

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

Chapter-14 SQL COMMANDS

Using Relational Databases for Digital Research

Relational Model. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Basant Group of Institution

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

ITCS 3160 DATA BASE DESIGN AND IMPLEMENTATION

Mahathma Gandhi University

SQL DATA DEFINITION LANGUAGE

Data, Databases, and DBMSs

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

Introduction to Databases CSE 414. Lecture 2: Data Models

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

1) Introduction to SQL

Full file at

CS143: Relational Model

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

8) A top-to-bottom relationship among the items in a database is established by a

The Relational Model. Week 2

Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU /615

The Structured Query Language Get Started

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Introduction to SQL Part 1 By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

Data about data is database Select correct option: True False Partially True None of the Above

Relational terminology. Databases - Sets & Relations. Sets. Membership

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

SQL: Data Definition Language

COURSE OVERVIEW THE RELATIONAL MODEL. CS121: Relational Databases Fall 2017 Lecture 1

Department of Computer Science and Information Systems, College of Business and Technology, Morehead State University

COURSE OVERVIEW THE RELATIONAL MODEL. CS121: Introduction to Relational Database Systems Fall 2016 Lecture 1

CSE 344 JANUARY 5 TH INTRO TO THE RELATIONAL DATABASE

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

Module 9: Managing Schema Objects

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

Lecture 2: Chapter Objectives. Relational Data Structure. Relational Data Model. Introduction to Relational Model & Structured Query Language (SQL)

Introduction to Data Management. Lecture #4 (E-R Relational Translation)

Lecture 2: Chapter Objectives

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Assignment Session : July-March

SQL DATA DEFINITION LANGUAGE

DS Introduction to SQL Part 1 Single-Table Queries. By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Relational data model

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Relational Data Model

Let s briefly review important EER inheritance concepts

CSC Web Programming. Introduction to SQL

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT )

CS425 Midterm Exam Summer C 2012

Introduction to Databases

Informatics 1: Data & Analysis

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

Relational Databases

user specifies what is wanted, not how to find it

LAB 3 Notes. Codd proposed the relational model in 70 Main advantage of Relational Model : Simple representation (relationstables(row,

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Midterm Review. Winter Lecture 13

Lecture 2: Introduction to SQL

Review. The Relational Model. Glossary. Review. Data Models. Why Study the Relational Model? Why use a DBMS? OS provides RAM and disk

UFCEKG 20 2 : Data, Schemas and Applications

CS275 Intro to Databases

Database Management Systems. Chapter 3 Part 1

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer,

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

Transcription:

SQL Simple Queries Chapter 3.1 V3.01 Copyright @ Napier University

Introduction SQL is the Structured Query Language It is used to interact with the DBMS (database management system) SQL can Create Schemas in the DBMS Alter Schemas Add data Remove data Change data Access Data

DSL SQL is a Data Sub Language This is a combination of two languages DDL Data Definition Language DML Data Manipulation Language The main way of accessing data is using the DML command SELECT. The abilities of the SELECT command forms the majority of this material on SQL

Database Models A data model comprises a data structure a set of integrity constraints operations associated with the data structure Examples of data models include: hierarchic network Relational (E. F. Codd)

Relational Databases The relational data model comprises: relational data structure relational integrity constraints relational algebra or equivalent (SQL) SQL is an ISO language based on relational algebra the operations relational algebra is a mathematical formulation

Relational Data Structure A relational data structure is a collection of tables, or relations. A relation is a collection of rows or tuples A tuple is a collection of columns or attributes A domain is a pool of values from which the actual attribute values are taken.

Relational Structure cont Relation Attributes Description Price Tuples Domain

Domain and Integrity Constraints Domain Constraints limit the range of values of an attribute specify uniqueness and nullness of an attribute specify a default value for an attribute when no value is provided. Entity Integrity every tuple is uniquely identified by a unique non-null attribute, the primary key. Referential Integrity rows in different tables are correctly related by valid key values ( foreign keys refer to primary keys).

Example Database In order to better understand SQL, all the example queries make use of a simple database. The database is formed from 2 tables, CAR and DRIVER. Each car may be owned by a DRIVER. A DRIVER may own multiple CARs. DRIVER CAR

DRIVER NAME DOB Jim Smith 11 Jan 1980 Bob Smith 23 Mar 1981 Bob Jones 3 Dec 1986

CAR REGNO MAKE COLOUR PRICE OWNER F611 AAA FORD RED 12000 Jim Smith J111 BBB SKODA BLUE 11000 Jim Smith A155 BDE MERCEDES BLUE 22000 Bob Smith K555 GHT FIAT GREEN 6000 Bob Jones SC04 BFE SMART BLUE 13000

Each column holds data of a particular type Integer, string, decimal, blobs Arity The range of values can be further constrained If a column in a row contains no data, it is NULL. Null can indicate no possible value, or unavailable data. All rows (tuples) must differ from each other in some way Cardinality is the number of rows of a table cardinality Arity is the number of columns of a table

Primary Keys & Entity Integrity A Primary Key is a group of one or more columns which, when taken together, is unique in the table No part of a primary key can be NULL. In our example, DRIVER: the primary key is NAME CAR: the primary key is REGNO In our example this means that no two drivers can have the same name. In the real world this would be a problem, but this is just an example.

Referential Integrity Note that there is a link between CAR and DRIVER via the attribute OWNER. If there is a value in OWNER, then this value must also appear somewhere in DRIVER (attribute NAME). If you change a driver s NAME in DRIVER, you must make sure the same change is made in OWNER of CAR. The DBMS enforces the rules! If you try to break the rules the DBMS reports the problem as a REFERENTIAL INTEGRITY error.

SQL Basics Basic SQL statements include CREATE a data structure SELECT read one or more rows from a table INSERT one of more rows into a table DELETE one or more rows from a table UPDATE change the column values in a row DROP a data structure ALTER a data structure In this lecture the focus is on SELECT. DDL DML DML DML DDL DDL DDL

Simple SELECT SELECT column FROM tablename SELECT column1, column2, column3, FROM tablename1, tablename2, SELECT * from tablename e.g. SELECT * from CAR; -- gives REGNO MAKE COLOUR PRICE OWNER F611 AAA FORD RED 12000 Jim Smith J111 BBB SKODA BLUE 11000 Jim Smith A155 BDE MERCEDES BLUE 22000 Bob Smith K555 GHT FIAT GREEN 6000 Bob Jones SC04 BFE SMART BLUE 13000

SELECT regno from CAR; REGNO F611 AAA J111 BBB A155 BDE K555 GHT SC04 BFE

SELECT colour, owner from CAR; COLOUR RED BLUE BLUE GREEN BLUE OWNER Jim Smith Jim Smith Bob Smith Bob Jones

Formatting SPACES do not matter NEWLINES do not matter Good practice to put ; at the end of the query. CaSE (except between single quotes) does not matter. The following are all valid: SELECT REGNO FROM CAR; SElecT regno From car ; SELECT Regno FROM Car;

Comments To give you the ability to make notes in queries you are allowed to have comments. Comments are not executed (they are ignored) A comment starts with -- and ends with a newline They are only permitted within a query. SELECT regno -- The registration number FROM car -- The car storage table ;

SELECT filters You can have rules in your queries These rules are tested for each row your query produces If the rule is true, the row is displayed If the rule is false, the row is not displayed The rule starts with WHERE SELECT columns FROM table WHERE rule

Simple Rule A simple rule might be to look for a car with a colour of RED. The rule would be colour = 'RED' SELECT regno FROM CAR SELECT regno from REGNO CAR F611 AAA WHERE colour = 'RED' J111 BBB A155 BDE K555 GHT SC04 BFE REGNO F611 AAA

Note Things between quotes are CASE SENSITIVE. RED is not the same as Red or red Rules which mention fields can be used whether the fields appear REGNO on the COLOUR SELECT line or not. F611 AAA RED SELECT regno from CAR WHERE colour = 'RED'

Comparisons Valid comparisons include =,!=,<>,<,<=,>,>= Colour = RED The colour must be red Colour!= RED The colour is not red Colour <> RED Same result as!= Price > 10000 More than 10000 Price >= 10000 More than or equal to 10000 Price < 10000 Cheaper than 10000 Price <=10000Cheaper or the same as 10000 Numbers You may say 10000 or 10000 in Oracle SQL Strings and dates must always have quotes

DATE You can use all the normal comparators with dates. SELECT name,dob SELECT name,dob from driver from driver where DOB = 3 Jan 1986 NAME DOB Jim Smith 11 Jan 1980 Bob Smith 23 Mar 1981 Bob Jones 3 Dec 1986 NAME DOB Bob Jones 3 Dec 1986

The tricky part with dates is remembering that dates get bigger as you move into the future. DATE1>DATE2 indicates DATE1 is in the future after DATE2. (i,.e. 2007 > 2006 and Mar > Jan) SELECT name,dob from driver WHERE DOB >= 1 Jan 1981 NAME DOB Bob Smith 23 Mar 1981 Bob Jones 3 Dec 1986

DATE Syntax Date must be in quotes Each DBMS handles dates in a slightly different way Dates like 1 Jan 2003 work quite well. Oracle permits dates like 1-Jan-2003 Oracle also permits dates like 1-Jan-03 If you type this it will assume 2003. If you mean 1984 type 1984 not 84. You must always specify a day and a month. If you do not the DBMS will report an error.

BETWEEN (is inclusive) When dealing with dates sometimes you want to test to see if a field value falls between two dates. The easiest way to do this is with BETWEEN Find all drivers born between 1995 and 1999 SELECT name,dob from driver WHERE DOB BETWEEN 1 Jan 1985 AND 31 Dec 1999 Between works for other things, not just dates SELECT regno from CAR where price BETWEEN 5000 AND 10000;

NULL NULL indicates that something has no value It is not a value, and you cannot use normal comparison operators. For instance, looking for cars without owners Wrong: Wrong: = NULL SELECT regno from car where owner = NULL SELECT regno from car where owner Instead there are two special operators, IS NULL, or IS NOT NULL

SELECT regno from car WHERE OWNER is null REGNO SC04 BFE Has no owner SELECT regno from car REGNO F611 AAA J111 BBB WHERE OWNER is not null A155 BDE K555 GHT SC04 BFE

LIKE Sometimes you want to have a rule involving partial strings, substrings, or wildcards LIKE does this, and is a slot-in replacement for = If the string contains % or _, LIKE uses them to support wildcards. % - Matches zero or more characters in the string _ - Matches exactly 1 character in the string

Examples Name LIKE Jim Smith e.g. Jim Smith Name LIKE _im Smith e.g. Tim Smith Name LIKE _ Smith e.g. Bob Smith Name LIKE % Smith e.g. Frank Smith Name LIKE % S% e.g. Brian Smart Name LIKE Bob % e.g. Bob Martin Name LIKE % i.e. matches anyone LIKE is more expensive than = If you are not using wildcards, always use = rather than