Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March.

Slides:



Advertisements
Similar presentations
Bordoloi and Bock Chapter 2 :TABLES AND INDEXES. Bordoloi and Bock One of the first steps in creating a database is to create the tables that will store.
Advertisements

Bordoloi and Bock Chapter 5 : Aggregate Row Functions.
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Bordoloi and Bock Chapter 3 :Single Table Query Basics.
Introduction to Structured Query Language (SQL)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
Prentice Hall © COS 346 Day 10. Prentice Hall © Agenda Questions?Questions? Assignment 3 CorrectedAssignment 3 Corrected –2 B’s, 4 C’s, 1.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.
Bordoloi and BockCopyright 2004 Prentice Hall, Inc.3-1 COS 346 Day 14.
Introduction to Structured Query Language (SQL)
A Guide to SQL, Seventh Edition. Objectives Understand, create, and drop views Recognize the benefits of using views Grant and revoke user’s database.
1 Chapter 2 Reviewing Tables and Queries. 2 Chapter Objectives Identify the steps required to develop an Access application Specify the characteristics.
Pretice Hall © COS 346 Day 12. Pretice Hall © Agenda Questions?Questions? Quiz 1 correctedQuiz 1 corrected –1 A, 5 B’s, 1 C and 1 F Assignment.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Introduction to SQL  SQL or sequel  It is a standardised language with thousands of pages in the standard  It can be in database system through GUI,
Oracle Data Definition Language (DDL)
Copyright © Curt Hill SQL The Data Definition Language.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
ASP.NET Programming with C# and SQL Server First Edition
15 Structured Query Language (SQL). 2 Objectives After completing this section, you should be able to: Understand Structured Query Language (SQL) and.
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Concepts of Database Management, Fifth Edition Chapter 4: The Relational Model 3: Advanced Topics.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
Chapter 7 SQL HUANG XUEHUA. SQL SQL server2005 introduction Install components  management studio.
CSC 2720 Building Web Applications Database and SQL.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
SQL (DDL & DML Commands)
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Unit 6 Data Storage Design. Key Concepts 1. Database overview 2. SQL review 3. Designing fields 4. Denormalization 5. File organization 6. Object-relational.
11 3 / 12 CHAPTER Databases MIS105 Lec15 Irfan Ahmed Ilyas.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Topic 1: Introduction to SQL. SQL stands for Structured Query Language. SQL is a standard computer language for accessing and manipulating databases SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Data Types Lesson 4. Skills Matrix Table A table stores your data. Tables are relational in that they are organized as rows and columns (a matrix). Each.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Oracle 11g: SQL Chapter 4 Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Pretice Hall © Chapter 3: Single Table Query Basics SQL for SQL Server Bijoy Bordoloi and Douglas Bock.
Sql DDL queries CS 260 Database Systems.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
Working with Columns, Characters, and Rows. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Apply the concatenation.
Session 1 Module 1: Introduction to Data Integrity
9-1 © Prentice Hall, 2007 Topic 9: Physical Database Design Object-Oriented Systems Analysis and Design Joey F. George, Dinesh Batra, Joseph S. Valacich,
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
LECTURE FOUR Introduction to SQL DDL with tables DML with tables.
CDT/1 Creating data tables and Referential Integrity Objective –To learn about the data constraints supported by SQL2 –To be able to relate tables together.
Oracle 10g Retrieving Data Using the SQL SELECT Statement.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
Other database objects (Sequence and view). What Is a Sequence? A sequence: Automatically generates sequential numbers Is a sharable object Is typically.
Creating Database Objects
SQL Query Getting to the data ……..
TABLES AND INDEXES Ashima Wadhwa.
Managing Tables, Data Integrity, Constraints by Adrienne Watt
ATS Application Programming: Java Programming
Chapter 8: Views and Synonyms
Chapter 4: Adding Power to Queries
Chapter 5: Aggregate Functions and Grouping of Data
ORACLE SQL Developer & SQLPLUS Statements
Copyright 2004 Prentice Hall, Inc.
IST 318 Database Administration
Creating Database Objects
Presentation transcript:

Pretice Hall © COS 346 Day 12

7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March 23 Capstone Progress Report OverdueCapstone Progress Report Overdue Erwin tutorialErwin tutorial – New Time line (next slide)New Time line (next slide) –One less quiz 10%) –One less assignment ( %) Still drop lowest scoreStill drop lowest score More on SQL & SQL ServerMore on SQL & SQL Server –We do chap 2-10 in SQL Text next

New time line MarchMarch –16 - SQL Assignment 5 dueAssignment 5 due –19 - SQL –23 - SQL Assignment 6 dueAssignment 6 due –26 - SQL –31 - SQL Assignment 7 dueAssignment 7 due Progress reportProgress report AprilApril –2 Database Redesign –6 - Database redesign Quiz 2Quiz 2 Assignment 8 dueAssignment 8 due –9 - Managing Multiuser databases –13 - Managing Multiuser databases Assignment 9 due –16 Managing Multiuser databases –20 Database access standards Progress report –23 - Database access standards Assignment 10 due –27 Quiz 3 Capstones Presentations Due

Prentice Hall © Chapter 2 : Creating Tables and Indexes SQL for SQL Server Bijoy Bordoloi and Douglas Bock

Prentice Hall © Objectives Learn how to name tables, columns, and constraints.Learn how to name tables, columns, and constraints. Select appropriate data types.Select appropriate data types. Create, Alter, and Drop tables.Create, Alter, and Drop tables. Specify primary and foreign keys.Specify primary and foreign keys. Specify and maintain referential integrity among tables.Specify and maintain referential integrity among tables. Insert, Delete, and Update rows in tables.Insert, Delete, and Update rows in tables. Create and drop indexes.Create and drop indexes.

Prentice Hall © One of the first steps in creating a database is to create the tables that will store organization’s data.One of the first steps in creating a database is to create the tables that will store organization’s data. In order to create a table, four pieces of information must be determined:In order to create a table, four pieces of information must be determined: 1.The table name 2.The column (field) names 3.Column data types and 4.Column sizes Table Creation

Prentice Hall © Table and Column names should be meaningful and reflect the nature of the data that is to be stored.Table and Column names should be meaningful and reflect the nature of the data that is to be stored. If the data stored is about the products that a firm sells, then the table should probably be named product!If the data stored is about the products that a firm sells, then the table should probably be named product! If products are identified by a string of eight characters, then the column that stores the product information data should be named product_number, or product_code.If products are identified by a string of eight characters, then the column that stores the product information data should be named product_number, or product_code. Naming Tables and Columns

Prentice Hall © Picking a Data type The data type chosen for a column determines the nature of the data that can be stored in the column.The data type chosen for a column determines the nature of the data that can be stored in the column. This is termed the Domain of valid column values.This is termed the Domain of valid column values.

Prentice Hall © Data type Transact-SQL provides numerous data types categorized as follows:Transact-SQL provides numerous data types categorized as follows: Numeric data types.Numeric data types. String or Character data types – this includes binary data (bit strings).String or Character data types – this includes binary data (bit strings). Date and/or time data types.Date and/or time data types. Derived data types.Derived data types. Special, new data.Special, new data.

Prentice Hall © Integer Numeric Data Types BIGINT: Integer values requiring 8 bytes of storage. ( +/- 2 32)BIGINT: Integer values requiring 8 bytes of storage. ( +/- 2 32) INTEGER or INT: Integer values requiring 4 bytes of storage. INT is short for INTEGER.INTEGER or INT: Integer values requiring 4 bytes of storage. INT is short for INTEGER. SMALLINT: Integer values requiring 2 bytes of storage.SMALLINT: Integer values requiring 2 bytes of storage. TINYINT: Integer values (non-negative only) that can be stored in 1 byte. (2 8)TINYINT: Integer values (non-negative only) that can be stored in 1 byte. (2 8)

Prentice Hall © Real Numeric Data Types DECIMAL(p,[s]) or DEC: Fixed point values with precision p that specifies the total number of digits, with assumed decimal point of scale s to the right of the decimal. Memory requirements vary from 2 to 17 bytes depending on the value of p. The specification of a value for s is optional. NUMERIC(p,[s]): Same as DECIMAL. REAL: Floating point values. Positive values stored range from 2.23E-308 to 1.79E+308. Negative values stored range from -2.23E-308 to -1.79E+308. FLOAT[(p)]: Floating point values like REAL where the parameter p specifies the precision. When p = 25, the number is stored using 8 bytes and is double-precision.

Prentice Hall © Monetary Numeric Data Types MONEY: Monetary values requiring 8 bytes of storage. This corresponds to 8 byte DECIMAL values rounded to four digits to the right of the decimal point.MONEY: Monetary values requiring 8 bytes of storage. This corresponds to 8 byte DECIMAL values rounded to four digits to the right of the decimal point. –$ SMALLMONEY: Monetary values requiring 4 bytes of storage.SMALLMONEY: Monetary values requiring 4 bytes of storage. –$123.46

Prentice Hall © Character (String) Data Types CHAR[(n)] or CHARACTER(n): Fixed-length string values where n is the number of characters in the string. The parameter n cannot be greater than 8,000. The default length when n is omitted is 1 character. NCHAR[(n)]: Fixed-length string values storing Unicode character data. Each NCHAR character requires 2 bytes of storage whereas CHAR data requires 1 byte of storage per character. The parameter n cannot be greater than 4,000. VARCHAR[(n)]: Variable-length string values where n is the maximum number of characters in the string. The parameter n cannot be greater than 8,000. Also termed CHAR VARYING and CHARACTER VARYING.

Prentice Hall © Character (String) Data Types Contd. NVARCHAR[(n)]: Variable-length string values storing Unicode characters. This data type has the same characteristics of storage as NCHAR. TEXT[(n)]: Fixed-length string up to 2,147,483,647 characters. NTEXT[(n)]: Stores large string values of varying lengths with a maximum length of 1,073,741,823 characters. NTEXT data characters are stored using the Unicode scheme of 2 bytes per character while TEXT data requires 1 byte of storage per character.

Prentice Hall © Binary (and Bit) String Data Types BINARY[(n)]: Fixed-length bit string of exactly n bytes where the maximum value of the parameter n is VARBINARY[(n)]: Variable-length bit string where n is the maximum number of bytes stored. The maximum value of the parameter n is IMAGE[(n)]: Fixed-length bit strings of nearly unlimited values ~2 GB. BIT: Stores Boolean data. Each value requires only a single bit of storage. The values stored are limited to TRUE, FALSE, or NULL.

Prentice Hall © Date and Time Data Types DATETIME: Date and time data requiring 4 bytes of storage for the date and 4 bytes of storage for the time. # of days from Jan 1, 1753 SMALLDATETIME: Date and time data requiring 2 bytes of storage for the date and 2 bytes of storage for the time. # of days from Jan 1, 1900 # of days from Jan 1, 1900

Prentice Hall © Derived Data Types SYSNAME: Columns defined as NVARCHAR(128) that store the names of database objects in the system catalog. TIMESTAMP: Columns defined as VARBINARY(8) or BINARY(8) that stores the current value for each database that is used to timestamp rows that are inserted or updated that contain a TIMESTAMP column.

Prentice Hall © CREATING A TABLE Create a simple table that stores five items of information about employees for an organization.Create a simple table that stores five items of information about employees for an organization. The table is named “employee” and stores information about each employee’s social security number, last name, first name, date hired, and annual salary.The table is named “employee” and stores information about each employee’s social security number, last name, first name, date hired, and annual salary.

Prentice Hall © Table Creation CREATE TABLE employee ( emp_ssn CHAR(9), emp_last_name VARCHAR(25), emp_first_name VARCHAR(25), emp_date_of_birth DATETIME, emp_salary MONEY ); The table named “employee”, is specified along with five data columns.The table named “employee”, is specified along with five data columns. Each column has a name that is unique within the table and is specified to store a specific type of data.Each column has a name that is unique within the table and is specified to store a specific type of data.

Prentice Hall © Data Integrity and Table Constraints The term data integrity simply means that the data stored in the table is valid.The term data integrity simply means that the data stored in the table is valid. There are different types of data integrity, often referred to as constraints.There are different types of data integrity, often referred to as constraints. The specifications of different data types aid in maintaining certain aspects of the data stored for employees.The specifications of different data types aid in maintaining certain aspects of the data stored for employees.

Prentice Hall © NOT NULL Constraint A NOT NULL constraint means that a data row must have a value for the column specified as NOT NULL.A NOT NULL constraint means that a data row must have a value for the column specified as NOT NULL. A fairly standard practice is to assign each constraint a unique constraint name.A fairly standard practice is to assign each constraint a unique constraint name. It is common to use either a prefix or suffix to denote the type of constraint. In this text, we use prefixes. The prefix for a NOT NULL constraint is ‘nn.’It is common to use either a prefix or suffix to denote the type of constraint. In this text, we use prefixes. The prefix for a NOT NULL constraint is ‘nn.’Example emp_last_name VARCHAR(25) CONSTRAINT nn_emp_last_name NOT NULL CONSTRAINT nn_emp_last_name NOT NULL

Prentice Hall © PRIMARY KEY Constraint Each table must normally contain a column or set of columns that uniquely identifies rows of data that are stored in the table. This column or set of columns is referred to as the primary key. Example: Example: emp_ssnCHAR(9) emp_ssnCHAR(9) CONSTRAINT pk_employee PRIMARY KEY, CONSTRAINT pk_employee PRIMARY KEY,….….

Prentice Hall © Composite PRIMARY KEY Constraint If a table requires two or more columns in order to identify each row, the primary key is termed a composite primary key.If a table requires two or more columns in order to identify each row, the primary key is termed a composite primary key.Example: CREATE TABLE assignment ( work_emp_ssn CHAR(9), work_emp_ssn CHAR(9), work_pro_number SMALLINT, work_pro_number SMALLINT, work_hours DECIMAL (5,1), work_hours DECIMAL (5,1), CONSTRAINT pk_assignment PRIMARY KEY ( work_emp_ssn, work_pro_number ), PRIMARY KEY ( work_emp_ssn, work_pro_number ),…….…….

Prentice Hall © CHECK Constraint Sometimes the data values stored in a specific column must fall within some acceptable range of values.Sometimes the data values stored in a specific column must fall within some acceptable range of values. A CHECK constraint is used to enforce this data limit.A CHECK constraint is used to enforce this data limit. emp_salaryMONEY CONSTRAINT ck_emp_salary CONSTRAINT ck_emp_salary CHECK (emp_salary <= 85000), CHECK (emp_salary <= 85000),

Prentice Hall © UNIQUE Constraint Sometimes it is necessary to enforce uniqueness for a column value that is not a primary key column.Sometimes it is necessary to enforce uniqueness for a column value that is not a primary key column. The UNIQUE constraint can be used to enforce this rule.The UNIQUE constraint can be used to enforce this rule. Assume that each parking space for the organization is numbered and that no two employees can be assigned the same parking space.Assume that each parking space for the organization is numbered and that no two employees can be assigned the same parking space. emp_parking_space INT emp_parking_space INT CONSTRAINT un_emp_parking_space UNIQUE, CONSTRAINT un_emp_parking_space UNIQUE,

Prentice Hall © Commands to Manage and Alter Tables Viewing a Table Description The SQL Query Analyzer provides the ability to examine the columns that comprise a table through the object browser facility.The SQL Query Analyzer provides the ability to examine the columns that comprise a table through the object browser facility.

Prentice Hall © Viewing a Table Description

Prentice Hall © Altering a column for an existing Table Modifying existing tables to either add new columns or alter existing columns can be accomplished with the ALTER TABLE statement.Modifying existing tables to either add new columns or alter existing columns can be accomplished with the ALTER TABLE statement. The current data type of the emp_parking_space column is INT (INTEGER). Due to growth in the availability of employee parking spaces, you have determined that it is necessary to modify the definition of this column to specify a BIGINT data type.The current data type of the emp_parking_space column is INT (INTEGER). Due to growth in the availability of employee parking spaces, you have determined that it is necessary to modify the definition of this column to specify a BIGINT data type.

Prentice Hall © ALTER TABLE Command The ALTER TABLE command can be used to modify the emp_parking_space column to specify the BIGINT data type.The ALTER TABLE command can be used to modify the emp_parking_space column to specify the BIGINT data type. ALTER TABLE employee DROP CONSTRAINT un_emp_parking_space; ALTER TABLE employee ALTER COLUMN emp_parking_space BIGINT; ALTER TABLE employee ADD CONSTRAINT un_emp_parking_space ADD CONSTRAINT un_emp_parking_space UNIQUE (emp_parking_space); UNIQUE (emp_parking_space);

Prentice Hall © Adding New Columns The ALTER TABLE command can be used to add a new column to the employee table.The ALTER TABLE command can be used to add a new column to the employee table. Suppose that an organization recognizes the need to track the gender of employees in order to meet a governmental reporting requirement, an emp_gender column can be added to the employee table.Suppose that an organization recognizes the need to track the gender of employees in order to meet a governmental reporting requirement, an emp_gender column can be added to the employee table. ALTER TABLE employee ADD emp_gender CHAR(1);

Prentice Hall © Relating Tables – Identifying Foreign Keys Normally, in a relational database, data rows in one table are related to data rows in other tables.Normally, in a relational database, data rows in one table are related to data rows in other tables. The department table will store information about departments within the organization.The department table will store information about departments within the organization. Each department is identified by a unique, 2-digit department number (primary key).Each department is identified by a unique, 2-digit department number (primary key).

Prentice Hall © Relating Tables- Identifying Foreign Keys Contd. Relating Tables- Identifying Foreign Keys Contd. CREATE TABLE department ( dpt_noSMALLINT dpt_noSMALLINT CONSTRAINT pk_department PRIMARY KEY, CONSTRAINT pk_department PRIMARY KEY, dpt_nameVARCHAR2(20) dpt_nameVARCHAR2(20) CONSTRAINT nn_dpt_name NOT NULL CONSTRAINT nn_dpt_name NOT NULL); Employees are generally assigned to work in departments. In an organization, at a given time, an employee is assigned to a single department.Employees are generally assigned to work in departments. In an organization, at a given time, an employee is assigned to a single department. In order to link rows in the employee table to rows in department table we need to introduce a new type of constraint, the FOREIGN KEY constraint.In order to link rows in the employee table to rows in department table we need to introduce a new type of constraint, the FOREIGN KEY constraint.

Prentice Hall © Relating Tables- Identifying Foreign Keys Contd. Relating Tables- Identifying Foreign Keys Contd. Foreign keys (FKs) are columns in one table that reference primary key (PK) values in another or in the same table.Foreign keys (FKs) are columns in one table that reference primary key (PK) values in another or in the same table. Let’s relate employee rows to the PK column named dpt_no in the department table.Let’s relate employee rows to the PK column named dpt_no in the department table. The value stored to the emp_dpt_number column for any given employee row must match a value stored in the dpt_no column in the department table.The value stored to the emp_dpt_number column for any given employee row must match a value stored in the dpt_no column in the department table.

Prentice Hall © Relating Tables- Identifying Foreign Keys Contd.

Prentice Hall © Relating Tables- Identifying Foreign Keys Contd. Relating Tables- Identifying Foreign Keys Contd. CREATE TABLE employee ( emp_ssn CHAR(9) emp_ssn CHAR(9) CONSTRAINT pk_employee PRIMARY KEY, CONSTRAINT pk_employee PRIMARY KEY, emp_last_name VARCHAR(25) emp_last_name VARCHAR(25) CONSTRAINT nn_emp_last_name NOT NULL, CONSTRAINT nn_emp_last_name NOT NULL,………… emp_parking_space INT CONSTRAINT un_emp_parking_space UNIQUE, CONSTRAINT un_emp_parking_space UNIQUE, emp_gender CHAR(1) NULL, emp_gender CHAR(1) NULL, emp_dpt_number SMALLINT, emp_dpt_number SMALLINT, CONSTRAINT fk_emp_dpt FOREIGN KEY (emp_dpt_number) REFERENCES department, REFERENCES department,);

Prentice Hall © MAINTAINING REFERENTIAL INTEGRITY FOREIGN KEY constraints are also referred to as referential integrity constraints, and assist in maintaining database integrity.FOREIGN KEY constraints are also referred to as referential integrity constraints, and assist in maintaining database integrity. Referential integrity stipulates that values of a foreign key must correspond to values of a primary key in the table that it references. But what happens if the primary key values change or the row that is referenced is deleted or updated?Referential integrity stipulates that values of a foreign key must correspond to values of a primary key in the table that it references. But what happens if the primary key values change or the row that is referenced is deleted or updated?

Prentice Hall © MAINTAINING REFERENTIAL INTEGRITY Contd.

Prentice Hall © MAINTAINING REFERENTIAL INTEGRITY Contd. What if some specific employee, say, Waiman Zhu decides to seek employment elsewhere and leaves The Company? If Zhu's row is deleted from the employee table, the dependent table will have three rows (dependents) that do not belong to an employee row. A special clause for the FOREIGN KEY constraint enables the maintenance of referential integrity to prevent this type of problem. This is the ON DELETE CASCADE clause.

Prentice Hall © MAINTAINING REFERRENTIAL INTEGRITY Contd. CREATE TABLE dependent ( dep_emp_ssn CHAR(9), dep_emp_ssn CHAR(9), dep_name VARCHAR(50), dep_name VARCHAR(50), dep_gender CHAR(1) NULL, dep_gender CHAR(1) NULL, dep_date_of_birth DATETIME NULL, dep_date_of_birth DATETIME NULL, dep_relationship VARCHAR(10) NULL, dep_relationship VARCHAR(10) NULL, CONSTRAINT pk_dependent PRIMARY KEY (dep_emp_ssn, dep_name), CONSTRAINT fk_dep_emp_ssn FOREIGN KEY (dep_emp_ssn) REFERENCES employee FOREIGN KEY (dep_emp_ssn) REFERENCES employee ON DELETE CASCADE ON DELETE CASCADE);

Prentice Hall © MAINTAINING REFERENTIAL INTEGRITY Contd. Because of this special ON DELETE CASCADE clause in the dependent table, if Zhu's row is deleted from the employee table, this clause will cause Zhu's dependent's to be deleted automatically from the dependent table, thereby maintaining referential integrity between the two tables.

Prentice Hall © MAINTAINING REFERENTIAL INTEGRITY Contd. The other ON DELETE clause option is to specify NO ACTION as the object of the clause. When NO ACTION is the option, any attempted deletion of an employee row that has associated dependent rows will fail with an error from SQL Server.The other ON DELETE clause option is to specify NO ACTION as the object of the clause. When NO ACTION is the option, any attempted deletion of an employee row that has associated dependent rows will fail with an error from SQL Server. SQL Server also supports the ON UPDATE CASCADE option.SQL Server also supports the ON UPDATE CASCADE option.

Prentice Hall © Dropping a Table Tables can be removed from the database with the DROP TABLE command.Tables can be removed from the database with the DROP TABLE command. DROP TABLE assignment; This command deletes both the table structure, its data, related constraints, and indexes.This command deletes both the table structure, its data, related constraints, and indexes. Note: If you attempt to drop a table that is referenced through FOREIGN KEY constraint by another table, then the DROP TABLE statement will fail. For example, you cannot DROP the project table without altering or dropping the assignment table first.

Prentice Hall © Populating Tables: The INSERT Command The INSERT command is used to store data in tables.The INSERT command is used to store data in tables. The INSERT command is often embedded in higher-level programming language applications as an embedded SQL command.The INSERT command is often embedded in higher-level programming language applications as an embedded SQL command. We focus on two different forms of the INSERT command.We focus on two different forms of the INSERT command.

Prentice Hall © POPULATING TABLES: THE INSERT Command Contd. The first form is used if a new row will have a value inserted into each column of the row.The first form is used if a new row will have a value inserted into each column of the row. INSERT INTO table VALUES (column1 value, column2 value, …); INSERT INTO department VALUES (7, 'Production'); INSERT INTO department VALUES (3, 'Admin and Records'); INSERT INTO department VALUES (1, 'Headquarters');

Prentice Hall © POPULATING TABLES: THE INSERT Command Contd. The second form of the INSERT command is used to insert rows where some of the column data is unknown (NULL ).The second form of the INSERT command is used to insert rows where some of the column data is unknown (NULL ). This form of the INSERT command requires that you specify the names of the columns for which data are being stored.This form of the INSERT command requires that you specify the names of the columns for which data are being stored. INSERT INTO table (column1 name, column2 name,...) VALUES (column1 value, column2 value,...); VALUES (column1 value, column2 value,...); INSERT INTO employee (emp_ssn, emp_last_name, emp_first_name,emp_salary) VALUES (' ', 'Bock', 'Douglas', 30000); VALUES (' ', 'Bock', 'Douglas', 30000);

Prentice Hall © The DELETE Command It removes one or more rows from a table. Multiple table delete operations are not allowed in SQL.It removes one or more rows from a table. Multiple table delete operations are not allowed in SQL. The syntax of the DELETE command is:The syntax of the DELETE command is: DELETE FROM table_name [WHERE condition];

Prentice Hall © The DELETE Command Contd. As the WHERE clause is optional, you can easily delete all rows from a table by omitting a WHERE clause because the WHERE clause limits the scope of the DELETE operation.As the WHERE clause is optional, you can easily delete all rows from a table by omitting a WHERE clause because the WHERE clause limits the scope of the DELETE operation. For example, the DELETE FROM command shown here removes all rows in the assignment table.For example, the DELETE FROM command shown here removes all rows in the assignment table. DELETE FROM assignment;

Prentice Hall © The UPDATE Command Values stored in individual columns of selected rows can be modified (updated) with the UPDATE command.Values stored in individual columns of selected rows can be modified (updated) with the UPDATE command. Updating columns is different from altering columns.Updating columns is different from altering columns. The ALTER command changes the table structure, but leaves the table data unaffected.The ALTER command changes the table structure, but leaves the table data unaffected. The UPDATE command changes data in the table, not the table structure.The UPDATE command changes data in the table, not the table structure.

Prentice Hall © The UPDATE Command Contd. The general syntax of the UPDATE command is: The general syntax of the UPDATE command is: UPDATE table SET column = expression [,column = expression]... [WHERE condition]; UPDATE employee SET emp_salary = WHERE emp_ssn = ' '; WHERE emp_ssn = ' ';

Prentice Hall © Committing Transactions Unlike many other relational DBMS products such as Oracle, SQL Server automatically commits after every INSERT, DELETE, or UPDATE operation.Unlike many other relational DBMS products such as Oracle, SQL Server automatically commits after every INSERT, DELETE, or UPDATE operation. One option for controlling when transactions commit is to use explicit transaction specifications by grouping SQL statements within transaction delimiters: BEGIN TRANSACTION and COMMIT TRANSACTION.One option for controlling when transactions commit is to use explicit transaction specifications by grouping SQL statements within transaction delimiters: BEGIN TRANSACTION and COMMIT TRANSACTION. This is you “Save your bacon” commandThis is you “Save your bacon” command

Prentice Hall © Committing Transactions Contd. BEGIN TRANSACTION DELETE FROM employee WHERE emp_ssn = ' '; WHERE emp_ssn = ' '; DELETE FROM employee WHERE emp_ssn = ' '; WHERE emp_ssn = ' '; COMMIT TRANSACTION; The BEGIN TRANSACTION statement begins an explicit transaction. Two employee rows are deleted, but the change to the database does not take place until the COMMIT TRANSACTION statement processes. At any point prior to execution of COMMIT TRANSACTION, the ROLLBACK TRANSACTION statement can be used to cancel the deletions that are in-process.

Prentice Hall © COMPUTED (Derived)COLUMNS Sometimes you will want to store information in a column that is derived from other information stored in the table. Examine the CREATE TABLE statement shown below:Sometimes you will want to store information in a column that is derived from other information stored in the table. Examine the CREATE TABLE statement shown below: CREATE TABLE equipment ( eqp_no CHAR(4) eqp_no CHAR(4) CONSTRAINT pk_equipment PRIMARY KEY, CONSTRAINT pk_equipment PRIMARY KEY, eqp_description VARCHAR(15), eqp_description VARCHAR(15), eqp_value MONEY, eqp_value MONEY, eqp_qty_on_hand SMALLINT, eqp_qty_on_hand SMALLINT, eqp_total_value AS eqp_value * eqp_qty_on_hand, eqp_total_value AS eqp_value * eqp_qty_on_hand, eqp_pro_number SMALLINT, eqp_pro_number SMALLINT, CONSTRAINT fk_eqp_pro_number FOREIGN KEY (eqp_pro_number) REFERENCES project REFERENCES project ON DELETE CASCADE ); ON DELETE CASCADE );

Prentice Hall © COMPUTED (Derived) COLUMNS Contd. –When values are inserted into the table, it is not necessary to insert a value for the eqp_total_value derived column. –Data for a computed column is not actually stored; rather, it is computed at the time that data for the column is selected. –Likewise, if a value stored in a row for either the eqp_value or eqp_qty_on_hand column(s) changes, the value displayed for the corresponding eqp_total_value computed column during a SELECT operation is automatically updated.

Prentice Hall © INDEXES Indexes are optional structures associated with tables. Indexes facilitate the rapid retrieval of information from tables much like the index of a book enables you to find specific topics in the book rapidly.Indexes are optional structures associated with tables. Indexes facilitate the rapid retrieval of information from tables much like the index of a book enables you to find specific topics in the book rapidly. There are different types of indexes including those used to enforce primary key constraints, unique indexes, non-unique indexes, composite indexes, and others.There are different types of indexes including those used to enforce primary key constraints, unique indexes, non-unique indexes, composite indexes, and others.

Prentice Hall © INDEXES Contd.

Prentice Hall © PRIMARY KEY indexes When a PRIMARY KEY constraint is specified, SQL Server will automatically create a unique index to support rapid data retrieval for the specified table.When a PRIMARY KEY constraint is specified, SQL Server will automatically create a unique index to support rapid data retrieval for the specified table. Without an index, a command that retrieves data will cause the DBMS to completely scan a table for rows that satisfy the retrieval condition.Without an index, a command that retrieves data will cause the DBMS to completely scan a table for rows that satisfy the retrieval condition. For example, consider the following SELECT statement that will display a list of employees assigned to a specific department.For example, consider the following SELECT statement that will display a list of employees assigned to a specific department.

Prentice Hall © PRIMARY KEY indexes Contd. SELECT emp_last_name,emp_first_name, emp_dpt_number FROM employee WHERE emp_dpt_number = 7; If the employee table is not indexed on the emp_dpt_number column, SQL Server will have to scan the entire table in order to satisfy the query.If the employee table is not indexed on the emp_dpt_number column, SQL Server will have to scan the entire table in order to satisfy the query.

Prentice Hall © Creating an Index The general form of the CREATE INDEX command is:The general form of the CREATE INDEX command is: CREATE INDEX CREATE INDEX ON (column1, column2 … ); CREATE INDEX employee_emp_dpt_number ON employee (emp_dpt_number); ON employee (emp_dpt_number);

Prentice Hall © Creating a UNIQUE Index The general form of the CREATE UNIQUE INDEX command is:The general form of the CREATE UNIQUE INDEX command is: CREATE UNIQUE INDEX CREATE UNIQUE INDEX ON (column1, column2 … ); CREATE UNIQUE INDEX patient_pat_ssn ON patient (pat_ssn); ON patient (pat_ssn);

Prentice Hall © Creating a Composite Index A composite index (also called a concatenated index) is an index created on multiple columns of a table.A composite index (also called a concatenated index) is an index created on multiple columns of a table. Columns in a composite index can appear in any order and need not be adjacent columns in the table.Columns in a composite index can appear in any order and need not be adjacent columns in the table. Composite indexes enhance row retrieval speed for queries in which the WHERE clause references all or the leading portion of the columns in the composite index.Composite indexes enhance row retrieval speed for queries in which the WHERE clause references all or the leading portion of the columns in the composite index. Generally the most commonly accessed or most selective columns are listed first when creating the index.Generally the most commonly accessed or most selective columns are listed first when creating the index.

Prentice Hall © DROPPING Indexes An index should not be retained unless it improves system processing in some fashion.An index should not be retained unless it improves system processing in some fashion. All indexes on a table must be updated whenever row data is changed that is referenced by an index.All indexes on a table must be updated whenever row data is changed that is referenced by an index. Useless indexes burden the system by adding unnecessary maintenance and by needlessly occupying disk space. These indexes should be dropped.Useless indexes burden the system by adding unnecessary maintenance and by needlessly occupying disk space. These indexes should be dropped.

Prentice Hall © DROPPING Indexes Contd. The syntax of the DROP INDEX command is simple:The syntax of the DROP INDEX command is simple: DROP INDEX table_name.index_name; DROP INDEX employee.employee_emp_dpt_number;

Prentice Hall © Summary This chapter exposed you to the Data Definition Language (DDL) part of SQL.This chapter exposed you to the Data Definition Language (DDL) part of SQL. CREATE TABLE is the command that you use to define the structure of a table including selection and specification of:CREATE TABLE is the command that you use to define the structure of a table including selection and specification of: –Appropriate data types and length. –Primary and foreign keys. –Various data integrity constraints such as NOT NULL, CHECK, and UNIQUE. –Referential integrity rules. You also learned how to:You also learned how to: –DROP and ALTER the structural definition of tables. –Insert, Delete, and Update rows in tables. –Create and drop INDEXES.

Pretice Hall © Chapter 3: Single Table Query Basics SQL for SQL Server Bijoy Bordoloi and Douglas Bock

Pretice Hall © OBJECTIVES Write simple SELECT statements.Write simple SELECT statements. Learn to use the CAST and CONVERT commands to format columnar output.Learn to use the CAST and CONVERT commands to format columnar output. Eliminate duplicate rows with the DISTINCT clause.Eliminate duplicate rows with the DISTINCT clause. Use the WHERE clause to specify selection criteria and conditions.Use the WHERE clause to specify selection criteria and conditions. Order rows with the ORDER BY clause.Order rows with the ORDER BY clause. Display a TOP few rows from the result table.Display a TOP few rows from the result table. Save the output of a query INTO a temporary table.Save the output of a query INTO a temporary table.

Pretice Hall © SIMPLE SELECT STATEMENTS The main element in a SQL query is the SELECT statement. The main element in a SQL query is the SELECT statement. A properly written SELECT statement will always produce a result in the form of one or more rows of output. A properly written SELECT statement will always produce a result in the form of one or more rows of output. The SELECT statement chooses (select) rows from one or more tables according to specific criteria. The SELECT statement chooses (select) rows from one or more tables according to specific criteria.

Pretice Hall © Example SELECT * FROM employee; emp_ssn emp_last_name emp_first_name emp_middle_name Bock Douglas B Amin Hyder NULL Joshi Dinesh Null more rows and columns will be displayed… – This query selects rows from the “employee” table. – The asterisk (*) tells Oracle to select (display) all columns contained in the table “employee”.

Pretice Hall © Example Contd. The following SELECT statement produces an identical output.The following SELECT statement produces an identical output. SELECT emp_ssn, emp_last_name, emp_first_name, emp_middle_name, emp_address, emp_city, emp_state, emp_zip, emp_date_of_birth, emp_salary, emp_parking_space, emp_gender, emp_dpt_number, emp_superssn FROM employee; Note that a comma separates each column name. This syntax is required. The SELECT statement also specifies a table name in the FROM clause. Finally, the semicolon at the end of the query, which is optional in T-SQL, indicates that this is the end of the query.

Pretice Hall © SQL Server will process the query regardless of whether you type the entire query on one line, or indent.SQL Server will process the query regardless of whether you type the entire query on one line, or indent. There are no rules about how many words can be put on a line or where to break a line.There are no rules about how many words can be put on a line or where to break a line. Although SQL Server does not require indenting, indenting enhances readability.Although SQL Server does not require indenting, indenting enhances readability. You must, however, follow the order of the syntax of the SELECT statement shown on the next slide.You must, however, follow the order of the syntax of the SELECT statement shown on the next slide. Indenting SQL Code

Pretice Hall © The following keywords (which constitute the order of the syntax of a SELECT statement) are your signal to start a new line.The following keywords (which constitute the order of the syntax of a SELECT statement) are your signal to start a new line. »SELECT »FROM »WHERE »GROUP BY »HAVING »ORDER BY Indenting SQL Code Contd.

Pretice Hall © Specify the column names you want displayed in the result set by typing the exact, complete column names.Specify the column names you want displayed in the result set by typing the exact, complete column names. Separate each column name with a comma (,).Separate each column name with a comma (,). The column names selected must belong to the table(s) named in the FROM clause.The column names selected must belong to the table(s) named in the FROM clause. Although we use a semicolon to mark the end of a query in almost all the examples in this book, the semicolon at the end of the query is optional in T-SQL (versus required when using SQL for other databases such as Oracle).Although we use a semicolon to mark the end of a query in almost all the examples in this book, the semicolon at the end of the query is optional in T-SQL (versus required when using SQL for other databases such as Oracle). Selecting Specific Columns

Pretice Hall © At times you will write a query where the columnar output will not fit onto a single display line (and may ‘wrap’ around).At times you will write a query where the columnar output will not fit onto a single display line (and may ‘wrap’ around). You can clean up the result table for such a query by modifying the output display size of specific columns.You can clean up the result table for such a query by modifying the output display size of specific columns. In SQL Server you can reformat the column output with automatic data type conversion by using the CAST and CONVERT functions in the SELECT statement.In SQL Server you can reformat the column output with automatic data type conversion by using the CAST and CONVERT functions in the SELECT statement. Formatting Default Output

Pretice Hall © Using the CAST FunctionUsing the CAST Function SELECT emp_ssn, CAST(emp_last_name As CHAR(12)), CAST(emp_first_name As CHAR(12)), CAST(emp_date_of_birth As CHAR(12)), CAST(emp_date_of_birth As CHAR(12)),emp_superssn FROM employee; emp_ssn emp_superssn Bock Douglas Dec Amin Hyder Mar Joshi Dinesh Sep more rows will be displayed… Formatting Default Output Contd.

Pretice Hall © Using the CAST Function (Renaming Column Names)Using the CAST Function (Renaming Column Names) SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", emp_superssn "Supervisor_SSN" FROM employee; emp_ssn Last Name First Name Date of Birth Supervisor_SSN Bock Douglas Dec Amin Hyder Mar Joshi Dinesh Sep more rows will be displayed… Formatting Default Output Contd.

Pretice Hall © When labeling or renaming display columns from the default column names, be sure to follow these rules: Enclose the label in quotes, either single or double.Enclose the label in quotes, either single or double. Do NOT separate the label from the expression with a comma.Do NOT separate the label from the expression with a comma. The label must follow the function or column name.The label must follow the function or column name. Formatting Default Output Contd.

Pretice Hall © Using the CONVERT Function Apart from the CAST function, you can also use the CONVERT function, which provides some additional features for formatting the output of numeric columns.Apart from the CAST function, you can also use the CONVERT function, which provides some additional features for formatting the output of numeric columns. Both CONVERT and CAST functions are discussed further in Chapter 9.Both CONVERT and CAST functions are discussed further in Chapter 9. Formatting Default Output Contd.

Pretice Hall © Using the CONVERT FunctionUsing the CONVERT Function SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "Last Name", CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", emp_salary FROM employee; emp_ssn First Name Last Name Date of Birth emp_salary Bock Douglas Dec Amin Hyder Mar Joshi Dinesh Sep Formatting Default Output Contd.

Pretice Hall © Using the CONVERT FunctionUsing the CONVERT Function SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "Last Name", CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employee; emp_ssn First Name Last Name Date of Birth Salary Bock Douglas Dec , Amin Hyder Mar , Joshi Dinesh Sep , Formatting Default Output Contd.

Pretice Hall © Using the CONVERT Function As shown in the previous example, the reformatted emp_salary data now has only two digits to the right of the decimal point and includes a comma for every three digits to the left of the decimal point.As shown in the previous example, the reformatted emp_salary data now has only two digits to the right of the decimal point and includes a comma for every three digits to the left of the decimal point. This was achieved by setting the style parameter value of the CONVERT function to “1”.This was achieved by setting the style parameter value of the CONVERT function to “1”. Also, the column heading label was changed to read Salary instead of the default column name (emp_salary).Also, the column heading label was changed to read Salary instead of the default column name (emp_salary). Formatting Default Output Contd.

Pretice Hall © Using the CONVERT Function We can improve the output for the salary column even further if we place a dollar sign ($) in front of the values for the employee salary figures.We can improve the output for the salary column even further if we place a dollar sign ($) in front of the values for the employee salary figures. As shown in the next slide, this result is achieved by including a constant character “$” as a column name in the SELECT statement and concatenating this column with the salary column. The “+” sign is the concatenation symbol.As shown in the next slide, this result is achieved by including a constant character “$” as a column name in the SELECT statement and concatenating this column with the salary column. The “+” sign is the concatenation symbol. Formatting Default Output Contd.

Pretice Hall © Using the CONVERT Function SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "Last Name", CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", '$' + CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employee; emp_ssn First Name Last Name Date of Birth Salary Bock Douglas Dec $ 30, Amin Hyder Mar $ 25, Joshi Dinesh Sep $ 38, Formatting Default Output Contd.

Pretice Hall © Although SQL is a free-form language, there are still syntactical rules that must be followed or you will receive an error message instead of the desired result table.Although SQL is a free-form language, there are still syntactical rules that must be followed or you will receive an error message instead of the desired result table. SQL Server will display some error message indicating the possible cause of error and the line number (in your query) where the error has occurred.SQL Server will display some error message indicating the possible cause of error and the line number (in your query) where the error has occurred. Common Errors

Pretice Hall © Invalid Column Name In this SELECT statement, the employee social security number column name is spelled incorrectly.In this SELECT statement, the employee social security number column name is spelled incorrectly. SELECT emp_socsecno FROM employee; Server: Msg 207, Level 16, State 3, Line 1 Invalid column name ‘emp_socsecno’.

Pretice Hall © FROM Keyword Missing The next SELECT statement is missing the FROM clause so that no table name has been specified.The next SELECT statement is missing the FROM clause so that no table name has been specified. Without a table name, the DBMS does not know which table to query.Without a table name, the DBMS does not know which table to query. SELECT emp_ssn; Server: Msg 207, Level 16, State 3, Line 1 Invalid column name ‘emp_ssn’.

Pretice Hall © Invalid Command Structure You must follow the syntax order of the SELECT statement correctly.You must follow the syntax order of the SELECT statement correctly. In the example below, the order of the SELECT and FROM clauses is reversed. SQL Server simply returns an ‘incorrect syntax’ error message.In the example below, the order of the SELECT and FROM clauses is reversed. SQL Server simply returns an ‘incorrect syntax’ error message. FROM employee SELECT emp_ssn; Server: Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'FROM'.

Pretice Hall © Errors in Placing Commas Must have a comma between column names in the SELECT clauseMust have a comma between column names in the SELECT clause SELECT emp_ssn, emp_last_name emp_first_name FROM employee; emp_ssn emp_first_name Bock Amin Joshi more rows will be displayed…

Pretice Hall © Errors in Placing Commas Contd. Must not have a comma after the last column names in the SELECT clauseMust not have a comma after the last column names in the SELECT clause SELECT emp_ssn, emp_last_name, emp_first_name, FROM employee; Server: Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'FROM'.

Pretice Hall © THE DISTINCT CLAUSE SQL Server provides a means for eliminating duplicate rows in a result table through use of the DISTINCT keyword. SELECT emp_salary FROM employee; emp_salary (8 row(s) affected) SELECT DISTINCT emp_salary FROM employee; emp_salary (5 row(s) affected)

Pretice Hall © THE DISTINCT CLAUSE Contd. The DISTINCT keyword also eliminates duplicate rows where more than one column is displayed in the result table. SELECT room_id, bed_type_id FROM bed; room_id bed_type_id SW1001 R1 SW1002 R1 SW1003 R2.. SW1010 R1 SW1010 R2 SW1011 R2 SW1012 R1 (98 row(s) affected) SELECT DISTINCT room_id, bed_type_id FROM bed; room_id bed_type_id SW1001 R1 SW1002 R1 SW1003 R1... SW1004 R2 SW1005 R2 SW1006 R1 SW1006 R2 SW1010 RE SW1011 R2 SW1012 R1 (65 row(s) affected)

Pretice Hall © THE WHERE CLAUSE THE WHERE CLAUSE Specific rows can be selected by adding a WHERE clause to the SELECT query.Specific rows can be selected by adding a WHERE clause to the SELECT query. SELECT emp_ssn, emp_last_name, emp_first_name, emp_salary FROM employee WHERE emp_salary >= 35000; emp_ssn emp_last_name emp_first_name emp_salary Joshi Dinesh Zhu Waiman Joyner Suzanne Bordoloi Bijoy

Pretice Hall © Comparison Operators Operator Meaning =equal to =equal to <less than <less than >greater than >greater than >=greater than or equal to >=greater than or equal to <=less than or equal to <=less than or equal to !=not equal to !=not equal to <>not equal to <>not equal to !>not greater than !>not greater than !<not less than !<not less than

Pretice Hall © Comparing Character Data Comparing Character Data Comparison operators are not limited to numeric data.Comparison operators are not limited to numeric data. They can also be used with columns containing character data.They can also be used with columns containing character data. If the value is a character string or date, you must surround the value (string of characters) with which a column is being compared with single quotation (' ') marks.If the value is a character string or date, you must surround the value (string of characters) with which a column is being compared with single quotation (' ') marks. SELECT emp_ssn, emp_last_name, emp_first_name FROM employee WHERE emp_gender = ‘M’;

Pretice Hall © Comparing Character Data Comparing Character Data You can also write SELECT statements that use operators other than the equal sign.You can also write SELECT statements that use operators other than the equal sign. SELECT emp_last_name, emp_first_name FROM employee WHERE emp_last_name >= 'J'; emp_last_name emp_first_name Joshi Dinesh Zhu Waiman Joyner Suzanne Markis Marcia Prescott Sherri

Pretice Hall © Comparison Operators in the WHERE Clause When you use comparison operators in a WHERE clause, the arguments (objects or values you are comparing) on both sides of the operator must be either a column name, or a specific value. If a specific value is specified, then the value must be either a numeric value or a literal, character string.When you use comparison operators in a WHERE clause, the arguments (objects or values you are comparing) on both sides of the operator must be either a column name, or a specific value. If a specific value is specified, then the value must be either a numeric value or a literal, character string.

Pretice Hall © Comparison Operators in the WHERE Clause Contd. SELECT emp_ssn, emp_last_name, emp_first_name FROM employee WHERE emp_gender = M; ERROR at line 3: ORA-00904: invalid column name Since the literal string value was not enclosed by single quote marks, SQL Server assumed the letter M to be a column name.Since the literal string value was not enclosed by single quote marks, SQL Server assumed the letter M to be a column name. There is no column named M in the table so an error was returned.There is no column named M in the table so an error was returned.

Pretice Hall © THE ORDER BY CLAUSE Output from a SELECT statement can be sorted by using the optional ORDER BY clause.Output from a SELECT statement can be sorted by using the optional ORDER BY clause. SELECT emp_last_name, emp_first_name FROM employee WHERE emp_last_name >= 'J' ORDER BY emp_last_name; emp_last_name emp_first_name Joshi Dinesh Joyner Suzanne Markis Marcia Prescott Sherri Zhu Waiman

Pretice Hall © ORDER BY With ASC and DESC By default, the ORDER BY clause sorts output rows in a result table in ascending order.By default, the ORDER BY clause sorts output rows in a result table in ascending order. To sort columns from high to low, or descending, an optional keyword DESC must be specified.To sort columns from high to low, or descending, an optional keyword DESC must be specified.  ASC - Ascending, low to high.  DESC - Descending, high to low.  When ASC or DESC is used, it must be followed by the column name.  You can include a maximum of 16 column names in the ORDER BY clause.

Pretice Hall © ORDER BY With ASC and DESC Contd. When ASC or DESC is used, it must be followed by the column name.When ASC or DESC is used, it must be followed by the column name. SELECT emp_last_name, emp_first_name, emp_salary FROM employee WHERE emp_salary > ORDER BY DESC emp_salary; Server: Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'DESC'.

Pretice Hall © ORDER BY With More Than One Column Sorting by multiple columns can improve the look and usability of the information.Sorting by multiple columns can improve the look and usability of the information. SELECT emp_dpt_number, emp_last_name, emp_first_name FROM employee ORDER BY emp_dpt_number DESC, emp_last_name; emp_dpt_number emp_last_name emp_first_name Bock Douglas 7 Joshi Dinesh 7 Prescott Sherri 7 Zhu Waiman 3 Amin Hyder 3 Joyner Suzanne 3 Markis Marcia 1 Bordoloi Bijoy

Pretice Hall © The TOP Keyword A SELECT statement that specifies the TOP keyword is particularly useful in business for producing listings of the top salespeople, top products sold, and the like.A SELECT statement that specifies the TOP keyword is particularly useful in business for producing listings of the top salespeople, top products sold, and the like. SQL example in the next slide combines the use of the TOP keyword with the ORDER BY clause to list the employees with the 2 largest salaries.SQL example in the next slide combines the use of the TOP keyword with the ORDER BY clause to list the employees with the 2 largest salaries.

Pretice Hall © The TOP Keyword Contd. SELECT TOP 2 emp_ssn, emp_last_name, emp_salary FROM employee ORDER BY emp_salary DESC; emp_ssn emp_last_name emp_salary Bordoloi Zhu

Pretice Hall © The TOP Keyword Contd. But what if there are salary ties?But what if there are salary ties? SELECT TOP 2 WITH TIES emp_ssn, emp_last_name, emp_salary FROM employee ORDER BY emp_salary DESC; emp_ssn emp_last_name emp_salary Bordoloi Zhu Joyner

Pretice Hall © The TOP Keyword Contd. If the PERCENT keyword is specified, only the specified percentage of rows is included in the result table.If the PERCENT keyword is specified, only the specified percentage of rows is included in the result table. SELECT TOP 40 PERCENT WITH TIES emp_ssn, emp_last_name, emp_salary FROM employee ORDER BY emp_salary DESC; emp_ssn emp_last_name emp_salary Bordoloi Zhu Joyner Joshi

Pretice Hall © The INTO Clause The optional INTO clause of the SELECT statement is used to create temporary tables.The optional INTO clause of the SELECT statement is used to create temporary tables. This clause can be used to store the output of a result table for future manipulation. This clause can be used to store the output of a result table for future manipulation. These temporary tables are not part of an organization’s permanent, base tables; rather, they are simply an additional option to support managerial decision-making.These temporary tables are not part of an organization’s permanent, base tables; rather, they are simply an additional option to support managerial decision-making.

Pretice Hall © The INTO Clause Contd. SELECT TOP 40 PERCENT WITH TIES emp_ssn, emp_last_name, emp_salary INTO top_salary_employees FROM employee ORDER BY emp_salary DESC; (4 row(s) affected) SELECT * FROM top_salary_employees; emp_ssn emp_last_name emp_salary Bordoloi Zhu Joyner Joshi (4 row(s) affected)

Pretice Hall © SUMMARY You retrieve data from a relational database using the SELECT statement. In this chapter, you were exposed to the following clauses of the SELECT statement: SELECT, FROM, WHERE, and ORDER BY. The SELECT clause controls the selection of columns in the final result table. The SELECT clause controls the selection of columns in the final result table. The FROM clause indicates to the DBMS the tables that are involved in processing the query. The FROM clause indicates to the DBMS the tables that are involved in processing the query. The WHERE clause controls the selection of rows depending on the selection criteria and conditions specified in the WHERE clause. The WHERE clause controls the selection of rows depending on the selection criteria and conditions specified in the WHERE clause. The ORDER BY clause controls the sort order according to which the output of the final result table should be displayed. The ORDER BY clause controls the sort order according to which the output of the final result table should be displayed. You also learned how to: Use the CAST and CONVERT commands to format columnar output. Use the CAST and CONVERT commands to format columnar output. Eliminate duplicate rows with the DISTINCT clause. Eliminate duplicate rows with the DISTINCT clause. Display a TOP few rows from the result table. Display a TOP few rows from the result table. Save the output of a query INTO a temporary table. Save the output of a query INTO a temporary table.