Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March."— Presentation transcript:

1 Pretice Hall © 20041 COS 346 Day 12

2 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 –http://www.isqa.unomaha.edu/wolcott/tutorials/erwin/ERwin.html http://www.isqa.unomaha.edu/wolcott/tutorials/erwin/ERwin.html New Time line (next slide)New Time line (next slide) –One less quiz (3 @ 10%) –One less assignment ( 9 @ 4.4444%) 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

3 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

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

5 Prentice Hall © 20045 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.

6 Prentice Hall © 20046 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

7 Prentice Hall © 20047 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

8 Prentice Hall © 20048 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.

9 Prentice Hall © 20049 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.

10 Prentice Hall © 200410 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)

11 Prentice Hall © 200411 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.

12 Prentice Hall © 200412 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. –$123.4567 SMALLMONEY: Monetary values requiring 4 bytes of storage.SMALLMONEY: Monetary values requiring 4 bytes of storage. –$123.46

13 Prentice Hall © 200413 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.

14 Prentice Hall © 200414 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.

15 Prentice Hall © 200415 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 8000. VARBINARY[(n)]: Variable-length bit string where n is the maximum number of bytes stored. The maximum value of the parameter n is 8000. 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.

16 Prentice Hall © 200416 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

17 Prentice Hall © 200417 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.

18 Prentice Hall © 200418 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.

19 Prentice Hall © 200419 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.

20 Prentice Hall © 200420 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.

21 Prentice Hall © 200421 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

22 Prentice Hall © 200422 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,….….

23 Prentice Hall © 200423 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 ),…….…….

24 Prentice Hall © 200424 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),

25 Prentice Hall © 200425 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,

26 Prentice Hall © 200426 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.

27 Prentice Hall © 200427 Viewing a Table Description

28 Prentice Hall © 200428 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.

29 Prentice Hall © 200429 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);

30 Prentice Hall © 200430 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);

31 Prentice Hall © 200431 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).

32 Prentice Hall © 200432 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.

33 Prentice Hall © 200433 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.

34 Prentice Hall © 200434 Relating Tables- Identifying Foreign Keys Contd.

35 Prentice Hall © 200435 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,);

36 Prentice Hall © 200436 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?

37 Prentice Hall © 200437 MAINTAINING REFERENTIAL INTEGRITY Contd.

38 Prentice Hall © 200438 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.

39 Prentice Hall © 200439 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);

40 Prentice Hall © 200440 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.

41 Prentice Hall © 200441 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.

42 Prentice Hall © 200442 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.

43 Prentice Hall © 200443 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.

44 Prentice Hall © 200444 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');

45 Prentice Hall © 200445 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 ('999111111', 'Bock', 'Douglas', 30000); VALUES ('999111111', 'Bock', 'Douglas', 30000);

46 Prentice Hall © 200446 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];

47 Prentice Hall © 200447 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;

48 Prentice Hall © 200448 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.

49 Prentice Hall © 200449 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 = 45000 WHERE emp_ssn = '999444444'; WHERE emp_ssn = '999444444';

50 Prentice Hall © 200450 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

51 Prentice Hall © 200451 Committing Transactions Contd. BEGIN TRANSACTION DELETE FROM employee WHERE emp_ssn = '999111111'; WHERE emp_ssn = '999111111'; DELETE FROM employee WHERE emp_ssn = '999444444'; WHERE emp_ssn = '999444444'; 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.

52 Prentice Hall © 200452 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 );

53 Prentice Hall © 200453 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.

54 Prentice Hall © 200454 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.

55 Prentice Hall © 200455 INDEXES Contd.

56 Prentice Hall © 200456 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.

57 Prentice Hall © 200457 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.

58 Prentice Hall © 200458 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);

59 Prentice Hall © 200459 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);

60 Prentice Hall © 200460 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.

61 Prentice Hall © 200461 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.

62 Prentice Hall © 200462 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;

63 Prentice Hall © 200463 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.

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

65 Pretice Hall © 200465 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.

66 Pretice Hall © 200466 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.

67 Pretice Hall © 200467 Example SELECT * FROM employee; emp_ssn emp_last_name emp_first_name emp_middle_name --------- --------------- ---------------- --------------- 99111111 Bock Douglas B 999222222 Amin Hyder NULL 999333333 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”.

68 Pretice Hall © 200468 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.

69 Pretice Hall © 200469 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

70 Pretice Hall © 200470 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.

71 Pretice Hall © 200471 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

72 Pretice Hall © 200472 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

73 Pretice Hall © 200473 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 ----------- ----------- ---------- --------------- --------------- 999111111 Bock Douglas Dec 5 1950 999444444 999222222 Amin Hyder Mar 29 1969 999555555 999333333 Joshi Dinesh Sep 15 1972 999444444 more rows will be displayed… Formatting Default Output Contd.

74 Pretice Hall © 200474 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 ----------- ------------ ------------- --------------- ------------------ 999111111 Bock Douglas Dec 5 1950 999444444 999222222 Amin Hyder Mar 29 1969 999555555 999333333 Joshi Dinesh Sep 15 1972 999444444 more rows will be displayed… Formatting Default Output Contd.

75 Pretice Hall © 200475 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.

76 Pretice Hall © 200476 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.

77 Pretice Hall © 200477 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 ---------- ------------- ------------- ---------------- -------------- 999111111 Bock Douglas Dec 5 1950 30000.0000 999222222 Amin Hyder Mar 29 1969 25000.0000 999333333 Joshi Dinesh Sep 15 1972 38000.0000 Formatting Default Output Contd.

78 Pretice Hall © 200478 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 ---------- ------------- ------------- ---------------- -------------- 999111111 Bock Douglas Dec 5 1950 30,000.00 999222222 Amin Hyder Mar 29 1969 25,000.00 999333333 Joshi Dinesh Sep 15 1972 38,000.00 Formatting Default Output Contd.

79 Pretice Hall © 200479 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.

80 Pretice Hall © 200480 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.

81 Pretice Hall © 200481 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 ---------- ------------- ------------- ---------------- --------------- 999111111 Bock Douglas Dec 5 1950 $ 30,000.00 999222222 Amin Hyder Mar 29 1969 $ 25,000.00 999333333 Joshi Dinesh Sep 15 1972 $ 38,000.00 Formatting Default Output Contd.

82 Pretice Hall © 200482 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

83 Pretice Hall © 200483 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’.

84 Pretice Hall © 200484 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’.

85 Pretice Hall © 200485 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'.

86 Pretice Hall © 200486 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 ----------- ------------------------- 999111111 Bock 999222222 Amin 999333333 Joshi more rows will be displayed…

87 Pretice Hall © 200487 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'.

88 Pretice Hall © 200488 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----------30000.000025000.000038000.000043000.000043000.000055000.000025000.000025000.0000 (8 row(s) affected) SELECT DISTINCT emp_salary FROM employee; emp_salary----------25000.000030000.000038000.000043000.000055000.0000 (5 row(s) affected)

89 Pretice Hall © 200489 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)

90 Pretice Hall © 200490 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 ------- ------------- -------------- ---------- 999333333 Joshi Dinesh 38000.0000 999444444 Zhu Waiman 43000.0000 999555555 Joyner Suzanne 43000.0000 999666666 Bordoloi Bijoy 55000.0000

91 Pretice Hall © 200491 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

92 Pretice Hall © 200492 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’;

93 Pretice Hall © 200493 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

94 Pretice Hall © 200494 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.

95 Pretice Hall © 200495 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.

96 Pretice Hall © 200496 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

97 Pretice Hall © 200497 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.

98 Pretice Hall © 200498 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 > 35000 ORDER BY DESC emp_salary; Server: Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'DESC'.

99 Pretice Hall © 200499 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 -------------- ------------------ -------------------- 7 Bock Douglas 7 Joshi Dinesh 7 Prescott Sherri 7 Zhu Waiman 3 Amin Hyder 3 Joyner Suzanne 3 Markis Marcia 1 Bordoloi Bijoy

100 Pretice Hall © 2004100 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.

101 Pretice Hall © 2004101 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 --------- ---------------- ------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000

102 Pretice Hall © 2004102 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 --------- ---------------- ------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000 999555555 Joyner 43000.0000

103 Pretice Hall © 2004103 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 --------- ---------------- ------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000 999555555 Joyner 43000.0000 999333333 Joshi 38000.0000

104 Pretice Hall © 2004104 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.

105 Pretice Hall © 2004105 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 --------- ------------------------- --------------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000 999555555 Joyner 43000.0000 999333333 Joshi 38000.0000 (4 row(s) affected)

106 Pretice Hall © 2004106 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.


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

Similar presentations


Ads by Google