F - DataBase Chapter 7
F - DataBase Chapter 7
History:
1970 -- Dr. E. F. "Ted" of IBM is known as the father of relational databases. He described a
relational model for databases.
1974 -- Structured Query Language appeared.
1978 -- IBM worked to develop Codd's ideas and released a product named System/R.
1986 -- IBM developed the first prototype of relational database and standardized by ANSI. The
first relational database was released by Relational Software and its later becoming Oracle.
Characteristics of SQL
It is very easy to learn and use.
Large volume of databases can be handled quite easily.
Note: - SQL can be linked to most of other high level languages that makes it first choice for the
database programmers.
SQL Process:
When you are executing an SQL command for any RDBMS, the system determines the best way to
carry out your request and SQL engine figures out how to interpret the task.
There are various components included in the process. These components are Query Dispatcher,
Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine
handles all non-SQL queries, but SQL query engine won't handle logical files.
7.2. SQL Data Types
A data type defines what kind of value a column can hold: integer data, character data,
monetary data, date and time data, binary strings, and so on.
1
Number Description Storage
data types:
Chapter 7
Data type
Fundamentals of database system GTC 2014 E.C
bit Integer that can be 0, 1, or NULL
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8 bytes
The n parameter indicates whether the field should hold 4 or 8 bytes. float(24)
holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is
53.
Each column in a database table is required to have a name and a data type.
An SQL developer must decide what type of data that will be stored inside each column when
creating a table. The data type is a guideline for SQL to understand what type of data is expected
inside of each column, and it also identifies how SQL will interact with the stored data.
varchar(n) Variable width character string 8,000 characters 2 bytes + number of chars
varchar(max) Variable width character string 1,073,741,824 characters 2 bytes + number of chars
Text Variable width character string 2GB of text data 4 bytes + number of chars
Date data types:
SQL Server comes with the following data types for storing a date or a date/time value in the
database:
Note: The date types are chosen for a column when you create a new table in your database
2
Chapter 7 Fundamentals of database system GTC 2014 E.C
SQL Command
The standard SQL commands to interact with relational database are CREATE,INSERT,
UPDATE,DELETE, and DROP.
These commands can be classified into groups based on their nature:
DDL -Data Definition Language:
Create: - Creates a new table, a view of a table, or other object in database
Alter: - Modifies an existing database object, such as a table
Drop:-Deletes an entire table, a view of a table or other object in the database
DML -Data Manipulation Language
Insert:-Creates a record
Update :- Modifies records
Delete :- Deletes records
Syntax
CREATE DATABASE databasename;
CREATE DATABASE Example
Example
CREATE DATABASE testDB
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
)
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer,
date, etc.).
The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:
4
Chapter 7 Fundamentals of database system GTC 2014 E.C
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)Try it Yourself »
Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.
Syntax
DROP DATABASE databasename;
Note: Be careful before dropping a database. Deleting a database will result in loss of complete
information stored in the database!
Example
DROP DATABASE testDB;
Tip: Make sure you have admin privilege before dropping any database. Once a database is dropped, you
can check it in the list of databases with the following SQL command: SHOW DATABASES;
5
Chapter 7 Fundamentals of database system GTC 2014 E.C
Syntax:
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete information
stored in the table!
Example
DROP TABLE Shippers;
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.
Example
ALTER TABLE Customers
ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column)
The following SQL deletes the "Email" column from the "Customers" table:
Example
6
Chapter 7 Fundamentals of database system GTC 2014 E.C
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The
data type specifies what type of data the column can hold.
Change Data Type Example
Now we want to change the data type of the column named "DateOfBirth" in the "Persons"
table.
We use the following SQL statement:
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-
or four-digit format.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
7
Chapter 7 Fundamentals of database system GTC 2014 E.C
The first way specifies both the column names and the values to be inserted:
If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as
the columns in the table. The INSERT INTO syntax would be as follows:
The following SQL statement inserts a new record in the "Customers" table:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway')
Insert Data Only in Specified Columns
Comments are used to explain sections of SQL statements, or to prevent execution of SQL
statements.
Note: The examples in this chapter will not work in Firefox and Microsoft Edge!
Comments are not supported in Microsoft Access databases. Firefox and Microsoft Edge are
using Microsoft Access database in our examples.
Example
8
Chapter 7 Fundamentals of database system GTC 2014 E.C
--Select all:
SELECT * FROM Customers;
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
Example
--SELECT * FROM Customers;
SELECT * FROM Products;
Multi-line Comments
Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Example
9
Chapter 7 Fundamentals of database system GTC 2014 E.C
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
)
UNIQUE: - Constraint: Ensures that all values in a column are different.
A unique constraint (also referred to as a unique key constraint) is a rule that forbids
duplicate values in one or more columns within a table. Unique and primary keys are
the supported unique constraints. For example, a unique constraint can be defined on
the supplier identifier in the supplier table to ensure that the same supplier identifier is
not given to two suppliers.
For example, the following SQL creates a new table called CUSTOMERS and adds five columns,
Name column is set to UNIQUE and not null, so that you can not have two records with same name and
specify not to accept NULLs,
add a CHECK with AGE column, so that you cannot have any CUSTOMER below 18 years:
Address column is set to „DM‟ by default, Then by default this column would be set to „DM‟
What are the differences between an Unique constraint and a Primary Key?
The difference between a UNIQUE constraint and a Primary Key is that per table you may only
have one Primary Key but you may define more than one UNIQUE constraint.
Primary Key constraints are not null able.
Both PRIMARY KEY and UNIQUE KEY enforces the Uniqueness of the values (i.e. avoids
duplicate values) on the column[s] on which it is defined.
Primary Key constraints are not nullable. UNIQUE constraints may be nullable.
When you create a UNIQUE constraint, the database automatically creates a UNIQUE index. For MS
SQL Server databases, a PRIMARY KEY will generate a unique CLUSTERED INDEX. A UNIQUE
constraint will generate a unique NON-CLUSTERED INDEX.
11
Chapter 7 Fundamentals of database system GTC 2014 E.C
Primary Key
Foreign key is a field in the table that is primary key in another table.
Foreign key can accept multiple null value.
Foreign key do not automatically create an index, clustered or non-clustered. You can manually
create an index on foreign key.
We can have more than one foreign key in a table.
There are actual advantages to having a foreign key be supported with a clustered index, but you
get only one per table. What's the advantage? If you are selecting the parent plus all child records,
you want the child records next to each other. This is easy to accomplish using a clustered index.
Having a null foreign key is usually a bad idea. In the example below, the record in [dbo].[child]
is what would be referred to as an "orphan record". Think long and
Data Integrity
The following categories of the data integrity exist with each RDBMS:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the type, the format, or the
range of values.
Referential Integrity: Rows cannot be deleted which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall into entity, domain, or
referential integrity.
12
Chapter 7 Fundamentals of database system GTC 2014 E.C
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to
select all the fields available in the table, use the following syntax:
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
Example
SELECT CustomerName, City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers
The SQL SELECT INTO Statement
The SELECT INTO statement copies data from one table into a new table.
The new table will be created with the column-names and types as defined in the old table.
You can create new column names using the AS clause.
13
Chapter 7 Fundamentals of database system GTC 2014 E.C
WHERE Syntax
SELECT column1, column2, ..
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE
statement, etc.!
The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Text Fields vs. Numeric Fields
SQL requires single quotes around text values (most database systems will also allow double
quotes).
However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Operators in the WHERE Clause
The following operators can be used in the WHERE clause:
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
14
Chapter 7 Fundamentals of database system GTC 2014 E.C
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE
statement. The WHERE clause specifies which record(s) that should be updated. If you omit the
WHERE clause, all records in the table will be updated!
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person anda new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Multiple Records
It is the WHERE clause that determines how many records that will be updated.
The following SQL statement will update the contactname to "Juan" for all records where
country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
15
Chapter 7 Fundamentals of database system GTC 2014 E.C
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example
UPDATE Customers
SET ContactName='Juan'
The SQL DELETE Statement
DELETE Syntax
DELETE FROM table_name
WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all
records in the table will be deleted!
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste'
Delete All Records
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:
Example
DELETE FROM Customers;
AUTO INCREMENT Field
16
Chapter 7 Fundamentals of database system GTC 2014 E.C
Often this is the primary key field that we would like to be created automatically every time a
new record is inserted.
The following SQL statement defines the "ID" column to be an auto-increment primary key
field in the "Persons" table:
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.
Tip: 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):
The SQL statement above would insert a new record into the "Persons" table. The "ID" column
would be assigned a unique value. The "FirstName" column would be set to "Lars" and the
"LastName" column would be set to "Monsen".
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to
list the different (distinct) values.
The following SQL statement selects all (and duplicate) values from the "Country" column in
the "Customers" table:
17
Chapter 7 Fundamentals of database system GTC 2014 E.C
Example
SELECT Country FROM Customers;
Now, let us use the DISTINCT keyword with the above SELECT statement and see the result.
The following SQL statement selects only the DISTINCT values from the "Country" column in
the "Customers" table:
Example
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
Try it YORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
SQL GROUP BY Examples
The following SQL statement lists the number of customers in each country:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The following SQL statement lists the number of customers in each country, sorted high to low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESCTry it Yourself »
The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
SQL HAVING Examples
19
Chapter 7 Fundamentals of database system GTC 2014 E.C
The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
The following SQL statement lists the number of customers in each country, sorted high to low
(Only include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
SQL Wildcard Characters
There are two wildcards used in conjunction with the LIKE operator:
Note: MS Access uses a question mark (?) instead of the underscore (_).
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
20
Chapter 7 Fundamentals of database system GTC 2014 E.C
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
The following SQL statement selects all customers with a City starting with "ber":
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the pattern "es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
Using the _ Wildcard
The following SQL statement selects all customers with a City starting with any character,
followed by "erlin":
Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';
The following SQL statement selects all customers with a City starting with "L", followed by
any character, followed by "n", followed by any character, followed by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
Using the [charlist] Wildcard
The following SQL statement selects all customers with a City starting with "b", "s", or "p":
Example
21
Chapter 7 Fundamentals of database system GTC 2014 E.C
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
Using the [!charlist] Wildcard
The two following SQL statements select all customers with a City NOT starting with "b", "s",
or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';T
Or:
Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
The SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large
number of records can impact on performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause
to select a limited number of records, while Oracle uses ROWNUM.
The following SQL statement selects the first 50% of the records from the "Customers" table:
Example
SELECT TOP 50 PERCENT * FROM Customers;
22
Chapter 7 Fundamentals of database system GTC 2014 E.C
Aggregation function
TSQL Functions
Function is a database object in Sql Server. Basically it is a set of sql statements that accepts
only input parameters, perform actions and return the result. Function can return only
single value or a table. We can't use function to Insert, Update, and Delete records in
the database table
Aggregate function
★ Aggregate functions help to summarize the large volumes of data.
★This function can produced a single value for an entire group or table.
★They operate on sets of rows and return results based on groups of rows.
Aggregate Functions
The COUNT() function returns the number of rows that matches a specified criteria.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.
COUNT() function
The SQL COUNT function returns the number of rows in a table satisfying the criteria
specified in the WHERE clause. It sets on the number of rows or non NULL column values.
SQL Syntax : COUNT(*) OR
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Example : SELECT
COUNT(DISTINCT dname)
FROM department
AVG() function
The SQL AVG function calculates the average value of a column of numeric type.
It returns the average of all not NULL values.
SQL Syntax : AVG ([ALL | DISTINCT] expression )
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition
Example: AVG()
SUM() function
The SQL AGGREGATE SUM() function returns the sum of all selected column.
SQL Syntax : SUM ([ALL | DISTINCT] expression )
Example : SUM()
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
MAX() function
The aggregate function SQL MAX() is used to find the maximum value or highest value of a
certain column or expression. This function is useful to determine the largest of all selected
values of a column.
Example : MAX()
MIN() function
The aggregate function SQL MIN() is used to find the minimum value or lowest value of a
column or expression. This function is useful to determine the smallest of all selected values of
a column.
Syntax : MIN([ALL | DISTINCT] expression ): With
SQL Aliases
SQL aliases are used to give a table or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of the query.
The following SQL statement creates two aliases, one for the CustomerID column and one for
the CustomerName column:
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
25
Chapter 7 Fundamentals of database system GTC 2014 E.C
The following SQL statement creates two aliases, one for the CustomerName column and one
for the ContactName column.
Note: It requires double quotation marks or square brackets if the alias name contains spaces:
String functions
These functions are used to deal with the string type values like
ASCII, LOWEWR, UPPER, LEN, LEFT, RIGHT, TRIM, LTRIM, RTRIM etc.
ASCII : Returns the ASCII code value of a character (leftmost character of string
LOWER : Convert character strings data into lowercase.
Syntax: LOWER(string)
SELECT LOWER('STRING FUNCTION')
Syntax: UPPER(string)
Syntax:LEN(string)
CURRENT_TIMESTAMP:-
SELECT CURRENT_TIMESTAMP; :
GETDATE();;
SELECT GETDATE();;
26
Chapter 7 Fundamentals of database system GTC 2014 E.C
Mathematical Function
These functions performs a calculation, usually based on input values that are provided as
arguments and return a numeric value they take “n” as input where “n” is numeric expression.
The ROUND() Function
The ROUND() function is used to round a numeric field to the number of decimals specified
SQL ROUND() Syntax
SELECT ROUND(column_name,decimals) FROM table_name;
Eg: select round(salary,2) from employee
select fname,ROUND(salary,2)as'roundedsalary'from employee
Power ()function
Returns the power value of the specified expression to the specified power.
Syntax:Power(expression,power)
Eg. Select power(2,3) ---returns=8
Square() function
Returns the square of the given number
Syntax:Square(number)
Eg:select square(4) -– return=16
select square(9)- - 81
SQRT()function
Return the square root of the given number.
Syntax:sqrt(number)
Eg; select sqrt(81)--- return 9
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each. JOIN is a means for
combining columns from one (self-join) or more tables by using values common to each.
A SQL JOIN combines records from two tables.
A JOIN locates related column values in the two tables.
A query can contain zero, one, or multiple JOIN operations.
INNER JOIN is the same as JOIN; the keyword INNER is optional.
Different types of JOINs
(INNER) JOIN: Select records that have matching values in both tables.
LEFT (OUTER) JOIN: Select records from the first (left-most) table with matching right table
records.
27
Chapter 7 Fundamentals of database system GTC 2014 E.C
RIGHT (OUTER) JOIN: Select records from the second (right-most) table with matching left
table records. RIGHT JOIN and RIGHT OUTER JOIN are the same.
FULL (OUTER) JOIN: Selects all records that match either left or right table records.
SELECT column-names
FROM table-name1 INNERJOIN table-name2
ON column-name1 = column-name2
WHERE condition
The general syntax is:
SELECT column-names
FROM table-name1 LEFTJOIN table-name2
ON column-name1 = column-name2
WHERE condition
SELECT column-names
FROM table-name1 RIGHTJOIN table-name2
ON column-name1 = column-name2
WHERE condition
28
Chapter 7 Fundamentals of database system GTC 2014 E.C
Operators in SQL
An operator is a reserved word or a character used primarily in an SQL statement's WHERE
clause to perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions
The following are the commonly used operators in SQL
Arithmetic Operators +, -, *, /
Comparison Operators =, <, >, <=, >=, <>
Logical Operators OR, AND, NOT
1. Multiplication ( * )
2. Division (/)
3. Modulo (%)
4. Addition (+)
5. Subtraction (-)
29
Chapter 7 Fundamentals of database system GTC 2014 E.C
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
Note: The column names in the result-set are usually equal to the column names in the first SELECT
statement in the UNION
Note: If some customers or suppliers have the same name, each name will only be listed once, because
UNION selects only distinct values. Use UNION ALL to also select duplicate values!
30
Chapter 7 Fundamentals of database system GTC 2014 E.C
EXCEPT Clause
The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns
rows from the first SELECT statement that are not returned by the second SELECT statement.
This means EXCEPT returns only rows, which are not available in second SELECT statement.
Just as with the UNION operator, the same rules apply when using the EXCEPT operator.
The basic syntax of EXCEPT is as follows:
SELECT column-name
FROM table1
EXCEPT
SELECT column name
FROM table2
ALL operator returns true if all of the sub query values meet the condition.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
The EXISTS operator is used to test for the existence of any record in a sub query.
The EXISTS operator returns true if the sub query returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition)
31
Chapter 7 Fundamentals of database system GTC 2014 E.C
A sub query is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.A sub query may occur in :
o - A SELECT clause
o - A FROM clause
o - A WHERE clause
The sub query can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or
inside another sub query.
A sub query is usually added within the WHERE Clause of another SQL SELECT statement.
You can use the comparison operators, such as >, <, or =. The comparison operator can also be
a multiple-row operator, such as IN, ANY, or ALL.
A sub query is also called an inner query or inner select, while the statement containing a sub
query is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an inner query can
be passed to the outer query.
The sub query (inner query) executes once before the main query (outer query) executes.
The main query (outer query) uses the sub query result.
You can use a sub query in a SELECT, INSERT, DELETE, or UPDATE statement to perform
the following tasks:
Syntax :
Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So, only create indexes on columns that will be frequently searched
against.
33
Chapter 7 Fundamentals of database system GTC 2014 E.C
Note: The syntax for creating indexes varies among different databases. Therefore: Check the syntax
for creating indexes in your database
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 idx_pname
ON Persons (LastName, FirstName);
SQL Server:
34
Chapter 7 Fundamentals of database system GTC 2014 E.C
A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.You can add SQL functions, WHERE, and JOIN
statements to a view and present the data as if the data were coming from one single table.
Advantages view
Structure data in a way that users or classes of users find natural or intuitive.
There are 2 types of Views in SQL: Simple View and Complex View.
Complex views can be constructed on more than one base table. In particular, complex views can
contain: join conditions, a group by clause, a order by clause
Contains only one single base table or is created from only one table
We cannot use group functions like MAX(), COUNT(), etc
Does not contain groups of data.
DML operations could be performed through a simple view
INSERT, DELETE and UPDATE are directly possible on a simple view.
Simple view does not contain group by, distinct, pseudocolumn like rownum, columns defined
by expressions
Does not include NOT NULL columns from base tables.
COMPLEX VIEW
Contains more than one base table or is created from more than one table.
We can use group functions
It can contain groups of data
DML operations could not always be performed through a complex view.
We cannot apply INSERT, DELETE and UPDATE on complex view directly
It can contain group by, distinct, pseudocolumn like rownum, columns defiend by
expressions
35
Chapter 7 Fundamentals of database system GTC 2014 E.C
NOT NULL columns that are not selected by simple view can be included in complex view
A view is a virtual table. A view consists of rows and columns just like a table. The
difference between a view and a table is that views are definitions built on top of other tables
(or views), and do not hold data themselves. If data is changing in the underlying table, the
same change is reflected in the view
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL
statement, every time a user queries a view.
The following SQL creates a view that shows all customers from Brazil:
createview view_emp asselect eid,ename,age from emp1
select*from view_emp
Updating a View
A view can be updated under certain conditions which are given below −
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY clause.
The FROM clause may not contain multiple tables.
The WHERE clause may not contain sub queries.
The query may not contain GROUP BY or HAVING.
Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The following
code block has an example to update the enameof eid=1.
36
Chapter 7 Fundamentals of database system GTC 2014 E.C
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The
syntax is very simple and is given below −
37