SQL LEC8 Indexes The CREATE INDEX statement is

  • Slides: 83
Download presentation
SQL LEC-8

SQL LEC-8

Indexes • The CREATE INDEX statement is used to create indexes • • in

Indexes • The CREATE INDEX statement is used to create indexes • • in tables. Indexes allow the database application to find data fast; without reading the whole table. An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.

 • SQL CREATE INDEX Syntax • Creates an index on a table. Duplicate

• SQL CREATE INDEX Syntax • Creates an index on a table. Duplicate values are • • allowed: CREATE INDEX index_name ON table_name (column_name) SQL CREATE UNIQUE INDEX Syntax Creates a unique index on a table. Duplicate values are not allowed: CREATE UNIQUE INDEX index_name ON table_name (column_name)

 • The syntax for creating indexes varies amongst different • • • databases.

• The syntax for creating indexes varies amongst different • • • databases. Therefore: Check the syntax for creating indexes in your database. CREATE INDEX Example The SQL statement below creates an index named "PIndex" on the "Last. Name" column in the "Persons" table: CREATE INDEX PIndex ON Persons (Last. Name) If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas: CREATE INDEX PIndex ON Persons (Last. Name, First. Name)

 • Indexes, tables, and databases can easily be • • • deleted/removed with

• Indexes, tables, and databases can easily be • • • deleted/removed with the DROP statement. The DROP INDEX Statement The DROP INDEX statement is used to delete an index in a table. DROP INDEX Syntax for MS Access: DROP INDEX index_name ON table_name DROP INDEX Syntax for MS SQL Server: DROP INDEX table_name. index_name DROP INDEX Syntax for DB 2/Oracle: DROP INDEX index_name DROP INDEX Syntax for My. SQL: ALTER TABLE table_name DROP INDEX index_name

The DROP TABLE Statement • The DROP TABLE statement is used to delete a

The DROP TABLE Statement • The DROP TABLE statement is used to delete a table. • DROP TABLE table_name The DROP DATABASE Statement • The DROP DATABASE statement is used to delete a database. DROP DATABASE database_name The TRUNCATE TABLE Statement • What if we only want to delete the data inside the table, and not the table itself? • Then, use the TRUNCATE TABLE statement: • TRUNCATE TABLE table_name

 • The ALTER TABLE Statement • The ALTER TABLE statement is used to

• The ALTER TABLE Statement • The ALTER TABLE statement is used to add, delete, or modify • • columns in an existing table. SQL ALTER TABLE Syntax To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): ALTER TABLE table_name DROP COLUMN column_name To change the data type of a column in a table, use the following syntax: SQL Server / MS Access:

 • ALTER TABLE table_name • • ALTER COLUMN column_name datatype My SQL /

• ALTER TABLE table_name • • ALTER COLUMN column_name datatype My SQL / Oracle: ALTER TABLE table_name MODIFY COLUMN column_name datatype Oracle 10 G and later: ALTER TABLE table_name MODIFY column_name datatype SQL ALTER TABLE Example: "Persons" table:

 • Now we want to add a column named "Date. Of. Birth" in

• Now we want to add a column named "Date. Of. Birth" in • • the "Persons" table. We use the following SQL statement: ALTER TABLE Persons ADD Date. Of. Birth date Notice that the new column, "Date. Of. Birth", is of type date and is going to hold a date. The data type specifies what type of data the column can hold. The "Persons" table will now like this:

 • Change Data Type Example • Now we want to change the data

• Change Data Type Example • Now we want to change the data type of the column named "Date. Of. Birth" in the "Persons" table. • We use the following SQL statement: • ALTER TABLE Persons ALTER COLUMN Date. Of. Birth year • "Date. Of. Birth" column is now of type year and is going to hold a year in a two-digit or four-digit format.

 • DROP COLUMN Example • Next, we want to delete the column named

• DROP COLUMN Example • Next, we want to delete the column named "Date. Of. Birth" in the "Persons" table. • We use the following SQL statement: • ALTER TABLE Persons DROP COLUMN Date. Of. Birth • The "Persons" table will now like this:

 • Auto-increment allows a unique number to be • • • generated when

• Auto-increment allows a unique number to be • • • generated when a new record is inserted into a table. AUTO INCREMENT a Field Very often we would like the value of the primary key field to be created automatically every time a new record is inserted. We would like to create an auto-increment field in a table. Syntax for My. SQL The following SQL statement defines the "ID" column to be an auto-increment primary key field in the "Persons" table:

 CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT, Last. Name varchar(255) NOT

CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT, Last. Name varchar(255) NOT NULL, First. Name varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (ID) )

 • My. SQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. •

• My. SQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. • By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. • To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: • ALTER TABLE Persons AUTO_INCREMENT=100

 • To insert a new record into the "Persons" table, we will NOT

• To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically): • INSERT INTO Persons (First. Name, Last. Name) VALUES ('Lars', 'Monsen') • The SQL statement above would insert a new record into the "Persons" table. The "ID" column would be assigned a unique value. The "First. Name" column would be set to "Lars" and the "Last. Name" column would be set to "Monsen".

 • Syntax for SQL Server • The following SQL statement defines the "ID"

• Syntax for SQL Server • The following SQL statement defines the "ID" column to be an auto-increment primary key field in the "Persons" table: • CREATE TABLE Persons ( ID int IDENTITY(1, 1) PRIMARY KEY, Last. Name varchar(255) NOT NULL, First. Name varchar(255), Address varchar(255), City varchar(255) )

 • The MS SQL Server uses the IDENTITY keyword to perform an auto-increment

• The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. • In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. • To specify that the "ID" column should start at value 10 and increment by 5, change it to IDENTITY(10, 5). • To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):

 • INSERT INTO Persons (First. Name, Last. Name) VALUES ('Lars', 'Monsen') • The

• INSERT INTO Persons (First. Name, Last. Name) VALUES ('Lars', 'Monsen') • The SQL statement above would insert a new record into the "Persons" table. The "ID" column would be assigned a unique value. The "First. Name" column would be set to "Lars" and the "Last. Name" column would be set to "Monsen". • Syntax for Access • The following SQL statement defines the "ID" column to be an auto-increment primary key field in the "Persons" table:

 CREATE TABLE Persons ( ID Integer PRIMARY KEY AUTOINCREMENT, Last. Name varchar(255) NOT

CREATE TABLE Persons ( ID Integer PRIMARY KEY AUTOINCREMENT, Last. Name varchar(255) NOT NULL, First. Name varchar(255), Address varchar(255), City varchar(255) )

 • The By default, the starting value for AUTOINCREMENT is 1, and it

• The By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new record. • To specify that the "ID" column should start at value 10 and increment by 5, change the autoincrement to AUTOINCREMENT(10, 5). • To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically): • INSERT INTO Persons (First. Name, Last. Name) VALUES ('Lars', 'Monsen')

 • The SQL statement above would insert a new record • • into

• The SQL statement above would insert a new record • • into the "Persons" table. The "P_Id" column would be assigned a unique value. The "First. Name" column would be set to "Lars" and the "Last. Name" column would be set to "Monsen". Syntax for Oracle In Oracle the code is a little bit more tricky. You will have to create an auto-increment field with the sequence object (this object generates a number sequence). Use the following CREATE SEQUENCE syntax:

 • CREATE SEQUENCE seq_person MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE

• CREATE SEQUENCE seq_person MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10 • The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.

 • To insert a new record into the "Persons" table, we will have

• To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence): • INSERT INTO Persons (ID, First. Name, Last. Name) VALUES (seq_person. nextval, 'Lars', 'Monsen') • The SQL statement above would insert a new record into the "Persons" table. The "ID" column would be assigned the next number from the seq_person sequence. The "First. Name" column would be set to "Lars" and the "Last. Name" column would be set to "Monsen". • MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature.

 • NULL values represent missing unknown data. • By default, a table column

• NULL values represent missing unknown data. • By default, a table column can hold NULL values. • SQL NULL Values • If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.

 • NULL values are treated differently from other values. • NULL is used

• NULL values are treated differently from other values. • NULL is used as a placeholder for unknown or inapplicable values. • It is not possible to compare NULL and 0; they are not equivalent. SQL Working with NULL Values • Look at the following "Persons" table:

 • Suppose that the "Address" column in the "Persons" table is optional. This

• Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a record with no value for the "Address" column, the "Address" column will be saved with a NULL value. • How can we test for NULL values? • It is not possible to test for NULL values with comparison operators, such as =, <, or <>. • We will have to use the IS NULL and IS NOT NULL operators instead.

 • SQL IS NULL • How do we select only the records with

• SQL IS NULL • How do we select only the records with NULL values in the "Address" column? • We will have to use the IS NULL operator: • SELECT Last. Name, First. Name, Address FROM Persons WHERE Address IS NULL • The result-set will look like this:

 • Always use IS NULL to look for NULL values. • • SQL

• Always use IS NULL to look for NULL values. • • SQL IS NOT NULL How do we select only the records with no NULL values in the "Address" column? We will have to use the IS NOT NULL operator: SELECT Last. Name, First. Name, Address FROM Persons WHERE Address IS NOT NULL The result-set will look like this:

 • SQL ISNULL(), NVL(), IFNULL() and COALESCE() • • • Functions Look at

• SQL ISNULL(), NVL(), IFNULL() and COALESCE() • • • Functions Look at the following "Products" table: Suppose that the "Units. On. Order" column is optional, and may contain NULL values. We have the following SELECT statement: SELECT Product. Name, Unit. Price*(Units. In. Stock+Units. On. Order ) FROM Products In the example above, if any of the "Units. On. Order" values are NULL, the result is NULL.

 • Microsoft's ISNULL() function is used to specify how we want to treat

• Microsoft's ISNULL() function is used to specify how we want to treat NULL values. • The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result. • In this case we want NULL values to be zero. • Below, if "Units. On. Order" is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is NULL:

 • SQL Server / MS Access • SELECT Product. Name, Unit. Price*(Units. In.

• SQL Server / MS Access • SELECT Product. Name, Unit. Price*(Units. In. Stock+ISNULL(Units. On Order, 0)) FROM Products • Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result: • SELECT Product. Name, Unit. Price*(Units. In. Stock+NVL(Units. On. Ord er, 0)) FROM Products

 • My. SQL does have an ISNULL() function. However, it • • works

• My. SQL does have an ISNULL() function. However, it • • works a little bit different from Microsoft's ISNULL() function. In My. SQL we can use the IFNULL() function, like this: SELECT Product. Name, Unit. Price*(Units. In. Stock+IFNULL(Units. On Order, 0)) FROM Products or we can use the COALESCE() function, like this: SELECT Product. Name, Unit. Price*(Units. In. Stock+COALESCE(Units On. Order, 0)) FROM Products

Sql JOIN • SQL Joins are used to relate information in different tables. A

Sql JOIN • SQL Joins are used to relate information in different tables. A Join condition is a part of the sql query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL WHERE Clause of select, update, delete statements. • The Syntax for joining two tables is: • SELECT col 1, col 2, col 3. . . FROM table_name 1, table_name 2 WHERE table_name 1. col 2 = table_name 2. col 1;

 • Different SQL JOINs • Before we continue with examples, we will list

• Different SQL JOINs • Before we continue with examples, we will list the • • types the different SQL JOINs you can use: INNER JOIN: Returns all rows when there is at least one match in BOTH tables LEFT JOIN: Return all rows from the left table, and the matched rows from the right table RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table FULL JOIN: Return all rows when there is a match in ONE of the tables

 OUTER JOIN There are three different Outer Join methods. 1. left outer join

OUTER JOIN There are three different Outer Join methods. 1. left outer join 2. right outer join 3. outer join

 • If a sql join condition is omitted or if it is invalid

• If a sql join condition is omitted or if it is invalid the join operation will result in a Cartesian product. The Cartesian product returns a number of rows equal to the product of all rows in all the tables being joined. For example, if the first table has 20 rows and the second table has 10 rows, the result will be 20 * 10, or 200 rows. This query takes a long time to execute. • Lets use the below two tables to explain the sql join conditions. • database table "product";

 • SQL Joins can be classified into Equi join and Non • •

• SQL Joins can be classified into Equi join and Non • • • Equi join. 1) SQL Equi joins It is a simple sql join condition which uses the equal sign as the comparison operator. Two types of equi joins are SQL Outer join and SQL Inner join. For example: You can get the information about a customer who purchased a product and the quantity of product. 2) SQL Non equi joins It is a sql join condition which makes use of some comparison operator other than the equal sign like >, <,

 • 1) SQL Equi Joins: • An equi-join is further classified into two

• 1) SQL Equi Joins: • An equi-join is further classified into two categories: a) SQL Inner Join b) SQL Outer Join • a) SQL Inner Join: • All the rows returned by the sql query satisfy the sql join condition specified

 • b) SQL Outer Join: • This sql join condition returns all rows

• b) SQL Outer Join: • This sql join condition returns all rows from both tables which satisfy the join condition along with rows which do not satisfy the join condition from one of the tables. The sql outer join operator in Oracle is ( + ) and is used on one side of the join condition only. • The syntax differs for different RDBMS implementation. Few of them represent the join conditions as "sql left outer join", "sql right outer join".

 • If you want to display all the product data along with order

• If you want to display all the product data along with order items data, with null values displayed for order items if a product has no order item, the sql query for outer join would be as shown below: • SELECT p. product_id, p. product_name, o. order_id, o. total_units FROM order_items o, product p WHERE o. product_id (+) = p. product_id; • The output would be like,

 • NOTE: If the (+) operator is used in the left side of

• NOTE: If the (+) operator is used in the left side of the join • • condition it is equivalent to left outer join. If used on the right side of the join condition it is equivalent to right outer join. SQL Self Join: A Self Join is a type of sql join which is used to join a table to itself, particularly when the table has a FOREIGN KEY that references its own PRIMARY KEY. It is necessary to ensure that the join statement defines an alias for both copies of the table to avoid column ambiguity. The below query is an example of a self join, SELECT a. sales_person_id, a. name, a. manager_id, b. sales_person_id, b. name FROM sales_person a, sales_person b WHERE a. manager_id = b. sales_person_id;

 • 2) SQL Non Equi Join: • A Non Equi Join is a

• 2) SQL Non Equi Join: • A Non Equi Join is a SQL Join whose condition is established using all comparison operators except the equal (=) operator. Like >=, <, > • For example: If you want to find the names of students who are not studying either Economics, the sql query would be like, (lets use student_details table defined earlier. ) • SELECT first_name, last_name, subject FROM student_details WHERE subject != 'Economics' • The output would be something like,

 • An SQL JOIN clause is used to combine rows from two or

• An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. • The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met. • Let's look at a selection from the "Orders" table:

 Then, have a look at a selection from the "Customers" table: Notice that

Then, have a look at a selection from the "Customers" table: Notice that the "Customer. ID" column in the "Orders" table refers to the customer in the "Customers" table. The relationship between the two tables above is the "Customer. ID" column.

 • Then, if we run the following SQL statement (that contains an INNER

• Then, if we run the following SQL statement (that contains an INNER JOIN): • Example • SELECT Orders. Order. ID, Customers. Customer. Name, Orders. Order. Date FROM Orders INNER JOIN Customers ON Orders. Customer. ID=Customers. Customer. ID; • it will produce something like this:

 • SQL INNER JOIN Keyword • The INNER JOIN keyword selects all rows

• SQL INNER JOIN Keyword • The INNER JOIN keyword selects all rows from both tables as • • • long as there is a match between the columns in both tables. SQL INNER JOIN Syntax SELECT column_name(s) FROM table 1 INNER JOIN table 2 ON table 1. column_name=table 2. column_name; or: SELECT column_name(s) FROM table 1 JOIN table 2 ON table 1. column_name=table 2. column_name; INNER JOIN is the same as JOIN.

Customer tbl

Customer tbl

Order tbl

Order tbl

 • SQL INNER JOIN Example • The following SQL statement will return all

• SQL INNER JOIN Example • The following SQL statement will return all customers with orders: • Example • SELECT Customers. Customer. Name, Orders. Order. ID FROM Customers INNER JOIN Orders ON Customers. Customer. ID=Orders. Customer. ID ORDER BY Customers. Customer. Name; • Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are rows in the "Customers" table that do not have matches in "Orders", these customers will NOT be listed.

 • SQL LEFT JOIN Keyword • The LEFT JOIN keyword returns all rows

• SQL LEFT JOIN Keyword • The LEFT JOIN keyword returns all rows from the left table • • • (table 1), with the matching rows in the right table (table 2). The result is NULL in the right side when there is no match. SQL LEFT JOIN Syntax SELECT column_name(s) FROM table 1 LEFT JOIN table 2 ON table 1. column_name=table 2. column_name; or: SELECT column_name(s) FROM table 1 LEFT OUTER JOIN table 2 ON table 1. column_name=table 2. column_name; In some databases LEFT JOIN is called LEFT OUTER JOIN.

Customer tbl

Customer tbl

Order tbl

Order tbl

 • SQL LEFT JOIN Example • The following SQL statement will return all

• SQL LEFT JOIN Example • The following SQL statement will return all customers, and any orders they might have: • Example • SELECT Customers. Customer. Name, Orders. Order. ID FROM Customers LEFT JOIN Orders ON Customers. Customer. ID=Orders. Customer. ID ORDER BY Customers. Customer. Name; • The LEFT JOIN keyword returns all the rows from the left table (Customers), even if there are no matches in the right table (Orders).

 • SQL RIGHT JOIN Keyword • The RIGHT JOIN keyword returns all rows

• SQL RIGHT JOIN Keyword • The RIGHT JOIN keyword returns all rows from the right table • • • (table 2), with the matching rows in the left table (table 1). The result is NULL in the left side when there is no match. SQL RIGHT JOIN Syntax SELECT column_name(s) FROM table 1 RIGHT JOIN table 2 ON table 1. column_name=table 2. column_name; or: SELECT column_name(s) FROM table 1 RIGHT OUTER JOIN table 2 ON table 1. column_name=table 2. column_name; In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Order tbl

Order tbl

Employee tbl

Employee tbl

 • SQL RIGHT JOIN Example • The following SQL statement will return all

• SQL RIGHT JOIN Example • The following SQL statement will return all employees, and any orders they have placed: • Example • SELECT Orders. Order. ID, Employees. First. Name FROM Orders RIGHT JOIN Employees ON Orders. Employee. ID=Employees. Employee. ID ORDER BY Orders. Order. ID; • The RIGHT JOIN keyword returns all the rows from the right table (Employees), even if there are no matches in the left table (Orders).

 • SQL FULL OUTER JOIN Keyword • The FULL OUTER JOIN keyword returns

• SQL FULL OUTER JOIN Keyword • The FULL OUTER JOIN keyword returns all rows from the left table (table 1) and from the right table (table 2). • The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins. • SQL FULL OUTER JOIN Syntax • SELECT column_name(s) FROM table 1 FULL OUTER JOIN table 2 ON table 1. column_name=table 2. column_name;

Customer tbl

Customer tbl

Order tbl

Order tbl

 • SQL FULL OUTER JOIN Example • The following SQL statement selects all

• SQL FULL OUTER JOIN Example • The following SQL statement selects all customers, and all orders: • SELECT Customers. Customer. Name, Orders. Order. ID FROM Customers FULL OUTER JOIN Orders ON Customers. Customer. ID=Orders. Customer. ID ORDER BY Customers. Customer. Name; • A selection from the result set may look like this:

 The FULL OUTER JOIN keyword returns all the rows from the left table

The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and all the rows from the right table (Orders). If there are rows in "Customers" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will be listed as well.