You are on page 1of 37

Chapter 7 Fundamentals of database system GTC 2014 E.

Chapter 7: The SQL Language


7.1. Structured Query Language
 SQL is a language of database, it includes database creation, deletion, fetching rows and
modifying rows etc.
 SQL is an ANSI (American National Standards Institute) standard, but there are many
different versions of the SQL language.
 SQL is Structured Query Language, which is a computer language for storing, manipulating
and retrieving data stored in relational database.
 SQL is the standard language for Relation Database System. All relational database
management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL
Server use SQL as standard database language.

What can SQL do?


 Allows users to access data in relational database management systems.
 Allows users to describe the data.
 Allows users to define the data in database and manipulate that data.
 Allows embedding within other languages using SQL modules, libraries & pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a database.
 Allows users to set permissions on tables, procedures and views

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

tinyint Allows whole numbers from 0 to 255 1 byte

smallint Allows whole numbers between -32,768 and 32,767 2 bytes

int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

decimal(p,s) Fixed precision and scale numbers. 5-17 bytes


Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits that can be
stored (both to the left and to the right of the decimal point). p must be a
value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right
of the decimal point. s must be a value from 0 to p. Default value is 0

money Monetary data from -922,337,203,685,477.5808 to 8 bytes


922,337,203,685,477.5807

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.

String data types:

Data type Description Max size Storage

char(n) Fixed width character string 8,000 characters Defined width

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:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: a unique number

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

7.3. DDL, DML, TCL and DCL

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

DCL -Data Control Language


 Grant: - Gives a privilege to user
 Revoke: - Takes back privileges granted from user
DQL -Data Query Language
 SELECT :- Retrieves certain records from one or more tables

SQL RDBMS Concepts


What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL and for
all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
A Relational database management system (RDBMS) is a database management system (DBMS) that
is based on the relational model as introduced by E. F. Codd.
What is table?
 The data0 in RDBMS is stored in database objects called tables. The table is a collection of
related data entries and it consists of columns and rows.
 Remember, a table is the most common and simplest form of data storage in a relational
database.
What is field?
 Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS
table consist of ID, SEX,NAME, AGE, City and SALARY.
 A field is a column in a table that is designed to maintain specific information about every
record in the table.
What is record or row?
 A record, also called a row of data, is each individual entry that exists in a table.
 A record is a horizontal entity in a table.
3
Chapter 7 Fundamentals of database system GTC 2014 E.C

What is NULL value?


 A NULL value in a table is a value in a field that appears to be blank, which means a field with
a NULL value is a field with no value.
 It is very important to understand that a NULL value is different than a zero value or a field
that contains spaces. A field with a NULL value is one that has been left blank during record
creation

7.4 . Basic Queries in SQL

SQL CREATE Database


The SQL CREATE DATABASE Statement

 The CREATE DATABASE statement is used to create a new SQL database.

Syntax
CREATE DATABASE databasename;
CREATE DATABASE Example

The following SQL statement creates a database called "testDB":

Example
CREATE DATABASE testDB

The SQL CREATE TABLE Statement

 The CREATE TABLE statement is used to create a new table in a database.

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.).

SQL CREATE TABLE Example

 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 »

 The PersonID column is of type int and will hold an integer.


 The LastName, FirstName, Address, and City columns are of type varchar and will hold characters,
and the maximum length for these fields is 255 characters.

The empty "Persons" table will now look like this:

PersonID LastName FirstName Address City

Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.

The SQL DROP DATABASE Statement


The DROP DATABASE statement is used to drop an existing SQL database.

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!

DROP DATABASE Example

 The following SQL statement drops the existing database "testDB":

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;

The SQL DROP TABLE Statement

 The DROP TABLE statement is used to drop an existing table in a database.

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!

SQL DROP TABLE Example

 The following SQL statement drops the existing table "Shippers":

Example
DROP TABLE Shippers;

SQL ALTER TABLE Statement

 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.

ALTER TABLE - ADD Column

 To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

 The following SQL adds an "Email" column to the "Customers" 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)

ALTER TABLE table_name


DROP COLUMN column_name;

 The following SQL deletes the "Email" column from the "Customers" table:

Example
6
Chapter 7 Fundamentals of database system GTC 2014 E.C

ALTER TABLE Customers


DROP COLUMN Email;
ALTER TABLE - ALTER/MODIFY COLUMN

SQL Server / MS Access:

ALTER TABLE table_name


ALTER COLUMN column_name datatype;

SQL ALTER TABLE Example

 Now we want to add a column named "DateOfBirth" in the "Persons" table.


 We use the following SQL statement:

ALTER TABLE Persons


ADD DateOfBirth date;

 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:

ALTER TABLE Persons


ALTER COLUMN DateOfBirth year;

 Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-
or four-digit format.

DROP COLUMN Example

 Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
 We use the following SQL statement:

ALTER TABLE Persons


DROP COLUMN DateOfBirth;

The SQL INSERT INTO Statement

 The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax

 It is possible to write the INSERT INTO statement in two ways.

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:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

 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:

INSERT INTO table_name


VALUES (value1, value2, value3, ...)

INSERT INTO Example

 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

 It is also possible to only insert data in specific columns.


 The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):

7.5. SQL Comments

 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.

Single Line Comments

 Single line comments start with --.


 Any text between -- and the end of the line will be ignored (will not be executed).
 The following example uses a single-line comment as an explanation:

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';

The following example uses a single-line comment to ignore a statement:

Example
--SELECT * FROM Customers;
SELECT * FROM Products;
Multi-line Comments

 Multi-line comments start with /* and end with */.


 Any text between /* and */ will be ignored.
 The following example uses a multi-line comment as an explanation:

Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;

 The following example uses a multi-line comment to ignore many statements:

Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;

 To ignore just a part of a statement, also use the /* */ comment.


 The following example uses a comment to ignore part of a line:
 Example
SELECT CustomerName, /*City,*/ Country FROM Customers;

 The following example uses a comment to ignore part of a statement:

Example

9
Chapter 7 Fundamentals of database system GTC 2014 E.C

SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'


OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName

7.6 .SQL Constraints

 Constraints are the rules enforced on data columns on table.


 Constraints enforce limits to the data or type of data that can be inserted/updated/deleted from a table.
 The whole purpose of constraints is to maintain the data integrity during an update/delete/insert into a
table. If there is any violation between the constraint and the data action, the action is aborted.
 Constraints could be column level or table level. Column level constraints are applied only to
one column, whereas table level constraints are applied to the whole table.

The following are commonly used constraints available in SQL:


NOT NULL: - Constraint: Ensures that a column cannot have NULL value.
 It is a rule that prevents null values from being entered into one or more columns within
a table.

 By default, a column can hold NULL values.


 The NOT NULL constraint enforces a column to NOT accept NULL values.
 This enforces a field to always contain a value, which means that you cannot insert a
new record, or update a record without adding a value to this field.
 The following SQL ensures that the "ID", "LastName", and "FirstName" columns will
NOT accept NULL values:

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.

PRIMARY Key: Uniquely identified each rows/records in a database table.


 A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
FOREIGN Key: Uniquely identified a rows/records in any another database table.
10
Chapter 7 Fundamentals of database system GTC 2014 E.C

 A foreign key constraint (also referred to as a referential constraint or a referential integrity


constraint) is a logical rule about values in one or more columns in one or more tables.
 For example, a set of tables shares information about a corporation's suppliers. Occasionally, a
supplier's name changes. You can define a referential constraint stating that the ID of the
supplier in a table must match a supplier ID in the supplier information. This constraint
prevents insert, update, or delete operations that would otherwise result in missing supplier
information.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.
 The CHECK Constraint enables a condition to check the value being entered into a record. If
the condition evaluates to false, the record violates the constraint and isn‟t entered into the
table.
 A (table) check constraint (also called a check constraint) sets restrictions on data added to a
specific table. For example, a table check constraint can ensure that the salary level for an
employee is at least $20 000 whenever salary data is added or updated in a table containing
personnel information.

DEFAULT:-Constraint: Provides a default value for a column when none is specified.


INDEX: Use to create and retrieve data from the database very quickly.

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‟

Create Table Customers(


Id Int Primary Key Not Null,
Name Varchar (20) Not Null Unique,
Age int not null check (age >= 18),,
Address Char (25) Default „Dm‟,
Salary Money
)

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

 Primary key cannot have a NULL value.


 Each table can have only one primary key.
 By default, Primary key is clustered index and data in the database table is physically organized in
the sequence of clustered index.
 Primary key can be related with another table's as a Foreign Key.
 We can generate ID automatically with the help of Auto Increment field. Primary key supports
Auto Increment value.
Unique Key

 Unique Constraint may have a NULL value.


 Each table can have more than one Unique Constraint.
 By default, unique key is a unique non-clustered index.
 Unique Constraint cannot be related with another table's as a Foreign Key.
 Unique Constraint doesn't support Auto Increment value.
Foreign 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

The SQL SELECT Statement

 The SELECT statement is used to select data from a database.


 The data returned is stored in a result table, called the result-set.

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:

SELECT * FROM table_name;

 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.

SELECT INTO Syntax


Copy all columns 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.

SQL SELECT INTO Examples


EG.
SELECT * INTO copytable
FROM Customers

13
Chapter 7 Fundamentals of database system GTC 2014 E.C

The SQL WHERE Clause

 The WHERE clause is used to filter records.


 The WHERE clause is used to extract only those records that fulfill a specified condition.

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.!

WHERE Clause Example

 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 !=

> Greater than

< Less than

14
Chapter 7 Fundamentals of database system GTC 2014 E.C

>= Greater than or equal

<= Less than or equal

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

SQL UPDATE Statement

 The UPDATE statement is used to modify the existing records in a table.

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

 The DELETE statement is used to delete existing records in a table.

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!

 SQL DELETE Example


 The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

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:

DELETE FROM table_name;

 The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:

Example
DELETE FROM Customers;
AUTO INCREMENT Field

 Auto-increment allows a unique number to be generated automatically when a new record is


inserted into a table.

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.

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,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
)

 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):

INSERT INTO Persons (FirstName,LastName)


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 "FirstName" column would be set to "Lars" and the
"LastName" column would be set to "Monsen".

The SQL SELECT DISTINCT Statement

 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.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT Example

 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.

SELECT DISTINCT Examples

 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:

Example SELECT * FROM Customers


ORDER BY Country DESC
18
Chapter 7 Fundamentals of database system GTC 2014 E.C

The SQL GROUP BY Statement


The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to
group the result-set by one or more columns.

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

 A wildcard character is used to substitute any other character(s) in a string.


 Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a
WHERE clause to search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

 % - The percent sign represents zero, one, or multiple characters


 _ - The underscore represents a single character

Note: MS Access uses a question mark (?) instead of the underscore (_).

In MS Access and SQL Server you can also use:

 [charlist] - Defines sets and ranges of characters to match


 [^charlist] or [!charlist] - Defines sets and ranges of characters NOT to match
 The wildcards can also be used in combinations!
 Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

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"

Using the % Wildcard

 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

SELECT * FROM Customers


WHERE City LIKE '[bsp]%';

 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.

SQL Server / MS Access Syntax:

SELECT TOP number|percent column_name(s)


FROM table_name
WHERE condition;
SQL TOP PERCENT Example

 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

MIN returns the smallest value in a given column


MAX returns the largest value in a given column
SUM returns the sum of the numeric values in a given column
AVG returns the average value of a given column
returns the total number of values in a given column
COUNT

The SQL COUNT(), AVG() and SUM(),MAX(),MIN() 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 : COUNT() with WHERE


23
Chapter 7 Fundamentals of database system GTC 2014 E.C

Example : SELECT COUNT(*)


FROM Employee
WHERE age>=20

Example : COUNT() with DISTINCT

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()

Example : SELECT AVG(salary)


FROM Employee

SUM() function

The SQL AGGREGATE SUM() function returns the sum of all selected column.
SQL Syntax : SUM ([ALL | DISTINCT] expression )

Example : SUM()

Example : SELECT SUM(salary)


FROM Employee

Example : SUM() with WHERE

Example : SELECT SUM(salary)


FROM Employee
WHERE qty>3;
24
Chapter 7 Fundamentals of database system GTC 2014 E.C

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()

Example : SELECT MAX(salary)


FROM Employee

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.

Alias Column Syntax


SELECT column_name AS alias_name
FROM table_name;
Alias for Columns Examples

 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:

Aliases can be useful when:

 There are more than one table involved in a query


 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

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')

Returns string function


UPPER : Convert character strings data into Uppercase.

Syntax: UPPER(string)

SELECT UPPER('string function')

LEN: Returns the length of the character string.

Syntax:LEN(string)

SELECT LEN('STRING FUNCTION')

SQL -Date function

 Date Expressions return current system date and time values:

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

Exe SQL Joins

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.

The SQL JOIN syntax:

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

The SQL RIGHT JOIN syntax

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

Arithmetic operators are used to perform simple arithmetic operations.


 Arithmetic Operators. Arithmetic operators can perform arithmetical operations on
numeric operands involved.
 Arithmetic operators are addition (+), subtraction (-),multiplication(*) and division(/).
 The + and - operators can also be used in date arithmetic.
 SQL support all arithmetic operators (multiplication, division, modulo, addition, subtraction).

Order of precedence of arithmetic expression

1. Multiplication ( * )
2. Division (/)
3. Modulo (%)
4. Addition (+)
5. Subtraction (-)

Comparison Operators are used when two values are to be compared

29
Chapter 7 Fundamentals of database system GTC 2014 E.C

=, <, >, <=, >=, <>


Here are simple examples showing usage of SQL Comparison Operators:
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;
Logical operators are used to connect search conditions in the WHERE Clause in SQL.
SQL UNION Clause
 The UNION operator is used to combine the result-set of two or more SELECT statements.
 Each SELECT statement within UNION must have the same number of columns
 The columns must also have similar data types
 The columns in each SELECT statement must also be in the same order
 ORDER By clause should be use only on the last select statement in the union query.

UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL Syntax

The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

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

The SQL ANY and ALL Operators

 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 SQL EXISTS Operator

 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

7.7 . .Nested Queries in SQL

SQL - Sub Queries


A Sub query or Inner query or a Nested query is a query within another SQL query and embedded
within the WHERE clause.

 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

There are a few rules that sub queries must follow :-


 Sub queries must be enclosed within parentheses.
 A sub query must be placed on the right side of the comparison operator.
 Sub queries cannot manipulate their results internally; therefore ORDER BY clause cannot be
added into a sub query. You can use an ORDER BY clause in the main SELECT statement
(outer query) which will be the last 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:

 Compare an expression to the result of the query.


 Determine if an expression is included in the results of the query.
 Check whether the query selects any rows.
32
Chapter 7 Fundamentals of database system GTC 2014 E.C

Syntax :

CREATE INDEX Statement


 Indexes are used to retrieve data from the database very fast. The users cannot see the indexes;
they are just used to speed up searches/queries.Indexes are created on columns in tables or
views. ... For example, if you create an index on the primary key and then search for a row of
data based on one of the primary key values, SQL Server first finds that value in theindex, and
then uses the index to quickly locate the entire row of data
 In SQL Server, a clustered index determines the physical order of data in a table. There can be
only one clustered index per table (the clustered index
 Clustered Index. A clustered index defines the order in which data is physically stored in a
table. Table data can be sorted in only way, therefore, there can be only one clustered
index per table. In SQL Server, the primary key constraint automatically creates a clustered
index on that particular column.
 A clustered index actually describes the order in which records are physically stored on the
disk, hence the reason you can only have one.
 A Non-Clustered Index defines a logical order that does not match the physical order on disk.
Clustered index is essentially a sorted copy of the data in the indexed columns

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.

CREATE INDEX Syntax

 Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2, ...);

33
Chapter 7 Fundamentals of database system GTC 2014 E.C

CREATE INDEX Example


 The SQL statement below creates an index named "idx_ename" on the "ename" column in the
"Employee" table:
 createindex idx_ename on employee(ename)
 The SQL statement below creates an index named "idx_Lastname" on the "Lastname" column
in the "person" table:
CREATE INDEX idx_lastname
ON Persons (LastName);
CREATE UNIQUE INDEX Syntax

 Creates a unique index on a table. Duplicate values are not allowed:


 CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);

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);

DROP INDEX Statement

The DROP INDEX statement is used to delete an index in a table.

SQL Server:

DROP INDEX table_name.index_name;


The following guidelines indicate when the use of an index should be reconsidered.
 Indexes should not be used on small tables.
 Tables that have frequent, large batch updates or insert operations.
 Indexes should not be used on columns that contain a high number of NULL values.
 Columns that are frequently manipulated should not be indexed.
7.8. SQL View
SQL CREATE VIEW Statement

 In SQL, a view is a virtual table based on the result-set of an SQL statement.

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.

 A database view allows you to simplify complex queries:


 Restrict access to the data in such a way that a user can see and (sometimes) modify exactly
what they need and no more.
 Summarize data from various tables which can be used to generate reports.
 It is used to implement the security mechanism in the SQL Server

There are 2 types of Views in SQL: Simple View and Complex View.

Simple views can only contain a single base table.

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

The key differences between these types of Views are:


SIMPLE VIEW

 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

The difference between a view and a table

 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

CREATE VIEW Syntax


CREATE VIEW view name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

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.

SQL CREATE VIEW Examples

 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

update view_emp set ename='aa'where eid=1


Inserting Rows into a View
Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also
apply to the INSERT command.
Eg:
Insert into view_emp values(6,'bb',32)

Deleting Rows into a View


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.
Following is an example to delete a record having AGE = 30.
deletefrom view_emp where age=30

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 −

DROP VIEW view_name


Eg:
dropview view_emp
|

37

You might also like