Chapter 7 Introduction to Structured Query Language SQL

  • Slides: 45
Download presentation
Chapter # 7 Introduction to Structured Query Language (SQL) BIS 3635 - Database Systems

Chapter # 7 Introduction to Structured Query Language (SQL) BIS 3635 - Database Systems School of Management, Business Information Systems, Assumption University A. Thanop Somprasong

Objectives l In this chapter, you will learn: l The basic commands and functions

Objectives l In this chapter, you will learn: l The basic commands and functions of SQL l How to use SQL for data administration (to create tables, indexes, and views) l How to use SQL for data manipulation (to add, modify, delete, and retrieve data) l How to use SQL to query a database for useful information

Introduction to SQL l l SQL functions fit into two broad categories: l Data

Introduction to SQL l l SQL functions fit into two broad categories: l Data definition language l Data manipulation language Basic command set has vocabulary of less than 100 words American National Standards Institute (ANSI) prescribes a standard SQL Several SQL dialects exist

SQL Family SQL (Structured Query Language) Data Definition Language (DDL) Data Manipulation Language (DML)

SQL Family SQL (Structured Query Language) Data Definition Language (DDL) Data Manipulation Language (DML) Data Control Language (DCL) CREATE ALTER DROP SELECT INSERT UPDATE DELETE GRANT REVOKE

Data Definition Commands l The database model l In this chapter, a simple database

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

Data Definition Commands (2)

Data Definition Commands (2)

Creating the Database l l Two tasks must be completed: l Create database structure

Creating the Database l l Two tasks must be completed: l Create database structure l Create tables that will hold end-user data First task: l RDBMS creates physical files that will hold database l Differs substantially from one RDBMS to another

The Database Schema l l Authentication l DBMS verifies that only registered users are

The Database Schema l l Authentication l DBMS verifies that only registered users are able to access database l Log on to RDBMS using user ID and password created by database administrator Schema l Group of database objects that are related to each other

Data Types l l Data type selection is usually dictated by nature of data

Data Types l l Data type selection is usually dictated by nature of data and by intended use Supported data types: l Number(L, D), Integer, Smallint, Decimal(L, D) l Char(L), Varchar 2(L) l Date, Timestamp l Real, Double, Float l Interval day to hour l Many other types

Creating Table Structures l l l l Use one line per column (attribute) definition

Creating Table Structures l l l l 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 Primary key attributes contain both a NOT NULL and a UNIQUE specification RDBMS will automatically enforce referential integrity foreign keys Command sequence ends with semicolon

SQL Constraints l l NOT NULL constraint l Ensures that column does not accept

SQL Constraints l l NOT NULL constraint l Ensures that column does not accept nulls UNIQUE constraint l Ensures that all values in column are unique DEFAULT constraint l Assigns value to attribute when a new row is added to table CHECK constraint l Validates data when attribute value is entered

SQL Indexes l l When primary key is declared, DBMS automatically creates unique index

SQL Indexes l l 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 l Index based on two or more attributes l Often used to prevent data duplication

Data Manipulation Commands l l l INSERT SELECT UPDATE DELETE ROLLBACK COMMIT

Data Manipulation Commands l l l INSERT SELECT UPDATE DELETE ROLLBACK COMMIT

Adding Table Rows l INSERT l Used to enter data into table l Basic

Adding Table Rows l INSERT l Used to enter data into table l Basic Syntax: INSERT INTO columnname VALUES (value 1, value 2, … , value. N);

Adding Table Rows (2) l l When entering values, notice that: l Row contents

Adding Table Rows (2) l l When entering values, notice that: l Row contents are entered between parentheses l Character and date values are entered between apostrophes l Numerical entries are not enclosed in apostrophes l Attribute entries are separated by commas l A value is required for each column Use NULL for unknown values

Saving Table Changes l l Changes made to table contents are not physically saved

Saving Table Changes l l Changes made to table contents are not physically saved on disk until: l Database is closed l Program is closed l COMMIT command is used Syntax: COMMIT [WORK]; l Will permanently save any changes made to any table in the database

Listing (Showing) Table Rows l SELECT l l Used to list contents of table

Listing (Showing) Table Rows l SELECT l l Used to list contents of table Basic Syntax: SELECT columnlist FROM tablename; l l Columnlist represents one or more attributes, separated by commas Asterisk can be used as wildcard character to list all attributes

Updating Table Rows l UPDATE l Modify data in a table l Basic Syntax:

Updating Table Rows l UPDATE l Modify data in a table l Basic Syntax: UPDATE tablename SET columnname = expression [, columnname = expression] [WHERE conditionlist]; l If more than one attribute is to be updated in row, separate corrections with commas

Restoring Table Contents l l ROLLBACK l Undoes changes since last COMMIT l Brings

Restoring Table Contents l l ROLLBACK l Undoes changes since last COMMIT l Brings data back to pre-change values Syntax: ROLLBACK; l COMMIT and ROLLBACK only work with commands to add, modify, or delete table rows

Deleting Table Rows l DELETE l l Deletes a table row Basic Syntax: DELETE

Deleting Table Rows l DELETE l l Deletes a table row Basic Syntax: DELETE FROM tablename [WHERE conditionlist ]; l l WHERE condition is optional If WHERE condition is not specified, all rows from specified table will be deleted

Inserting Table Rows with a SELECT Subquery l INSERT l Inserts multiple rows from

Inserting Table Rows with a SELECT Subquery l INSERT l Inserts multiple rows from another table (source) l Uses SELECT subquery l Subquery: query embedded (or nested) inside another query l Subquery executed first l Syntax: INSERT INTO tablename SELECT columnlist FROM tablename;

SELECT Queries l Fine-tune SELECT command by adding restrictions to search criteria using: l

SELECT Queries l Fine-tune SELECT command by adding restrictions to search criteria using: l Conditional restrictions l Arithmetic operators l Logical operators l Special operators

Selecting Rows with Conditional Restrictions l l Select partial table contents by placing restrictions

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

Arithmetic Operators The Rule of Precedence l l Perform operations within parentheses Perform power

Arithmetic Operators The Rule of Precedence l l Perform operations within parentheses Perform power operations Perform multiplications and divisions Perform additions and subtractions

Logical Operators: AND, OR and NOT l l l Searching data involves multiple conditions

Logical Operators: AND, OR and NOT l l l Searching data involves multiple conditions Logical operators: AND, OR, and NOT Can be combined l Parentheses placed to enforce precedence order l Conditions in parentheses always executed first Boolean algebra: mathematical field dedicated to use of logical operators NOT negates result of conditional expression

Logical Operators: AND, OR and NOT l l l BETWEEN: checks whether attribute value

Logical Operators: AND, OR and NOT l l l 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

Advanced Data Definitions Commands l l l All changes in table structure are made

Advanced Data Definitions Commands l l l All changes in table structure are made by using ALTER command Three options l ADD adds a column l MODIFY changes column characteristics l DROP deletes a column Can also be used to: l Add table constraints l Remove table constraints

Changing a Column’s Data Type l l l ALTER can be used to change

Changing a Column’s Data Type l l l ALTER can be used to change data type Some RDBMSs do not permit changes to data types unless column is empty Basic Syntax: ALTER TABLE tablename ALTER COLUMN columnname datatype ;

Adding a Column l l Use ALTER to add column l Do not include

Adding a Column l l Use ALTER to add column l Do not include the NOT NULL clause for new column Basic Syntax: ALTER TABLE tablename ADD columnname datatype ;

Dropping a Column l l Use ALTER to drop column l Some RDBMSs impose

Dropping a Column l l Use ALTER to drop column l Some RDBMSs impose restrictions on the deletion of an attribute Basic Syntax: ALTER TABLE tablename DROP COLUMN columnname ;

Advanced Data Updates l l UPDATE command updates only data in existing rows If

Advanced Data Updates l l UPDATE command updates only data in existing rows If relationship between entries and existing columns, can assign values to slots Arithmetic operators useful in data updates In Oracle, ROLLBACK command undoes changes made by last two UPDATE statements

Advanced Data Updates (2)

Advanced Data Updates (2)

Copying Parts of Tables l l l SQL permits copying contents of selected table

Copying Parts of Tables l l l SQL permits copying contents of selected table columns l 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

Copying Parts of Tables (2)

Copying Parts of Tables (2)

Adding Primary and Foreign Key Designations l l When table is copied, integrity rules

Adding Primary and Foreign Key Designations l l When table is copied, integrity rules do not copy l Primary and foreign keys manually defined on new table User ALTER TABLE command l Syntax: ALTER TABLE tablename ADD PRIMARY KEY (fieldname); l For foreign key, use FOREIGN KEY in place of PRIMARY KEY

Deleting a Table from the Database l DROP l Deletes table from database l

Deleting a Table from the Database l DROP l Deletes table from database l Syntax: DROP TABLE tablename; l Can drop a table only if it is not the “one” side of any relationship l Otherwise RDBMS generates an error message l Foreign key integrity violation

Advanced SELECT Queries l l l Logical operators work well in the query environment

Advanced SELECT Queries l l l Logical operators work well in the query environment SQL provides useful functions that: l Count l Find minimum and maximum values l Calculate averages, etc. SQL allows user to limit queries to: l Entries having no duplicates l Entries whose duplicates may be grouped

Ordering a Listing l l ORDER BY clause useful when listing order important Basic

Ordering a Listing l l ORDER BY clause useful when listing order important Basic Syntax: SELECT columnlist FROM tablelist [WHERE conditionlist] [ORDER BY columnlist [ASC | DESC]]; l Ascending order by default

Listing Unique Values l l DISTINCT clause produces list of only values that are

Listing Unique Values l l DISTINCT clause produces list of only values that are different from one another Syntax Example: SELECT DISTINCT V_CODE FROM PRODUCT; l Access places nulls at the top of the list l Oracle places it at the bottom l Placement of nulls does not affect list contents

Aggregate Functions l l COUNT function tallies number of non-null values of an attribute

Aggregate Functions l l COUNT function tallies number of non-null values of an attribute l Takes one parameter: usually a column name MAX and MIN find highest (lowest) value in a table l Compute MAX value in inner query l Compare to each value returned by the query SUM computes total sum for any specified attribute AVG function format similar to MIN and MAX

Grouping Data l l Frequency distributions created by GROUP BY clause within SELECT statement

Grouping Data l l Frequency distributions created by GROUP BY clause within SELECT statement Basic Syntax: SELECT FROM [WHERE [GROUP BY [HAVING [ORDER BY columnlist tablelist conditionlist] columnlist] conditionlist] columnlist [ASC | DESC] ] ;

Grouping Data (2)

Grouping Data (2)

Virtual Tables: Creating a View l l l View is virtual table based on

Virtual Tables: Creating a View l l l View is virtual table based on SELECT query Create view by using CREATE VIEW command Special characteristics of relational view: l Name of view can be used anywhere a table name is expected l View dynamically updated l Restricts users to only specified columns and rows l Views may be used as basis for reports

Joining Database Tables l l l Joining tables is the most important distinction between

Joining Database Tables l l l 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 l Equality comparison between foreign key and primary key of related tables Join tables by listing tables in FROM clause of SELECT statement l DBMS creates Cartesian product of every table

THE END

THE END