Database Query 1: SQL Basics



Similar documents
SQL SELECT Query: Intermediate

3.GETTING STARTED WITH ORACLE8i

SQL. Short introduction

Introduction to Microsoft Jet SQL

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

Access Queries (Office 2003)

How To Create A Table In Sql (Ahem)

Oracle SQL. Course Summary. Duration. Objectives

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Using AND in a Query: Step 1: Open Query Design

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Oracle Database: SQL and PL/SQL Fundamentals

Financial Data Access with SQL, Excel & VBA

A Brief Introduction to MySQL

Oracle Database: SQL and PL/SQL Fundamentals NEW

Information Systems SQL. Nikolaj Popov

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

SQL Basics. Introduction to Standard Query Language

T-SQL STANDARD ELEMENTS

David M. Kroenke and David J. Auer Database Processing: Fundamentals, Design and Implementation

Oracle Database: SQL and PL/SQL Fundamentals

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

Structured Query Language (SQL)

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

In-Depth Guide Advanced Database Concepts

SQL Server Database Coding Standards and Guidelines

A basic create statement for a simple student table would look like the following.

Joining Tables in Queries

CSC 443 Data Base Management Systems. Basic SQL

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Oracle Database 10g: Introduction to SQL

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Oracle Database 12c: Introduction to SQL Ed 1.1

Talking to Databases: SQL for Designers



Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

SQL Programming. Student Workbook

Programming with SQL

Netezza SQL Class Outline

Instant SQL Programming

Database Migration from MySQL to RDM Server

DBMS Questions. 3.) For which two constraints are indexes created when the constraint is added?

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Database Applications Microsoft Access

SQL Server An Overview

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

Relational Database: Additional Operations on Relations; SQL

Access 2010: Creating Queries Table of Contents INTRODUCTION TO QUERIES... 2 QUERY JOINS... 2 INNER JOINS... 3 OUTER JOINS...

Database Administration with MySQL

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Creating QBE Queries in Microsoft SQL Server

Using SQL Server Management Studio

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Business Intelligence. 11. SSIS, ETL January 2014.

IT2305 Database Systems I (Compulsory)

1.204 Lecture 3. SQL: Basics, Joins SQL

Microsoft Access Lesson 5: Structured Query Language (SQL)

BCA. Database Management System

IT2304: Database Systems 1 (DBS 1)

ORACLE 10g Lab Guide

Choosing a Data Model for Your Database

Microsoft Access 3: Understanding and Creating Queries

Database Development and Management with SQL

Oracle Database: Introduction to SQL

VBScript Database Tutorial Part 1

Oracle 10g PL/SQL Training

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

Deleting A Record Updating the Database Binding Data Tables to Controls Binding the Data Table to the Data Grid View...

Oracle Database: Introduction to SQL

A Migration Methodology of Transferring Database Structures and Data

A table is a collection of related data entries and it consists of columns and rows.

Improving SQL Server Performance

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database 11g SQL

4 Logical Design : RDM Schema Definition with SQL / DDL

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Conventional Files versus the Database. Files versus Database. Pros and Cons of Conventional Files. Pros and Cons of Databases. Fields (continued)

KB_SQL SQL Reference Guide Version 4

Databases in Engineering / Lab-1 (MS-Access/SQL)

Information Systems Modelling Information Systems I: Databases

Creating Database Tables in Microsoft SQL Server

GET DATA FROM MULTIPLE TABLES QUESTIONS

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

MYSQL DATABASE ACCESS WITH PHP

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

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

Firebird. Embedded SQL Guide for RM/Cobol

Oracle Database: Introduction to SQL

Introduction to SQL for Data Scientists

Performing Queries Using PROC SQL (1)

Transcription:

Database Query 1: SQL Basics CIS 3730 Designing and Managing Data J.G. Zheng Fall 2010 1

Overview Using Structured Query Language (SQL) to get the data you want from relational databases Learning basic syntax and simple queries All examples can be used with the Northwind database 2

SQL: Introduction SQL is a standard command language use by relational DBMS to perform database operations Some facts about SQL English-like Case insensitive An ANSI standard Not considered to be a programming language Most venders have their own proprietary extensions, making SQL slightly different in different DBMS products 3

What Does SQL Do? DML - data manipulation language Retrieving data: database queries Manipulating data: insert, update, delete DDL - data definition language Defining and modifying data structures (schema): databases, tables, views, etc. DCL - data control language Control data access: permissions, etc. 4

Database Queries A query is a request for information from a database. SELECT statements are used to retrieve data The result of a query is generally a table (but not necessarily a relation) SQL SELECT basics Defining selection criteria Sorting Table join 5

SELECT: General Syntax SELECT [Column(s), or other expressions] FROM [Table(s)] [WHERE ] [ORDER BY ] 6

1.1 Select Columns Syntax SELECT * (or a list of columns) FROM TableName Example SELECT * FROM Products; * represents all columns in the table SELECT ProductName, UnitPrice FROM Products; Provide a list of columns separated by comma 7

Column Qualifier and Alias Qualifiers are used to distinguish column names when there is ambiguity SELECT Products.ProductName, Products.UnitPrice FROM Products A qualifier of table name Alias is used to give column another name SELECT UnitPrice*Quantity AS Total FROM [Order Details]; Use AS operator to Use square brackets if there is blank spaces in table or column names. give an alias. 8

2. Select Rows (Selection Criteria) Use WHERE clause to specify selection criteria Common comparison operators =, >, <, >=, <=, <>,!= Examples SELECT * FROM Products WHERE UnitPrice = 18; SELECT BookTitle, ListPrice FROM Products WHERE UnitPrice < 20; 9

2.1 Comparing with Constants Numbers (int, float, decimal, etc.) WHERE UnitPrice > 20.99 Text (char, varchar, nvarchar, etc.): use ' ' (single quote) for values WHERE ProductName = 'Tofu' // exact match WHERE ProductName > 'Chang' Data/Time: SQL Server uses '...' WHERE OrderDate < '08/30/2008' compared by alphabetical order, > means after Before the date, 12:00AM Boolean (bit, yes/no, etc.): 'TURE' or 1, 'FALSE' or 0 WHERE Discontinued = 1 WHERE Discontinued = 'true' 10

2.2 IN and BETWEEN IN (a value list): equals to any value in the list SELECT * FROM Products WHERE UnitPrice IN (18, 19, 21) BETWEEN min AND max: any value falls in the range, inclusive SELECT * FROM Products WHERE UnitPrice BETWEEN 10 AND 20 11

2.3 String Pattern Match: LIKE LIKE: keyword match, or fuzzy query _ (underscore): matching one single character % (percentage) wildcard: matching any multiple characters Comparison pattern is case insensitive Example Can I get all tofu related products? SELECT * FROM Products WHERE ProductName LIKE '%tofu%' Matching any characters before tofu Matching any characters after tofu 12

2.4 IS NULL NULL means missing value IS NULL, IS NOT NULL SELECT * FROM Orders WHERE ShipPostalCode IS NULL SELECT * FROM Orders WHERE ShipPostalCode IS NOT NULL 13

2.5 NOT Reversal criteria NOT (expression) Examples WHERE NOT UnitPrice > 20; WHERE NOT ProductName LIKE '%tofu%'; WHERE ProductName NOT LIKE '%tofu%'; WHERE NOT ShipPostalCode IS NULL; 14

2.6 Compound Conditions Use logical operators to connect multiple criteria AND: satisfy both conditions OR: satisfy either criterion Comparison precedence: AND has a higher precedence over OR Best practice: use parentheses () to explicitly define comparison order Examples WHERE UnitPrice <= 20 AND UnitPrice >= 10; WHERE ShippedDate ='8/2/1996' OR ShippedDate = '8/9/1996'; WHERE (City = 'London' OR City = 'Seattle') AND HireDate > '1/1/1993'; If () are not used, City = 'Seattle' AND HireDate > '1/1/1993' will be evaluated first, which is wrong. 15

3. Sorting Sorting query results ORDER BY Column(s) [ASC/DESC] ASC (ascending) is the default order Examples SELECT * FROM Products ORDER BY UnitPrice; SELECT * FROM Products ORDER BY 6; Multiple sorting SELECT * FROM Products ORDER BY CategoryID, UnitPrice DESC Column position can also be used (starting from 1) Sort by category first, then UnitPrice 16

4. Table Join Retrieving data from multiple tables The query result consists of columns from more than one table How do rows match from different tables? Cross Join: no need to match. Inner Join: use the foreign key constraint as the matching criteria 17

Table Join Effect Product Category A 1 B 2 FK Join Category Name 1 Canned 2 Drink 3 Fresh Product A A A B B B Category Canned Drink Fresh Canned Drink Fresh Product A B Cross Join: no row matching Category Canned Drink Inner Join: row matching based on foreign key 18

Table Join SQL Example What is the category name for each product? SELECT ProductName, CategoryName FROM Products, Categories Where Foreign key Products.CategoryID = Categories.CategoryID Primary key Use table.column format to avoid ambiguity CategoryID in which table? Joining/matching criteria: very important, don t forget! 19

3. Table Join Syntax Alternative SELECT ProductName, CategoryName FROM Products, Categories Where Products.CategoryID = Categories.CategoryID AND Discontinued = 0; VS. 1. Joining/matching criteria: very important, don t forget! 2. Table.Cloumn format is used to avoid ambiguity. SELECT ProductName, CategoryName FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID WHERE Discontinued = 0; 20

Joining More Tables (1) For each order after April 1, 1998, I want to see what products (product name) were ordered, and how many. SELECT Orders.OrderID, OrderDate, ProductName, Quantity FROM Orders, [Order Details], Products WHERE Orders.OrderID = [Order Details].OrderID AND [Order Details].ProductID = Products.ProductID AND OrderDate > '1998-04-01' 21

Joining More Tables (2) For each order after April 1, 1998, I want to see what products (product name) were ordered, and how many. SELECT Orders.OrderID, OrderDate, ProductName, Quantity FROM Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID INNER JOIN Products ON [Order Details].ProductID = Products.ProductID WHERE OrderDate > '1998-04-01' 22

Summary Key concepts Database query SQL: DML, DDL, DCL Join, cross join, inner join Key skills: write SQL SELECT statement to retrieve data; and know the result of a given SQL SELECT statement. Select columns, * Selection criteria in WHERE: comparison operators =, <, >, >=, <=, <>,!=, IN, BETWEEN, LIKE, IS NULL, NOT %, _ AND, OR ORDER BY Table join 23

More SQL Resources W3Schools SQL Tutorial http://www.w3schools.com/sql/ SQL Course http://sqlcourse.com/ http://sqlcourse2.com/ A gentle introduction to SQL http://sqlzoo.net/ Other http://www.youtube.com/watch?v=rpp28u_k9lk http://www.1keydata.com/sql 24