Sunteți pe pagina 1din 87

Introduction to SQL

By Mr. Mwegi

Introduction to SQL
The Structured Query Language (SQL) is used to interact with a database to access and edit data in it. SQL statements are divided, according to their nature, into three parts
Data Definition Language (DDL) and Data Manipulation Language(DML). Data control language (DCL)

To perform an operation, SQL requires only few lines of code compared to other languages. SQL statements include select which is used to access fields, tables and range of records in a database, inserts for adding new data, and deletes for removing data. When a query is processed the result will be returned in a RecordSet.

Data definition language


DDL (Data Definition Language) Data Definition Language is the language used to define the organization and storage of data. Some of the DDL statements are, CREATE TABLE Statement and DROP statement The Create Table statement is used for creating a table with the given table name and field types. Syntax CREATE TABLE tablename (field1 type [(size)] [NOT NULL] [index1] [, field2 type [(size)] [NOT NULL] [index2] [, ...]] [, CONSTRAINT constraintname [, ...]]) ;

Create table - example


Example Create table tblStudents (Student_id Varchar2(12) NOT NULL, Last_Name Varchar2(12) NULL, First_Name Varchar2(30) NOT NULL, SS_No Varchar2(12) NOT NULL );

SQL data types


The data type is used to specify information type (numeric, character, and so on) and how much space that information takes up in a particular column. You must choose your data types carefully, as they cannot be changed once a table has been created. To alter a column data type you must drop the table and recreate it. Some data types have a variable length, while others have a specific length. SQL Server data types can be broken down into the following groups: string, binary, integer, approximate and exact numeric, special, date and time, money, auto-incrementing data types, synonyms, and user-defined.

Sql server data types


Category String Binary

Datatype char(n), varchar binary(n),


varbinary int, smallint, tinyint

Integer Approximate Numeric Exact Numeric Special Date and Time Money Auto-incrementing Datatypes Synonyms User-defined

Comments Stores character strings. Stores binary information in two-byte pairs. Stores integer values. Stores approximate numeric information. Stores exact numeric information. Stores a single bit, character information greater than 255 bytes, or image data. Stores dates and times. Stores currency values. Stores values that are automatically incremented or set by the SQL Server. Maps ANSI datatypes to SQL Server datatypes. You can create your own datatypes to store information.

float, real decimal, numeric bit, text, image


datetime, smalldatetime money, smallmoney identity, timestamp

shown later shown later

Nullability
The nullability of a column refers to whether or not an entry is required for that column. If you would like to allow a column to be empty, then specify NULL. If you would like to insist that each row have an entry in that column, specify NOT NULL. If you do not specify NULL or NOT NULL, the system default will be used. When you first install SQL Server, the system default will be NOT NULL. As with most options things in SQL Server, this default can be modified.

Strings
Strings contain character data that is comprised of letters, numbers, and symbols. You can store character data in either a fixed-length or a variable-length format using the char(n) or varchar(n) keywords. You can store a maximum of 255 characters in these datatypes. When you create a fixed-length field, you are specifying that this field will always contain n bytes of information. If the data that you entered in the field is less than n, it will be padded with spaces so that it always takes up n bytes. If you try to put more than n bytes of data in the field, it will be truncated. Table 5.3 shows you some examples of entering data into a field declared as Fname char(*)

Creating tables- example


Here is an example of creating a table using the char and varchar keywords: CREATE TABLE tblCustomers
(CustID char(8) NOT NULL, CustName varchar(30) NOT NULL, Email varchar(50), )

Create table syntax


CREATE TABLE table_name ( column_name datatype [identity|constraint|NULL|NOT NULL] [...] ) Where: table_name is the name of the new table as follows the rules for identifiers. It must also be unique within the database for its owner. This means that if two users have permission to create tables within a database, the tables themselves may have the same name, but they will still be considered unique because the owner's name forms part of the table name. column_name is the column name and must follow the rules for identifiers.

Example 3
Here is a sample CREATE TABLE statement: CREATE TABLE employees (emp_id tinyint IDENTITY NOT NULL, Fname char(15),Lname char(20) NOT varchar(30),Address2 varchar(NULL,Address1 30),city varchar(30),state char(2),zipcode char(10),start_date datetime)

Deleting tables
Dropping Tables To drop a table using SQL, you should run the DROP TABLE statement. For example, to drop the tblEmployees table, you would run: DROP TABLE tblEmployees

Inserting Data into Tables


The basic INSERT statement adds one row to a table at a time. Variations of the basic INSERT statement allow you to add multiple rows by selecting data from another table or by executing a stored procedure. In any of these cases, you must know something about the structure of the table into which you are inserting. The following can be useful: The number of columns in the table The datatype of each column Knowledge of constraints and column properties, like identity Some INSERT statements require you to know the name of the columns

Syntax for inserting data into tables


INSERT [INTO] {table_name | view_name} [(column_list)] EXECute { procedure_name | @procedure_name_var} [[@parameter_name=] {value | @variable [OUTPUT] | DEFAULT} [, [@parameter_name =] {value | @variable [OUTPUT] | DEFAULT}]...] The simplest form of the INSERT statement requires a value for every column, in the order the columns were defined

Example on inserting data

insert into publishers values(`9956', `A New Publisher', `Poulsbo', `WA', `USA')

Guideline to using insert statement


In order for SQL Server to determine a value, every column not mentioned in the list of columns must meet one of the following criteria: The column has a default value attached to it. The column is an identity column. The column allows NULLs. The column is of type timestamp

DEFAULT VALUES
There is one more variation of the simple, single row INSERT statement, which is used when you don't want to include a list of column names, but do want SQL Server to use default values where they exist (this includes NULLs and identity values). You can use the keyword DEFAULT in the actual values list, as a way of telling SQL Server that it should determine what value should be used. For example: insert into publishers values(`9950', DEFAULT, DEFAULT,`AK', DEFAULT)

SQL QUERIES DATA RETRIEVAL


You can create queries to retrieve information from your database by using the SQL Query Tool in the Enterprise Manager, ISQL/w, ISQL, MSQuery, other tools, and third-party utilities. In this section, you will look at using the SELECT statement to retrieve rows and columns from tables in your database. The SELECT statement consists of three basic components: SELECT, FROM, and WHERE. The basic syntax follows:
SELECT column_list FROM table_list WHERE search_criteria

Complete select statement


The SELECT portion of the statement specifies the columns you want to retrieve. The FROM clause specifies the table(s) from which the columns are to be retrieved. The WHERE clause can be used to limit the amount of data returned by your query. The complete syntax for the SELECT statement follows: SELECT [ALL | DISTINCT] column_list[INTO [new_table_name]] [FROM {table_name | view_name}[(optimizer_hints)] [[, {table_name2 | view_name2}[(optimizer_hints)] [..., {table_name16 | view_name16}[(optimizer_hints)]]] [WHERE clause] [GROUP BY clause] [HAVING clause] [ORDER BY clause] [COMPUTE clause][FOR BROWSE]

Select statement - example


SELECT * FROM table_name is the most basic of all queries. When you use an asterisk (*) for column_list, it retrieves all columns from the table. In the pubs database, for example, you can run this query to select all columns and rows from the authors table: SELECT *FROM employee

Changing Column Headings


When the results of a query are displayed, the column headings are the names used in column_list. Instead of using column headings, such as lname and fname, you can produce more readable column headings, such as FirstName and LastName, by aliasing the column headings. You can alias column headings using SQL Server 2000 syntax or ANSI SQL syntax. You can alias columns with SQL Server syntax in two ways: SELECT column_heading = column_name FROM table_name OR SELECT column_name [AS] column_headingFROM table_name

Select , using alias names- example


SELECT emp_id AS EmployeeID, AS FirstName FROM employee lname AS LastName, fname

Both queries have the same result:


EmployeeID LastName ----------------PMA42628M Accorti PSA89086M Afonso VPA30890F Ashworth H-B39728F Bennett L-B31947F Brown F-C16315M Chang . . . . . . . . . . . . . . . GHT50241M Thomas DBT39435M Tonini (43 row(s) affected) FirstName --------Paolo Pedro Victoria Helen Lesley Francisco . . .

Gary Daniel

Manipulating Data
You can manipulate data in your query results to produce new columns that display computed values, new string values, converted dates, and more. Your query results can be manipulated using arithmetic operators, mathematical functions, string functions, datetime functions, and system functions. You also can use the CONVERT function to convert from one datatype to another for easier data manipulation. Arithmetic Operators You can use arithmetic operators on the following datatypes: int, smallint, tinyint, numeric, decimal, float, real, money, and smallmoney. Table 10.1 shows the arithmetic operators and the datatypes you can use with them.

Mathematical operators and data types


Addition Subtraction Division Mult. Modulo . Datatype + / * % Decimal Yes yes yes yes no Float Yes yes yes yes no Int Yes yes yes yes yes Money Yes yes yes yes no Numeric Yes yes yes yes no Real Yes yes yes yes no smallint Yes yes yes yes yes smallmoney Yes yes yes yes no Tinyint Yes yes yes yes yes

Mathematical operations
For example, Select 5 + 5 * 5 = 30 (The multiplication is done first.) but Select (5 + 5) * 5 = 50 (The nested expression is evaluated first.) Mathematical operations can also be performed on table columns as shown in the next example

Manipulation of data
Example Select unitprice*quantity as Total cost from products Select 0.25*quantity as 25% of quantity from products Select 0.85* unitprice as price reduced by 15% from products

VIEWING DATA IN THE TABLES


Once the data has been inserted, you must try and view the data to confirm that the insert operation was successful. Syntax for viewing records: SELECT <columname1>, <columnName2> <columnName n> FROM <tableName>;

Examples
Select productName, Supplier FROM products; Select ProductName TO DateofPurchase FROM products; SELECT * FROM products;

FILTERING TABLE DATA.


SQL provides the option of using a WHERE clause in a select query to apply a filter on the rows retrieved. When a where clause is added to an SQL query, the Oracle engine compares each record in the table with the condition specified in the where clause. Oracle displays only those records that satisfy the specified condition. Syntax SELECT * FROM <tableName> WHERE <condition>;

Example
To retrieve all product information from the products table where the ProductID is 1005247, we would use the following statement: SQL> SELECT * FROM products WHERE productID=1005247; The above select statement will select all columns BUT one row.

SELECTING PARTICULAR COLUMNS AND ROWS To view a specific set of rows and columns from a table, the syntax will be as follows SELECT <columnName1>, columnName2> FROM <tableName> WHERE <condition>;

Eliminating Duplicating Rows when using A SELECT statement


A table can hold duplicate rows, to view only distinct rows, the syntax is SELECT DISTINCT <columnName1>, <columnName2> FROM <tableName> WHERE <some condition is true> ; Example SELECT DISTINCT Supplier FROM products;

Sorting Data in a table.


The rows retrieved from a table can be sorted either in ascending or descending order depending on the condition specified in the select statement. Syntax SELECT * FROM <tableName> ORDER BY <columnName1>, <columnName2> <[sort Order]>;

Ordering Data
The sort order can either be ASC for ascending or DESC for descending. Example SELECT * FROM Products ORDER BY productId DESC; Example 2 SELECT EmpID, Firstname, Lastname FROM customers ORDER BY EmpID ASC;

DELETING DATA FROM TABLES


Delete statement can be used to remove either all rows from a table or just a set of rows from a table. Removing ALL rows DELETE FROM <tableName>; Example SQL> DELETE FROM Suppliers;

Delete with where .. clause


Delete operation is a very dangerous one and should be carried out with a lot of care after evaluating all the consequences of such an operation. Removing a set of Rows DELETE FROM <tableName> WHERE <condition>

Example - deletion
Will delete only those records that meet the specified condition or delete criteria. Example DELETE FROM Suppliers WHERE Town= Mombasa ;

UPDATING CONTENTS OF A TABLE


The UPDATE command is used to change or modify data values in a table. Updating ALL rows: Syntax UPDATE <tableName>
SET <columnName1> = <expression>, <ColumnName2> = <Expresson2>;

Update example
Example UPDATE Employees SET Sal = Sal + (Sal * 0.40); This example increases the salary of all employees by 40%

Updating records Conditionally: Syntax UPDATE <tableName>


SET <columnName> = <expression>, <ColumnName2> = <expression2> WHERE <condition>;

Example UPDATE Employees SET Comm = 3400 WHERE DeptID = 30;

EXPRESSIONS AND FUNCTIONS


Functions and expressions are used in performing calculations as well as logical operations on table data. SQL allows arithmetic operators to be used while viewing records from a table or while performing data manipulation operations such as INSERT, UPDATE and DELETE. Common Arithmetic Operators + Addition / Division - Subtraction ** Exponentiation * Multiplication () enclosed operation

Expressions
They are generally used to carry out simple arithmetic and logical operations. Example To retrieve productname, productID and compute 5% of the selling_price, we would use the following statement. SELECT productname, productID, selling_price*(5/100) as increment FROM Products;

Example -expressions
example 3 Select sal as "Old Salary",(sal*0.40) as "Increment(40%)", sal+(sal*0.40) as "New Pay" From Emp

LOGICAL OPERATORS
The AND Operator It instructs the sql engine to display the result only when all the conditions specified using the AND operator are satisfied. Example SELECT Ename, Sal, Job FROM Emp WHERE sal>1400 AND sal <2900;

The OR operator
Sql will process all rows in a table and display the result when one of the conditions specified in the OR operator are satisfied. Example SELECT * FROM Emp WHERE (Comm >0) OR (sal>3000);

The IN and NOT IN predicates


The NOT Operator The sql engine will process all rows in a table and display the result only when none of the conditions specified using the NOT operator is true. The IN and NOT IN predicates IN predicate compares a single value to a list of values. One can check a single value against multiple values by using the IN predicate.

Examples IN and NOT IN


SELECT Ename, Job, HireDate FROM Scott.Emp WHERE job IN( MANAGER , PRESIDENT ); The NOT IN Predicate selects all rows where values do not match all of the values in a list Example SELECT Ename, Job, Sal FROM Scott.Emp WHERE Job NOT IN ( SALESMAN );

Range Searching
The between operator is used to select data that is within a range of values. Example 1
SELECT * FROM products WHERE Unitprice BETWEEN 50 and 200;

Example 2 SELECT ename, job, deptno FROM EMP WHERE sal BETWEEN 1000 AND 2000;

Pattern Matching
The LIKE predicate allows for comparison of one string value with another string value which is not identical. This is achieved using wild-card characters. Two wild-card characters are available for this kind of operation. The percentage sign (%) matches any string The underscore (_) matches any single character

Example range searching


Example SELECT fname, Comm, hiredate From Emp WHERE ename LIKE S% ; Example 2
SELECT ename, job FROM Scott.Emp WHERE ename LIKE _M% ; This example selects records from the table EMP for employees having M as the second letter in their name

SQL FUNCTIONS
Functions are used in manipulating data items and returning a result. Functions are also capable of accepting user-supplied variables or constants and operating on them. Such variables or constants are called arguments. Any number of arguments can be passed to a function in the following format Function_name(argument1, argument2, )

Examples of sql functions


Function .
AVG([ALL | DISTINCT] column_name) COUNT(*) COUNT([ALL | DISTINCT] column_name) MAX(column_name) MIN(column_name) SUM([ALL | DISTINCT] column_name)

Results Average of the values in the numeric expression, either all or distinct Number of selected rows Number of values in the expression, either all or distinct Highest value in the expression Lowest value in the expression Total of the values in the numeric expression, either all or distinct

Classes of functions
Functions can be classified as follows
Group functions Scalar functions

Functions that act on a set of values are called group functions. An example is the SUM function which calculates the total set of numbers. A group function returns a single result row for a group of queried rows. Scalar functions act on only one value at a time. For example, LENGTH is a function that calculates the length of one particular string value. A single row function returns one result for every row of a queried table or view.

Scalar functions - examples


. Funct
n
LOWER(char_expr) LTRIM(char_expr) REPLICATE(char_expr, integer_expr) REVERSE(char_expr) RIGHT(char_expr, integer_expr) RTRIM(char_expr) SOUNDEX(char_expr) SPACE(integer_expr)

Result Converts to lowercase Returns data without leading blanks Repeats char_expr integer_expr number of times Returns the reverse of char_expr Returns the character string starting integer_expr characters from the right Returns data without trailing blanks Returns a four-digit (SOUNDEX) code to evaluate the similarity of two character strings Returns a string of repeated spaces equal to
integer_expr

SUBSTRING(expression, start, Returns part of a character or binary string length) UPPER(char_expr)

Converts to uppercase

Examples using scalar functions


. Statement

Result
71 abcde 2 CDE EDCBA

SELECT ASCII(`G') SELECT LOWER(`ABCDE') SELECT PATHINDEX(`%BC%','ABCDE') SELECT RIGHT(`ABCDE',3) SELECT REVERSE(`ABCDE')

Date functions
Function
DATEADD(datepart, . number, date) DATEDIFF(datepart, date1, date2) DATENAME(datepart, date)

DATEPART(datepart, date)

GETDATE ()

esults Adds the nu be o dateparts to the date Speci ies the nu be o datepart s bet een t o dates Retu ns the AS II value fo the specified datepart fo the date listed Retu ns an intege value fo the specified datepart fo the date listed Specifies the cu ent date and ti e in inte nal fo at

Examples date functions

Function
SELECT GETDATE() SELECT DATEADD(mm, 6, `1/1/97') SELECT DATEADD(mm -5, `10/6/97')

Results
Apr 29, 1997 2:10AM Jul 1, 1997 2:10AM May 6, 1997 2:10AM

SELECT DATEDIFF(mm, '1/1/97', '12/31/99') 35

COMPUTE AND COMPUTE BY clauses


The COMPUTE and COMPUTE BY clauses are used to produce new rows of summary and detail data. They use the aggregate functions specified earlier. The COMPUTE clause returns detail rows and a grand total summary row. The COMPUTE BY clause returns new rows of summary data, much like the GROUP BY clause, but it returns the rows as subgroups with summary values.

Example compute by
SELECT type, ytd_sales FROM titles ORDER BY type COMPUTE SUM(ytd_sales) BY type
SELECT type, ytd_sales FROM titles ORDER BY type COMPUTE SUM(ytd_sales)
type -----------business business business business sum ========= 30788 type -----------mod_cook mod_cook sum ========= 24278 type -----------popular_comp popular_comp popular_comp sum ========= 12875 type --------psychology psychology psychology psychology psychology

BY

type

ytd_sales ---------4095 3876 18722 4095

ytd_sales ---------2032 22246

ytd_sales ---------8780 4095 (null)

ytd_sales ---------375 2045 111 4072 3336

Aggregate functions
Here are a few examples using the aggregate functions. SELECT COUNT(*)FROM employees result----- 43(1 row(s) affected) ANALYSIS: This query returned a count of the total number of rows in table employee. SELECT MAX(ytd_sales)FROM titles result-----22246(1 row(s) affected)

Data integrity and Constraints


Data integrity refers to the consistency and accuracy of data that is stored within a database. Constraints are tools used to enforce integrity There are four types of data integrity, i.e.
Domain integrity Entity integrity Referential integrity User-defined integrity

Domain & entity integrity


The domain is simply the set of valid values for a particular column. Domain integrity ensures that the data values entered in a column are correct. Entity integrity ensures that every row in a table contains acceptable data. It places a check on the data that is entered in a row to ensure all columns contain correct data. Referential integrity is used to create relationships between two or more tables.

User-defined integrity
user-defined constraints are created by programmers to enforce certain business rules. For example, the rule that the lowest paid employee should earn Ksh. 4,600/= can be enforced by a user-defined constraint. Business rules that are enforced on data being stored are called constraints.

constraints
They are simply tools used in implementing integrity rules Examples of constraints are
Primary key constraint Composite key Foreign key Check constraint Unique constraint Default constraint

Primary key
A primary key is one or more columns in a table used to uniquely identify each row in the table. A primary key column has special attributes:
The column can not be left blank data held across the column must be UNIQUE. A multicolumn primary key is called a composite key.

Foreign key constraint


Establishes a relationship between record across a master table and a detail table. This relationship ensures the following:
That records cannot be inserted into a detail table if corresponding records do not exist in a master table. Records of the master table cannot be deleted if corresponding records in the detail table exist.

Defining primary key in a table


Primary key defined at column level CREATE TABLE ORDERS ( Orderno varchar(6) PRIMARY KEY, Client_no varchar(23) UNIQUE, Order_Date DATE, Order_status varchar(10) NOT NULL); Example 2 Primary key defined at table level CREATE TABLE Orders ( DetlOrderno varchar(6), Productno varchar(6), Product_rate decimal(8,2), PRIMARY KEY (DetlOrderno, Productno));

Defining foreign key columns


Syntax:
<columnName> <datatype> (<size>) REFERENCES <tablename> [(columnName)] [ON DELETE CASCADE] The parameters within the square brackets i.e. [<parameter>] are optional. Example CREATE TABLE students (RegNo varchar(12) PRIMARY KEY, Name varchar(20), Coursecode varchar(6) REFERENCES COURSES (CourseID) YearofStudy Varchar(10));

Foreign key at table level


Foreign key defined at Table level. Syntax: FOREIGN KEY (<column1>,[column2]) REFERENCES <tablename> [<columnName1>, <column2>] foreign key relates two tables, one refered to as the master table while the second is the details table

Example- foreign key at table level


Example CREATE TABLE EMPLOYEES ( Employeeid Number PRIMARY KEY, Firstname varchar(14), Lastname varchar2(15), Deptnumber Number(8), Pinumber number, DateofHire DATE, FOREIGN KEY (Deptnumber) REFERENCES Departments (deptno) ON DELETE CASCADE);

The UNIQUE constraint;


The UNIQUE constraint; This constraint ensures that a value entered in the column is UNIQUE(no repeating values allowed). A value entered in columns defined with the UNIQUE constraint must not be repeated across the columns. <columnName> <datatype> (<size>) UNIQUE, example

Example unique constraint


CREATE TABLE courses (courseID Number(6) PRIMARY KEY, CourseName varchar2(21) UNIQUE, Coursecode varchar2(24));
This example ensures that no two courses can have the same name.

THE CHECK CONSTRAINT


The check constraint enforces business rules. The constraint must be specified as a logical expression that evaluates either to true or false. Check constraint defined at column level <columName> <datatype> (size) CHECK (<logical expression>) Example CREATE TABLE Courses ( CourseID varchar2(10) CHECK ( courseID LIKE DIT% ), CourseName varchar2 (28), Department varchar2(20));

DEFAULT VALUE CONCEPT


At the time of table creation, a default value may be assigned to a column so that when a record is entered into the table and the column is left empty, the oracle engine will automatically load this column with the default value specified. The data type of the default value should match the data type of the column. The DEFAULT clause can be used to specify a default value for a column Syntax <columnName><datatype> (Size) DEFAULT (<value>);

Default constraint example


Example CREATE TABLE STUDENTS (RegNo VARCHAR(12), Coursename varchar2(22), Fees number(7,2) DEFAULT 29000); This example gives a default value of 29000 for the cost column of the students table

Using ALTER TABLE commmand


This command can be used to add constraints to a table after it has been created. Syntax Alter table <tablename> Add constraint Example 1: To add a primary key constraint on the productno field ALTER TABLE products ADD PRIMARY KEY(productno);

Alter table example 2


Example 2: To add a foreign key constraint called Order_key on the Order_no column of the table of orders that references the primary field of the sales_orders table. ALTER TABLE Orders ADD CONSTRAINT Order_key FOREIGN KEY(Order_no) REFERENCES Sales_orders;

DROPPING CONSTRAINTS
A constraint can be eliminated or removed using the DROP CONSTRAINT statement. Example 1 ALTER TABLE Products DROP PRIMARY KEY; ALTER TABLE Orders DROP CONSTRAINT Order_key; A constraint can either be dropped by referring to it using its name or by using its type.

TABLE JOINS
Sometimes it is necessary to work with multiple tables as though they were a single entity. A single SQL statement can then manipulate data from all tables. Joins are used to achieve this. Tables are joined on columns that have the same data type and data width. Joins enable retrieving data from two tables using a single SQL construct

Joins - example
We can join the two tables emp and dept on the common field deptno using the following SQL statements. SELECT ename, job, sal, dname, loc FROM emp, dept WHERE emp.deptno =dept.deptno ORDER BY sal DESC;

Types of joins
There are three types of table joins
Inner joins Cross joins Outer joins Outer joins are further divided into three groups Left outer join Right outer join Full outer join

Inner joins
Inner joins produce information where matching information is found in both tables. The most common types of inner joins are equijoins and natural joins. Example SELECT * FROM publishers inner join pub_info On publishers.pub_id = pub_info.pub_id
The two tables joined are publishers and pub_info

Cross joins
Cross or unrestricted joins return a combination of all rows of all tables in the join as the result set. A cross or unrestricted join is created not by using the WHERE clause in SQL Server. Example SELECT titles.title, titleauthor.au_id FROM titles CROSS JOIN titleauthor

Outer joins
LEFT OUTER JOIN
Includes all rows from the first table and only the matching rows in the second table.

RIGHT OUTER JOIN


Includes all rows from the second table and only the matching rows in the first table.

FULL OUTER JOIN


Includes all non-matching rows from both tables.

Example outer joins


SELECT titles.title_id, titles.title, sales.qty FROM titles LEFT OUTER JOIN sales ON titles.title_id = sales.title_id The same example can be written using right and full outer joins. E.g. SELECT titles.title_id, titles.title, sales.qty FROM titles RIGHT OUTER JOIN sales ON titles.title_id = sales.title_id

THE END

ASSIGNMENT
.

S-ar putea să vă placă și