50
Prentice Hall © 2004 1 SQL for SQL Server SQL for SQL Server Bijoy Bordoloi and Douglas Bock Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction Chapter 1: Introduction

Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Embed Size (px)

Citation preview

Page 1: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 1

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Chapter 1: IntroductionChapter 1: Introduction

Page 2: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 2

SQLSQL

• SQL, pronounced ‘Sequel’ or simply S-Q-L, is a SQL, pronounced ‘Sequel’ or simply S-Q-L, is a computer programming language that was computer programming language that was developed especially for querying relational developed especially for querying relational databases using a nonprocedural approach.databases using a nonprocedural approach.

• The term nonprocedural means that you can The term nonprocedural means that you can extract information by simply telling the system extract information by simply telling the system what information is needed without telling it how what information is needed without telling it how to perform the data retrieval.to perform the data retrieval.

• Transact-SQL or T-SQL is Microsoft's Transact-SQL or T-SQL is Microsoft's implementation of the SQL language. implementation of the SQL language.

Page 3: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 3

OBJECTIVESOBJECTIVES

• Develop a basic understanding of the relational Develop a basic understanding of the relational database.database.

• Learn the general capabilities of a relational database Learn the general capabilities of a relational database management system.management system.

• Become familiar with the features of the SQL Server Become familiar with the features of the SQL Server relational database management system.relational database management system.

• Learn to use the SQL Query Analyzer.Learn to use the SQL Query Analyzer.• Become familiar with the basic relational operations Become familiar with the basic relational operations

including the selection, projection, and join operations.including the selection, projection, and join operations.• Become familiar with the basic syntax of the SELECT Become familiar with the basic syntax of the SELECT

statement.statement.• Learn the T-SQL naming conventions.Learn the T-SQL naming conventions.

Page 4: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 4

DATA AND INFORMATIONDATA AND INFORMATION

• Information is derived from raw facts known Information is derived from raw facts known as data. as data.

• Data has little meaning or usefulness to Data has little meaning or usefulness to managers unless it is organized in some managers unless it is organized in some logical manner. logical manner.

• One of the most efficient ways to organize One of the most efficient ways to organize and manage data is through the use of and manage data is through the use of database management systems (DBMS). database management systems (DBMS).

Page 5: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 5

DBMSDBMS

• Some popular relational DBMS products are the Some popular relational DBMS products are the Oracle RDBMS, IBM’s DB2, Microsoft’s SQL Oracle RDBMS, IBM’s DB2, Microsoft’s SQL Server, and Microsoft’s desktop single user Server, and Microsoft’s desktop single user RDBMS named Microsoft Access. RDBMS named Microsoft Access.

• A DBMS provides both systems development A DBMS provides both systems development professionals and information users with an easy-professionals and information users with an easy-to-use interface to their organization’s database. to-use interface to their organization’s database.

Page 6: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 6

Relational DatabaseRelational Database

• The most common type of DBMS software in use The most common type of DBMS software in use today is termed a relational DBMS or RDBMS. today is termed a relational DBMS or RDBMS.

• A relational database stores data in the form of A relational database stores data in the form of tables.tables.

• A table is defined as a collection of rows and A table is defined as a collection of rows and columns.columns.

• The tables are formally known as relations; this The tables are formally known as relations; this is where the relational database gets its name. is where the relational database gets its name.

Page 7: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 7

TABLETABLE

Page 8: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 8

Characteristics of a Relation Characteristics of a Relation (Table) (Table)

• The order of rows and columns is immaterial.The order of rows and columns is immaterial.• All values are atomic – each row/column intersection All values are atomic – each row/column intersection

represents a single value. In other words, ‘repeating represents a single value. In other words, ‘repeating groups’ are not allowed.groups’ are not allowed.

• Every value in a column must be a member of a Every value in a column must be a member of a conceptual set of atomic values called a domain.conceptual set of atomic values called a domain.

• A value may be null, that is, not known or inapplicable.A value may be null, that is, not known or inapplicable.• A relation, A relation, by definitionby definition, cannot have duplicate rows. , cannot have duplicate rows.

Every table Every table mustmust have a ‘Primary Key’ ,which have a ‘Primary Key’ ,which guarantees that there are no duplicate rows.guarantees that there are no duplicate rows.

Page 9: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 9

Relating Tables: Foreign KeysRelating Tables: Foreign Keys• Foreign key – a (simple or composite) column that Foreign key – a (simple or composite) column that

refers to the primary key of some table (including refers to the primary key of some table (including itself) in a database.itself) in a database.

• Foreign and primary keys must be defined on same Foreign and primary keys must be defined on same data type.data type.

• A relational DBMS can relate any data field in one A relational DBMS can relate any data field in one table to any data field in another table as long as the table to any data field in another table as long as the two tables share a data field that is defined on the same two tables share a data field that is defined on the same ‘domain’ (the same data type).‘domain’ (the same data type).

• Therefore, if a table has a foreign key then you can Therefore, if a table has a foreign key then you can always link (‘join’) this table with the table where this always link (‘join’) this table with the table where this foreign key is the primary key.foreign key is the primary key.

• Foreign keys are also discussed further in Chapter 2.Foreign keys are also discussed further in Chapter 2.

Page 10: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 10

Relating TablesRelating Tables

Page 11: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 11

DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM

• A database management system (DBMS) manages the data in a database.

• A DBMS is a software package (collection of programs) that enables the users to create and maintain a database.

• A DBMS also enables data to be shared.• SQL is the language used to create and

retrieve data from a relational database using a RDMS, such as SQL Server.

Page 12: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 12

DBMSDBMS

Page 13: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 13

DATADATA

• Two types of data are stored within a Two types of data are stored within a database.database.

• User data: Data that must be stored by an User data: Data that must be stored by an organization. organization.

• System data: Data the database needs to System data: Data the database needs to manage user data to manage itself. This is manage user data to manage itself. This is also termed also termed metadata, or the data about data.metadata, or the data about data.

Page 14: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 14

DBMSDBMS Services Services

• Data definition for defining and storing Data definition for defining and storing all of the objects that comprise a database all of the objects that comprise a database such as tables and indexessuch as tables and indexes

• Data maintenance Data maintenance

• Data manipulation Data manipulation

• Data display Data display

• Data integrity Data integrity

• Data security Database backup and Data security Database backup and recoveryrecovery

Page 15: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 15

SQL Server VersionsSQL Server Versions

Edition Description

SQL Server Standard Edition

Small-and medium-sized businesses without large data center applications will find this edition best fits their budget. It supports up to four CPUs and 2GB of random access memory.

SQL Server Enterprise Edition

Aimed at large companies including multinational conglomerates that are moving into e-commerce. This version provides high availability and scalability. It can support up to 32 CPUs and 64GB of random access memory.

SQL Server Developer Edition

This is like the Enterprise Edition, but for system developers. It cannot be licensed for use in a production environment.

Page 16: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 16

SQL Server Versions Contd.SQL Server Versions Contd.SQL Server Desktop Edition

This Edition has the SQL Server database engine, but not all of the management tools or analysis services. Database size for this edition is limited to 2GB. It supports full application development and deployment for small business applications.

SQL Server 2000 Personal Edition

This version has much of the functionality of the Standard Edition. It can service small groups of concurrent access users. It will run on desktop Windows operating systems from Windows 98 to Windows 2000 Professional Edition.

SQL Server 2000 Windows CE Edition

This runs on the Windows CE operating system for pocket PC devices.

Page 17: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 17

SQL Server FeaturesSQL Server FeaturesFeature Description

Internet standard support

SQL Server uses Microsoft's new .NET technology to support data exchange across the Internet including new detailed support for the extensible-markup language, or XML.

Scalability SQL Server can be used to build very large, multiprocessor systems.

Security mechanisms

SQL Server's sophisticated security mechanisms control access to sensitive data through an assortment of privileges, for example, the privilege to read or write specific information within a database.

Backup and recovery

SQL Server's sophisticated backup and recovery programs minimize data loss and downtime if problems arise.

Page 18: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 18

SQL Server Features Cont.SQL Server Features Cont.

Space management

SQL Servers automated space management capability makes it easy for a database administrator to manage disk space for storage. These capabilities also include the ability to specify subsequent allocations on how much disk space to set aside for future requirements.

Open connectivity

SQL Server's open connectivity functionality provides uninterrupted access to the database throughout the day. It also provides open connectivity to and from other vendors’ software.

Tools and applications

SQL Server provides a wide range of development tools, end-user query tools, and support for third-party software applications that are used to model business processes and data and to generate program language code automatically.

Page 19: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 19

SQL: DDL and DMLSQL: DDL and DML

• SQL is used by SQL Server for all interaction SQL is used by SQL Server for all interaction with the database. SQL statements fall into with the database. SQL statements fall into two major categories:two major categories:

1.1. Data Definition Language(DDL)Data Definition Language(DDL): Set of SQL : Set of SQL commands that create and define objects in a commands that create and define objects in a database.database.

2.2. Data Manipulation Language(DML)Data Manipulation Language(DML): Set of : Set of SQL commands that allow users to SQL commands that allow users to manipulate the data in a database.manipulate the data in a database.

Page 20: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 20

SQLSQL• SQL is basically a free format language. This SQL is basically a free format language. This

means that there are no particular spacing rules means that there are no particular spacing rules that must be followed when typing SQL that must be followed when typing SQL commands.commands.

• SQL is a nonprocedural language. This means SQL is a nonprocedural language. This means that the user only has to specify the task for the that the user only has to specify the task for the DBMS to complete, but not how the task is to DBMS to complete, but not how the task is to be completed. The RDBMS parses (converts) be completed. The RDBMS parses (converts) the SQL commands and completes the task.the SQL commands and completes the task.

Page 21: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 21

Procedural and NonproceduralProcedural and Nonprocedural

Nonprocedural Procedural

SELECT emp_last_name, emp_first_nameFROM employeeWHERE emp_last_name = 'BOCK';

intIndex = 1DO WHILE intIndex <= Count_Of_Rows If emp_last_name = 'BOCK' Then DISPLAY emp_last_name, emp_first_name End If intIndex += 1LOOP

Page 22: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 22

SQL Query AnalyzerSQL Query Analyzer

GUI can be used to:GUI can be used to:

– Create databases.Create databases.

– Develop, test, and debug stored procedures. Develop, test, and debug stored procedures.

– Run SQL scripts – these are miniature programs that contain either Run SQL scripts – these are miniature programs that contain either DDL or DML commands or a combination of these commands. DDL or DML commands or a combination of these commands. An example would be a script to create a database, and then An example would be a script to create a database, and then populate the tables in the database with data.populate the tables in the database with data.

– Optimize system performance.Optimize system performance.

– Analyze query plans – these are the plans that the DBMS generates Analyze query plans – these are the plans that the DBMS generates for processing a query.for processing a query.

– Maintain and manage statistics concerning database performance.Maintain and manage statistics concerning database performance.

– Generate tune table indexes – the indexes are supposed to improve Generate tune table indexes – the indexes are supposed to improve system performance for data retrieval. system performance for data retrieval.

Page 23: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 23

SQL Query Analyzer Contd.SQL Query Analyzer Contd.

Page 24: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 24

SQL Query Analyzer Contd.SQL Query Analyzer Contd.

Page 25: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 25

SQL Query Analyzer Contd.SQL Query Analyzer Contd.

Page 26: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 26

SQL Query Analyzer Contd.SQL Query Analyzer Contd.

Page 27: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 27

Creating a DatabaseCreating a Database

• When SQL Server is initially installed, five When SQL Server is initially installed, five systemsystem databases are generated. These are named: (1) databases are generated. These are named: (1) master, (2) model, (3) msdb, (4) distribution, and master, (2) model, (3) msdb, (4) distribution, and (5) tempdb. (5) tempdb.

• When you create a new database in SQL Server, When you create a new database in SQL Server, the DBMS uses the the DBMS uses the modelmodel database as a template database as a template to create a new database. to create a new database.

• The command to create a user database is : The command to create a user database is :

CREATE DATABASE <database_name>CREATE DATABASE <database_name>

Note:Note: You must have prior authorization from your You must have prior authorization from your system administrator to execute this command. system administrator to execute this command.

Page 28: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 28

Creating a Database: Creating a Database: In-Class ExerciseIn-Class Exercise

• Invoke Query Analyzer, Log on to SQL Server, and Invoke Query Analyzer, Log on to SQL Server, and Create a database called Company:Create a database called Company:

CREATE DATABASE Company;CREATE DATABASE Company;• Simply type the command in the Editor pane of the Simply type the command in the Editor pane of the

Query window and click the Execute Query button (or Query window and click the Execute Query button (or press the F5 key). press the F5 key).

• Once the Company database has been created, you will Once the Company database has been created, you will see it listed in the Object Browser. If you do not see it in see it listed in the Object Browser. If you do not see it in the Object Browser, simply right-mouse click and select the Object Browser, simply right-mouse click and select the Refresh option to refresh the screen.the Refresh option to refresh the screen.

Page 29: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 29

The Company Database The Company Database

• Throughout this textbook you will study SQL Throughout this textbook you will study SQL commands against the backdrop of a sample commands against the backdrop of a sample database called the Company database, which is database called the Company database, which is described in Appendix A. You may wish to described in Appendix A. You may wish to familiarize yourself with Appendix A at this time. familiarize yourself with Appendix A at this time.

• Note that the Company database you just created Note that the Company database you just created does not contain any data yet. Chapter 2 explains does not contain any data yet. Chapter 2 explains the commands to populate a database through the commands to populate a database through creation of tables and insertion of rows in much creation of tables and insertion of rows in much more detail. more detail.

Page 30: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 30

Using a DatabaseUsing a Database

• After you have CREATED your database(s) After you have CREATED your database(s) you must use the USE command to select a you must use the USE command to select a database for future processing. database for future processing.

• You can type the USE command into the You can type the USE command into the Editor pane and execute it also.Editor pane and execute it also.

USE Company;USE Company;

The command(s) completed successfully.The command(s) completed successfully.

Page 31: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 31

Executing ScriptsExecuting Scripts• Sometimes you need to execute a script that Sometimes you need to execute a script that

contains a series of SQL statements. The contains a series of SQL statements. The Editor pane can be used to create and save a Editor pane can be used to create and save a script as shown in Figure 1.8. script as shown in Figure 1.8.

• Simply select the Editor pane to make it the Simply select the Editor pane to make it the active window, then use the toolbar Save active window, then use the toolbar Save option and specify the location, file name, and option and specify the location, file name, and file format when the Save Query dialog box file format when the Save Query dialog box displays. displays.

• You should use the default filename extension You should use the default filename extension of of .sql.sql when naming a script file. when naming a script file.

Page 32: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 32

Executing Scripts (Fig: 1.8)Executing Scripts (Fig: 1.8)

Page 33: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 33

Executing ScriptsExecuting Scripts• You can also open scripts and execute You can also open scripts and execute

them, even if they were created with them, even if they were created with another text editor, such as Microsoft another text editor, such as Microsoft Notepad or Word. Notepad or Word.

• Figure 1.9 shows this operation. Figure 1.9 shows this operation.

• Select the Load SQL Script toolbar Select the Load SQL Script toolbar button and when the Open Query File button and when the Open Query File dialog box displays, locate and select the dialog box displays, locate and select the name of the file to be opened. name of the file to be opened.

Page 34: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 34

Executing Scripts (Fig: 1.9)Executing Scripts (Fig: 1.9)

Page 35: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 35

Creating, Saving, and Running Creating, Saving, and Running a Sample Scripta Sample Script

• Practice creating, saving, and running a Practice creating, saving, and running a sample script file named sample script file named Product.sql as Product.sql as shown in shown in SQL Examples 1.1 and 1.2.SQL Examples 1.1 and 1.2.

• Type the code Type the code exactlyexactly as shown. as shown.• Do not worry if you do not understand Do not worry if you do not understand

(you are not expected to) the code at this (you are not expected to) the code at this point. Things will become clearer as we point. Things will become clearer as we cover more materials in later chapters.cover more materials in later chapters.

Page 36: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 36

RELATIONAL OPERATIONS: OVERVIEWRELATIONAL OPERATIONS: OVERVIEW

• SQL operations for creating new tables, SQL operations for creating new tables, inserting table rows, updating table rows, inserting table rows, updating table rows, deleting table rows, and querying databases deleting table rows, and querying databases are the primary means of interfacing with are the primary means of interfacing with relational databases.relational databases.

• The SELECT statement is used primarily to The SELECT statement is used primarily to write queries that write queries that extract extract information from information from the database, which is a collection of related the database, which is a collection of related tables. tables.

Page 37: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 37

RELATIONAL OPERATIONSRELATIONAL OPERATIONS

• The ability to select specific rows and The ability to select specific rows and columns from one or more tables is referred columns from one or more tables is referred to as the fundamental relational operations, to as the fundamental relational operations, and there are three of these operations: and there are three of these operations: – SelectionSelection– ProjectionProjection– JoinJoin

• The purpose of the next few slides is just to The purpose of the next few slides is just to familiarize you with each of these familiarize you with each of these operations. We will study these operations operations. We will study these operations in detail in later chapters.in detail in later chapters.

Page 38: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 38

Selection OperationSelection Operation

• A selection operation selects a subset of rows A selection operation selects a subset of rows in a table (relation) that satisfy a selection in a table (relation) that satisfy a selection condition. That subset can range from no condition. That subset can range from no rows to all rows in a table. The SELECT rows to all rows in a table. The SELECT statement below selects a subset of rows statement below selects a subset of rows through use of a WHERE clause.through use of a WHERE clause.

SELECT emp_ssn, emp_last_name, emp_first_name SELECT emp_ssn, emp_last_name, emp_first_name FROM employeeFROM employeeWHERE emp_ssn = '999111111';WHERE emp_ssn = '999111111';

emp_ssn emp_last_name emp_first_name emp_ssn emp_last_name emp_first_name

------------- --------------------- --------------------------- --------------------- --------------999111111 Bock Douglas999111111 Bock Douglas

Page 39: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 39

Projection OperationProjection Operation

• A projection operation selects only certain A projection operation selects only certain columns from the table, thus producing a subset columns from the table, thus producing a subset of all available columns.of all available columns.

• The result table can include anything from a The result table can include anything from a single column to all the columns in the table.single column to all the columns in the table.

Page 40: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 40

EXAMPLEEXAMPLE

• This SELECT statement selects a subset This SELECT statement selects a subset of columns from the employee table by of columns from the employee table by specifying the columns to be listed. specifying the columns to be listed.

SELECT emp_ssn, emp_first_name, SELECT emp_ssn, emp_first_name, emp_last_nameemp_last_name

FROM employee;FROM employee;emp_ssn emp_first_name emp_last_name emp_ssn emp_first_name emp_last_name

--------- ---------------- -------------- --------- ---------------- --------------

999111111 Douglas Bock999111111 Douglas Bock

999222222 Hyder Amin999222222 Hyder Amin

999333333 Dinesh Joshi999333333 Dinesh Joshi

more rows will display…more rows will display…

Page 41: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 41

Join OperationJoin Operation• A join operation combines data from two or A join operation combines data from two or

more tables based upon one or more common more tables based upon one or more common column values.column values.

• The relational join is a very powerful operation The relational join is a very powerful operation because it allows users to investigate because it allows users to investigate relationships among data elements. relationships among data elements.

• The following SELECT statement displays The following SELECT statement displays column information from both the employee column information from both the employee and department tables.and department tables.

• This SELECT statement also completes both This SELECT statement also completes both selection and projection operations. selection and projection operations.

Page 42: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 42

Join Operation: ExampleJoin Operation: Example

Page 43: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 43

JOIN: ExampleJOIN: Example

• The tables are joined upon values stored in the The tables are joined upon values stored in the department number columns named emp_dpt_number in department number columns named emp_dpt_number in the employee table and dpt_no in the department table.the employee table and dpt_no in the department table.

SELECT emp_ssn, emp_first_name, emp_last_name, dpt_nameSELECT emp_ssn, emp_first_name, emp_last_name, dpt_name

FROM employee, department FROM employee, department

WHERE emp_dpt_number = dpt_no;WHERE emp_dpt_number = dpt_no;

emp_ssn emp_first_name emp_last_name dpt_name emp_ssn emp_first_name emp_last_name dpt_name

------------- ---------------- -------------------- -------------- ------------- ---------------- -------------------- --------------

999111111 Douglas Bock Production999111111 Douglas Bock Production

999222222 Hyder Amin Admin and Records999222222 Hyder Amin Admin and Records

999333333 Dinesh Joshi Production999333333 Dinesh Joshi Production

more rows will display…more rows will display…

Page 44: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 44

SQL SyntaxSQL Syntax

• Now that you've seen some basic SQL Now that you've seen some basic SQL statements, you may have noticed that SQL statements, you may have noticed that SQL requires you to follow certain syntax rules; requires you to follow certain syntax rules; otherwise, an error message is returned by otherwise, an error message is returned by the system and your statements fail to the system and your statements fail to execute.execute.

Page 45: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 45

T-SQL Naming RulesT-SQL Naming Rules

• The rules for creating identifiers in T-The rules for creating identifiers in T-SQL differ slightly from those in the SQL differ slightly from those in the ANSI/ISO-92 SQL standard. ANSI/ISO-92 SQL standard.

• Identifiers are the names given by Identifiers are the names given by information system developers and information system developers and system users to database objects such as system users to database objects such as tables, columns, indexes, and other tables, columns, indexes, and other objects as well as the database itself. objects as well as the database itself.

Page 46: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 46

T-SQL Naming Rules Contd.T-SQL Naming Rules Contd.There are several rules for naming database objects that must be There are several rules for naming database objects that must be

followed:followed:

IdeIdentifiers must be no more than 128 characters.ntifiers must be no more than 128 characters.

• Identifiers can consist of letters, digits, or the symbols #, @, $, and Identifiers can consist of letters, digits, or the symbols #, @, $, and _ (underscore). _ (underscore).

• The first character of an identifier must be either a letter (a-z, A-The first character of an identifier must be either a letter (a-z, A-Z) or the #, @ or _ (underscore) symbol. After the first character, Z) or the #, @ or _ (underscore) symbol. After the first character, you may use digits, letters, or the symbols $, #, or _ (underscore).you may use digits, letters, or the symbols $, #, or _ (underscore).

• Temporary objects are named by using the # symbol as the first Temporary objects are named by using the # symbol as the first character of the identifier. Avoid using this symbol as the leading character of the identifier. Avoid using this symbol as the leading character when naming permanent database objects.character when naming permanent database objects.

• The @ symbol as the first character of an identifier denotes a The @ symbol as the first character of an identifier denotes a variable name. Avoid using this symbol as the leading character variable name. Avoid using this symbol as the leading character when naming other database objects. when naming other database objects.

• SQL keywords such as SELECT and WHERE cannot be used as SQL keywords such as SELECT and WHERE cannot be used as an identifier.an identifier.

Page 47: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 47

SELECT Statement Syntax OverviewSELECT Statement Syntax Overview

• Each select statement must follow precise Each select statement must follow precise syntactical and structural rules. syntactical and structural rules.

• For example, you cannot place the FROM clause For example, you cannot place the FROM clause before the SELECT clause, or place the FROM before the SELECT clause, or place the FROM clause after the WHERE clause or the ORDER BY clause after the WHERE clause or the ORDER BY clause, and so on. clause, and so on.

• The basic syntax (including the order of various The basic syntax (including the order of various clauses) is as follows:clauses) is as follows:

Page 48: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 48

SELECT Statement Syntax Overview SELECT Statement Syntax Overview Contd.Contd.

SELECT SELECT [DISTINCT | ALL] [TOP n [PERCENT][WITH TIES]] [DISTINCT | ALL] [TOP n [PERCENT][WITH TIES]] {* | select_list}{* | select_list}

[[INTO INTO {table_name} ]{table_name} ]

[[FROM FROM {table_name [alias] | view_name} {table_name [alias] | view_name}

[{table_name [alias] | view_name}]]... [{table_name [alias] | view_name}]]...

[[WHERE WHERE condition | condition | JOIN_typeJOIN_type table_name ON table_name ON (join_condition) ](join_condition) ]

[[GROUP BY GROUP BY condition_list]condition_list]

[[HAVING HAVING condition]condition]

[[ORDER BY ORDER BY {column_name | column_# [ ASC | DESC ] } {column_name | column_# [ ASC | DESC ] } ......

Page 49: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 49

SELECT Statement SyntaxSELECT Statement Syntax

• you will learn the various clauses you will learn the various clauses of the SELECT statement of the SELECT statement throughout your study of this throughout your study of this text.text.

• Welcome to the study of SQL!Welcome to the study of SQL!

Page 50: Prentice Hall © 20041 SQL for SQL Server Bijoy Bordoloi and Douglas Bock Chapter 1: Introduction

Prentice Hall © 2004 50

SUMMARYSUMMARY

This chapter:This chapter:• Introduced you to the basics of relational Introduced you to the basics of relational

database, DBMS, and SQL.database, DBMS, and SQL.• Familiarized you with the features of the SQL Familiarized you with the features of the SQL

Server DBMS including its GUI, the SQL Server DBMS including its GUI, the SQL Query Analyzer.Query Analyzer.

• Familiarized you with the basic relational Familiarized you with the basic relational operations including the selection, projection, operations including the selection, projection, and join operations.and join operations.

• Familiarize with the basic syntax of the Familiarize with the basic syntax of the SELECT statement.SELECT statement.