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

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

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

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

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

Introduction to SQL. From Rob and Coronel (2004), Database Systems: Design, Implementation, and Management

CSC Web Programming. Introduction to SQL

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

Exact Numeric Data Types

Sql Server Syllabus. Overview

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

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

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

MTA Database Administrator Fundamentals Course

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

12. MS Access Tables, Relationships, and Queries

Oracle Database 11g: SQL and PL/SQL Fundamentals

Oracle Syllabus Course code-r10605 SQL

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

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

Slides by: Ms. Shree Jaswal

UNIT-IV (Relational Database Language, PL/SQL)

T-SQL Training: T-SQL for SQL Server for Developers

Chapter-14 SQL COMMANDS

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

DB2 SQL Class Outline

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

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Lesson 2. Data Manipulation Language

Principles of Data Management

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

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

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

ITCertMaster. Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way!

Chapter 4: SQL. Basic Structure

Querying Data with Transact SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

Relational Database Management Systems for Epidemiologists: SQL Part I

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

SQL Interview Questions

1) Introduction to SQL

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

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

The SQL database language Parts of the SQL language

III. Advanced Design and Implementation PART. Introduction to Structured Query Language (SQL) Advanced SQL. Database Design

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

The Structured Query Language Get Started

5. Single-row function

DATABASE TECHNOLOGY. Spring An introduction to database systems

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

Comparison Operators. Selecting Rows with Conditional Restrictions

Oracle Database 10g: Introduction to SQL

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

Lecture 07. Spring 2018 Borough of Manhattan Community College

Full file at

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

2) SQL includes a data definition language, a data manipulation language, and SQL/Persistent stored modules. Answer: TRUE Diff: 2 Page Ref: 36

Lecture 2: Chapter Objectives

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions

CST272 SQL Server, SQL and the SqlDataSource Page 1

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

Introduction to Computer Science and Business

UFCEKG 20 2 : Data, Schemas and Applications

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

DATABASE DESIGN I - 1DL300

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Activant Solutions Inc. SQL 2005: Basic Data Manipulation

Chapter 3: Introduction to SQL

Course Outline and Objectives: Database Programming with SQL

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Oracle Database: SQL and PL/SQL Fundamentals

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

II B.Sc(IT) [ BATCH] IV SEMESTER CORE: RELATIONAL DATABASE MANAGEMENT SYSTEM - 412A Multiple Choice Questions.

Mobile MOUSe MTA DATABASE ADMINISTRATOR FUNDAMENTALS ONLINE COURSE OUTLINE

Data Manipulation Language (DML)

SQL Workshop. Introduction Queries. Doug Shook

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

SQL Data Manipulation Language. Lecture 5. Introduction to SQL language. Last updated: December 10, 2014

Follow these steps to get started: o Launch MS Access from your start menu. The MS Access startup panel is displayed:

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

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

Greenplum SQL Class Outline

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

HKTA TANG HIN MEMORIAL SECONDARY SCHOOL SECONDARY 3 COMPUTER LITERACY. Name: ( ) Class: Date: Databases and Microsoft Access

Chapter 3: Introduction to SQL

SQL for MySQL A Beginner s Tutorial

Unit Assessment Guide

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

DATABASE TECHNOLOGY - 1MB025

CGS 3066: Spring 2017 SQL Reference

Concepts of Database Management Eighth Edition. Chapter 2 The Relational Model 1: Introduction, QBE, and Relational Algebra

Database Systems SQL SL03

CS 582 Database Management Systems II

20461: Querying Microsoft SQL Server 2014 Databases

Transcription:

Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition Chapter 7 Beginning Structured Query Language (SQL) MDM NUR RAZIA BINTI MOHD SURADI 019-3932846 razia@unisel.edu.my 1 Introduction to SQL SQL functions fit into two broad categories: Data definition language Data manipulation language 2 1

3 4 2

Data Definition Commands The database model In this chapter, a simple database with these tables is used to illustrate commands: CUSTOMER INVOICE LINE PRODUCT VENDOR Focus on PRODUCT and VENDOR tables 5 6 3

Creating the Database Two tasks must be completed: Create database structure Create tables that will hold end-user data First task: RDBMS creates physical files that will hold database Differs substantially from one RDBMS to another 7 Creating the Database (cont d.) Authentication DBMS verifies that only registered users are able to access database Log on to RDBMS using user ID and password created by database administrator 8 4

The Database Schema Schema Group of database objects that are related to each other CREATE SCHEMA AUTHORIZATION {creator}; Command is seldom used directly 9 Data Types Data type selection is usually dictated(said) by nature of data and by intended use Supported data types: Number(L,D), Integer, Smallint, Decimal(L,D) Char(L), Varchar(L), Varchar2(L) Date, Time, Timestamp Real, Double, Float Interval day to hour Many other types 10 5

11 12 6

Creating Table Structures Use one line per column (attribute) definition Use spaces to line up attribute characteristics and constraints Table and attribute names are capitalized NOT NULL specification UNIQUE specification 13 Primary key attributes contain both a NOT NULL and a UNIQUE specification RDBMS will automatically enforce referential integrity for foreign keys Command sequence ends with semicolon Creating Table Structures (cont d.) 14 7

NOT NULL constraint Ensures that column does not accept nulls UNIQUE constraint Ensures that all values in column are unique DEFAULT constraint Assigns value to attribute when a new row is added to table CHECK constraint Validates data when attribute value is entered SQL Constraints 15 When primary key is declared, DBMS automatically creates unique index Often need additional indexes Using CREATE INDEX command, SQL indexes can be created on basis of any selected attribute Composite index Index based on two or more attributes Often used to prevent data duplication SQL Indexes 16 8

Data Manipulation Commands INSERT SELECT COMMIT UPDATE ROLLBACK DELETE 17 Adding Table Rows INSERT Used to enter data into table Syntax: INSERT INTO columnname VALUES (value1, value2,, valuen); 18 9

Adding Table Rows (cont d.) When entering values, notice that: Row contents are entered between parentheses Character and date values are entered between apostrophes Numerical entries are not enclosed in apostrophes Attribute entries are separated by commas A value is required for each column Use NULL for unknown values 19 Saving Table Changes Changes made to table contents are not physically saved on disk until: Database is closed Program is closed COMMIT command is used Syntax: COMMIT [WORK]; Will permanently save any changes made to any table in the database 20 10

Listing Table Rows SELECT Used to list contents of table Syntax: SELECT columnlist FROM tablename; Columnlist represents one or more attributes, separated by commas Asterisk can be used as wildcard character to list all attributes 21 Updating Table Rows UPDATE Modify data in a table Syntax: UPDATE tablename SET columnname = expression [, columnname = expression] [WHERE conditionlist]; If more than one attribute is to be updated in row, separate corrections with commas 22 11

Restoring Table Contents ROLLBACK Undoes changes since last COMMIT Brings data back to prechange values Syntax: ROLLBACK; COMMIT and ROLLBACK only work with commands to add, modify, or delete table rows 23 Deleting Table Rows DELETE Deletes a table row Syntax: DELETE FROM tablename [WHERE conditionlist ]; WHERE condition is optional If WHERE condition is not specified, all rows from specified table will be deleted 24 12

Inserting Table Rows with a SELECT Subquery INSERT Inserts multiple rows from another table (source) Uses SELECT subquery Subquery: query embedded (or nested or inner) inside another query Subquery executed first Syntax: INSERT INTO tablename SELECT columnlist FROM tablename; 25 SELECT Queries Fine-tune SELECT command by adding restrictions to search criteria using: Conditional restrictions Arithmetic operators Logical operators Special operators 26 13

Selecting Rows with Conditional Restrictions Select partial table contents by placing restrictions on rows to be included in output Add conditional restrictions to SELECT statement, using WHERE clause Syntax: SELECT columnlist FROM tablelist [ WHERE conditionlist ] ; 27 28 14

29 Selecting Rows with Conditional Restrictions (cont d.) Using comparison operators on dates Date procedures are often more software-specific than other SQL procedures Using computed columns and column aliases SQL accepts any valid expressions (or formulas) in the computed columns Alias Alternate name given to a column or table in any SQL statement 30 15

Arithmetic Operators: The Rule of Precedence Perform operations within parentheses Perform power operations Perform multiplications and divisions Perform additions and subtractions 31 Logical Operators: AND, OR, and NOT Searching data involves multiple conditions Logical operators: AND, OR, and NOT Can be combined Parentheses enforce precedence order Conditions in parentheses are always executed first Boolean algebra: mathematical field dedicated to use of logical operators NOT negates result of conditional expression 32 16

Special Operators BETWEEN: checks whether attribute value is within a range IS NULL: checks whether attribute value is null LIKE: checks whether attribute value matches given string pattern IN: checks whether attribute value matches any value within a value list EXISTS: checks if subquery returns any rows 33 Advanced Data Definition Commands All changes in table structure are made by using ALTER command Three options: ADD adds a column MODIFY changes column characteristics DROP deletes a column Can also be used to: Add table constraints Remove table constraints 34 17

Changing a Column s Data Type ALTER can be used to change data type Some RDBMSs do not permit changes to data types unless column is empty 35 Changing a Column s Data Characteristics Use ALTER to change data characteristics Changes in column s characteristics are permitted if changes do not alter the existing data type 36 18

Adding a Column Dropping a Column Use ALTER to add column Do not include the NOT NULL clause for new column Use ALTER to drop column Some RDBMSs impose restrictions on the deletion of an attribute 37 Advanced Data Updates UPDATE command updates only data in existing rows If relationship between entries and existing columns, can assign values to slots Arithmetic operators are useful in data updates In Oracle, ROLLBACK command undoes changes made by last two UPDATE statements 38 19

Copying Parts of Tables SQL permits copying contents of selected table columns Data need not be reentered manually into newly created table(s) First create the table structure Next add rows to new table using table rows from another table 39 Adding Primary and Foreign Key Designations When table is copied, integrity rules do not copy Primary and foreign keys are manually defined on new table User ALTER TABLE command Syntax: ALTER TABLE tablename ADD PRIMARY KEY(fieldname); For foreign key, use FOREIGN KEY in place of PRIMARY KEY 40 20

Deleting a Table from the Database DROP Deletes table from database Syntax: DROP TABLE tablename; Can drop a table only if it is not the one side of any relationship Otherwise, RDBMS generates an error message Foreign key integrity violation 41 Additional SELECT Query Keywords Logical operators work well in the query environment SQL provides useful functions that: Count Find minimum and maximum values Calculate averages, etc. SQL allows user to limit queries to: Entries having no duplicates Entries whose duplicates may be grouped 42 21

Ordering a Listing ORDER BY clause is useful when listing order is important Syntax: SELECT columnlist FROM tablelist [WHERE conditionlist] [ORDER BY columnlist [ASC DESC]]; Ascending order by default 43 Listing Unique Values DISTINCT clause produces list of only values that are different from one another Example: SELECT DISTINCT V_CODE FROM PRODUCT; Access places nulls at the top of the list Oracle places it at the bottom Placement of nulls does not affect list contents 44 22

Aggregate Functions COUNT function tallies number of non-null values of an attribute Takes one parameter: usually a column name MAX and MIN find highest (lowest) value in a table Compute MAX value in inner query Compare to each value returned by the query SUM computes total sum for any specified attribute AVG function format is similar to MIN and MAX 45 Grouping Data Frequency distributions created by GROUP BY clause within SELECT statement Syntax: SELECT columnlist FROM tablelist [WHERE conditionlist] [GROUP BY columnlist] [HAVING conditionlist] [ORDER BY columnlist [ASC DESC] ] ; 46 23

47 Joining Database Tables Joining tables is the most important distinction between relational database and other DBs Join is performed when data are retrieved from more than one table at a time Equality comparison between foreign key and primary key of related tables Join tables by listing tables in FROM clause of SELECT statement DBMS creates Cartesian product of every table 48 24

Joining Tables with an Alias Alias identifies the source table from which data are taken Alias can be used to identify source table Any legal table name can be used as alias Add alias after table name in FROM clause FROM tablename alias 49 Recursive Joins Alias is especially useful when a table must be joined to itself Recursive query Use aliases to differentiate the table from itself 50 25