0% found this document useful (0 votes)
282 views78 pages

LO1 Write An SQL Statement To Retrieve and Sort Data: Using Basic Structured Query Language

SQL is a standardized language used to manage data in relational database management systems. It can perform functions like executing queries, retrieving, inserting, updating, and deleting records. Common DBMS that use SQL include Microsoft SQL Server, Oracle, MySQL, and Microsoft Access. SQL statements are divided into three categories - DDL for defining databases and schema, DML for manipulating data, and DCL for controlling access.

Uploaded by

Galaxy teck
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
282 views78 pages

LO1 Write An SQL Statement To Retrieve and Sort Data: Using Basic Structured Query Language

SQL is a standardized language used to manage data in relational database management systems. It can perform functions like executing queries, retrieving, inserting, updating, and deleting records. Common DBMS that use SQL include Microsoft SQL Server, Oracle, MySQL, and Microsoft Access. SQL statements are divided into three categories - DDL for defining databases and schema, DML for manipulating data, and DCL for controlling access.

Uploaded by

Galaxy teck
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Using Basic Structured Query Language

LO1 Write an SQL Statement to retrieve and sort data


1.1 Introduction to SQL
1.1.1 What is SQL?
SQL (Structured Query Language) is a database computer language designed for managing data
in relational database management systems (RDBMS).

Most Relational Database Management Systems like MS SQL Server, Microsoft Access, Oracle,
MySQL, DB2, Sybase, PostgreSQL and Informix use SQL as a database querying language.
Even though SQL is defined by both ISO and ANSI there are many SQL implementation, which
do not fully comply with those definitions.

SQL, is a standardized computer language that was originally developed by IBM for querying,
altering and defining relational databases, using declarative statements. SQL is relatively simple
language, but it’s also very powerful.
SQL is pronounced SEQUEL. SQL was developed during the early 70’s at IBM.

1.1.2 Categories of SQL Application


What can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

Even if SQL is a standard, many of the database systems that exist today implement their own
version of the SQL language.

1.2 Installing DBMS software


1.2.1 Introduction:- DBMS is a Set of programs to access the data or software system
designed to store, manage, and facilitate access to databases.
 Collection of interrelated data
 DMBS contains information about a particular enterprise
 DBMS provides an environment that it both convenient and efficient to use
Database Applications:
 Banking:- all transactions
 Airlines:- reservations, schedules
 Universities:- registrations. Grade
 Sales:- customers, products, purchase
 Human resource:- employee records, salaries, tax deduction

BY:- Ermias Israel


Page 1
Using Basic Structured Query Language

 Manufacturing: production, Inventory, orders, supply chain


Purpose of Database Systems
Database management systems were developed to handle the following difficulties of typical
file-processing systems supported by conventional operating systems:
 Data redundancy and inconsistency
 Difficulty in accessing data
 Data isolation – multiple files and formats
 Integrity problems
 Atomicity of updates
 Concurrent access by multiple users
 Security problems
There are lots of different database systems, or DBMS- Database Management Systems, such as:
1. Microsoft SQL Server
 Enterprise, Developer versions, etc.
 Express version is free of charge
MS SQL Server is a Relational Database Management System developed by Microsoft Corp. MS
SQL Server is an enterprise level database competing with products like Oracle and DB2. MS
SQL Server cost much less than its comparable competitors products, hence its popularity.

MS SQL Server is a paid database server, but it has a free limited version called MSDE
(Microsoft SQL Server Desktop Engine). MSDE version of MS SQL Server is free for re-
distribution with desktop applications. As we mentioned MSDE has certain restrictions, like:
 The maximum size of a database is 2 GB
 MSDE comes with no administration tools.
 MSDE has has a governor which will slower the db server response once you exceed 5
concurrent connections to it.
MS SQL Server uses SQL as its standard database language. The SQL dialect used by MS SQL
Server is called T-SQL.
The latest MS SQL Server version available on the market is MS SQL Server 2008.

2. Oracle
Oracle is aObject- relational database management system developed by Oracle Corporation.The
Oracle RDBMS is used in many database applications on sevarl OS platforms, including Unix
and Windows.
 Founding of Oracle
In 1977, Larry Ellison, Bob Miner, and Ed Oates started the consultancy Software Development
Laboratories, which became Relational Software, Inc. (RSI). In 1983, RSI became Oracle
Systems Corporation and then later Oracle Corporation.
 First commercially available RDBMS
In 1979, RSI introduced Oracle V2 (Version 2) as the first commercially available SQL-based
RDBMS, a landmark event in the history of relational databases.
 Objects and partitioning
Oracle8 was released in 1997 as the object-relational database, supporting many new data types.
Additionally, Oracle8 supported partitioning of large tables.

BY:- Ermias Israel


Page 2
Using Basic Structured Query Language

The Oracle database was the first commercial RDBMS that became available on Linux during
the summer of1999. The Oracle datatabase is more expensive compared to MS SQL Server.

 PL/SQL stored program units


PL/SQL short for Procedural Language/Structured Query Language is Oracle's server-based
extension to the SQL language.
 Portable version of Oracle Database

3. MySQL (Oracle, previously Sun Microsystems) –


MySQL can be used free of charge (open source license), MySQL is an open source relational
database management system released under GNU General Public License. The Swedish
company called MySQL AB develops MySQL. This is partly because it is completely free but
also very powerful.

MySQL is most commonly used for Web applications and for embedded applications and has
become a popular alternative to proprietary database systems because of its speed and reliability.
MySQL can run on UNIX, Windows and Mac OS. MySQL is developed, supported and
marketed by MySQL AB.

4. Microsoft Access
it’s one of the most popular Microsoft products. MS Access comes with the professional edition
of MS Office package. MS Access is a paid product and runs only on Windows platform.

MS Access has easy to use intuitive graphical interface, which makes it one of the most popular
database software among small business.

5. IBM DB2
DB2 is relational database management system developed by IBM. DB2 is the first database
product that used SQL language. DB2 was first available on the mainframe and later moved to
UNIX, Linux and Windows platforms.

DB2 has the ability to handle millions of transactions and huge sets of data. DB2 is very scalable
and can handle serious workloads.DB2’s main competitor is Oracle. DB2 is a low cost
alternative to MS SQL Server and Oracle databases. DB2 is usually administered through multi-
platform java client GUI.

DBMS Terminologies and Definations

1. Data Definition Language (DDL)


The DDL manages table and index structure. Specification notation for defining the database
schema. DDL compiler generates a set of tables stored in a data dictionary and Data dictionary
contains metadata (data about data). DDL statements are used to define the database structure or
schema.

BY:- Ermias Israel


Page 3
Using Basic Structured Query Language

Data storage and definition language – special type of DDL in which the storage structure and
access methods used by the database system are specified.
The most basic items of DDL are the CREATE, ALTER, RENAME and DROP statements:
 CREATE creates an object (a table, for example) in the database.
 DROP deletes an object in the database, usually irretrievably.
 ALTER modifies the structure an existing object in various ways—for example, adding a
column to an existing table
 TRUNCATE - remove all records from a table, including all spaces allocated for the records
are removed
 COMMENT - add comments to the data dictionary
 RENAME - rename an object
2. Data Manipulation Language (DML)
The DML Language for accessing and manipulating the data organized by the appropriate data
model. It is the subset of SQL used to add, update and delete data and statements are used for
managing data within schema objects.

The acronym CRUD refers to all of the major functions that need to be implemented in a
relational database application to consider it complete. Each letter in the acronym can be mapped
to a standard SQL statement:

Operation SQL Description


Create INSERT INTO inserts new data into a database
Read (Retrieve) SELECT extracts data from a database
Update UPDATE updates data in a database
Delete (Destroy) DELETE deletes data from a database
MERGE UPSERT operation (insert or update)
CALL call a PL/SQL or Java subprogram
EXPLAIN PLAN explain access path to data
LOCK TABLE control concurrency
3. Data Control Language (DCL)
DCL is a subset of the Structured Query Lanaguge (SQL) that allows database administrators
to configure security access to relational databases. Some examples:
 GRANT - to allow specified users to perform specified tasks
 REVOKE - to cancel previously granted or denied permissions.
 DENY - may be used to explicitly prevent a user from receiving a particular permission.
This is helpful when a user may be a member of a role or group that is granted a
permission and you want to prevent that user from inheriting the permission by creating
an exception.
BY:- Ermias Israel
Page 4
Using Basic Structured Query Language

4. Transaction Control Laguage (TCL)


TCL are used to manage the changes made by DML statements. It allows statements to be
grouped together into logical transactions. used to control transactional processing in a database.
 COMMIT - save work done. To apply the transaction by saving the database changes
 SAVEPOINT - identify a point (breakpoints) for a transaction to which you can later
rollback or to allow partial rollbacks.
 ROLLBACK - restore database to original since the last COMMIT or to undo all
changes of a transaction
 SET TRANSACTION - used to specify characteristics for the transaction that follows.
For example, you can specify a transaction to be read only or read write.
 RELEASE SAVEPOINT- used to remove a SAVEPOINT that you have created.

1.2.2 Hardware Requirements:- Minimum Hardware Requirements

Table 5.3 outlines SQL Server 2008 hardware requirements.

Minimum Hardware Requirements Minimum Hardware Minimum Hardware


Hardware
32-Bit Requirements x64 Requirements IA64
Pentium III-compatible processor or Any Intel EMT64 or AMD x64 Itanium processor.
CPU faster. 1GHz minimum. Recommended chip. Minimum 1.4GHz. Recommended 1GHz or
2GHz or faster. Recommended 2GHz or faster. faster.
512MB minimum, 2GB or more 512MB minimum, 2GB or
512MB minimum, 2GB or more
Memory recommended. Report Server will use a more recommended.
recommended. Maximum is the
(RAM) maximum of 3GB (with /3GB switch in Maximum is the OS-
OS-specified maximum.
boot.ini). specified maximum.
Total will vary depending on Total will vary depending
Hard disk Total will vary depending on selected
selected components. See Table on selected components.
space components. See Table 5.2.
5.2. See Table 5.2.
VGA or higher resolution.
VGA or higher resolution. 1024x768 VGA or higher resolution.
1024x768 recommended
Monitor recommended for SQL Server graphical 1024x768 recommended for SQL
for SQL Server graphical
tools. Server graphical tools.
tools.
Microsoft mouse or
Pointing Microsoft mouse or compatible Microsoft mouse or compatible
compatible pointing
device pointing device. pointing device.
device.
CD or DVD Drive as needed
CD or DVD drive as needed for given CD or DVD drive as needed for
CD/DVDROM for given installation
installation media. given installation media.
media.
The following is the terminology used in relation to the 64-bit platform:
 IA64 refers to Itanium-compatible hardware architecture. This architecture can run IA64 software
and 32-bit software using the Windows-On-Windows (WOW64) software emulator. The
Itanium CPU cannot natively run 32-bit x86-compatible instructions and uses instruction
emulation as a part of WOW64 processing.

BY:- Ermias Israel


Page 5
Using Basic Structured Query Language

 x64 refers to Extended Memory Technology support-compatible architecture and includes


systems based on Opteron, Athlon 64, Intel Xeon EM64T, and Intel Pentium EM64T. x64
architecture can run classic 32-bit x86-compatible instructions natively on the CPU. One of the
advantages of this architecture is an ability to support both 32- and 64-bit code. To ease an
adoption of the 64-bit platform and optimize a hardware purchase, some companies might first
deploy a 32-bit operating system and software on x64 hardware and then upgrade to 64-bit
software on the same hardware requirements.
NOTE
System Configuration Check blocks setup from running if the CPU type (Pentium III or higher)
requirement is not met. Setup issues a warning, but allows you to proceed, if the CPU speed or
minimum memory requirement is not met.

1.2.3 Operating System Requirements: Software Requirements


We recommend installing Reporting Services on Windows 2008. Although Windows 2003 SP2
is a fully supported platform, Windows 2008 reflects the latest technological advances, including
enhanced coverage in the areas of security and high availability.

Windows Server 2008 also provides the Hyper-V virtualization systems. SQL Server 2008 and
all of its components, including SSRS, are supported in virtual environments created using
Hyper-V, provided of course sufficient CPU and RAM resources are allocated to the virtual
machine and that the virtual machine runs an operating system supported by SQL Server
Reporting Services (SSRS).

Tables 5.4, 5.5, and 5.6 list operating system requirements and additional software requirements
for installation of Reporting Services on 32- and 64-bit platforms.

TABLE 5.4 Operating Systems That Can Run 32-Bit Versions of Report Server

Enterprise Enterprise Developer Standard Workgroup


 
Edition Evaluation Edition Edition Edition Edition
Windows XP Professional SP2 No Yes Yes Yes Yes
Windows XP SP2 Media Center
No Yes Yes Yes Yes
Edition
Windows Vista Ultimate No Yes Yes Yes Yes
Windows Vista Business No Yes Yes Yes Yes
Windows Vista Enterprise No Yes Yes Yes Yes
Windows Vista Home Premium No Yes Yes No No
Windows 2003 SP2 Standard Yes Yes Yes Yes Yes
Windows 2003 SP2 Enterprise Yes Yes Yes Yes Yes
Windows 2003 SP2 Data Center Yes Yes Yes Yes Yes
Windows 2008 Standard Yes Yes Yes Yes Yes

BY:- Ermias Israel


Page 6
Using Basic Structured Query Language

Windows 2008 Enterprise Yes Yes Yes Yes Yes


Windows 2008 Data Center Yes Yes Yes Yes Yes

NOTE
Systems that are not explicitly listed in Table 5.4 are not supported by Reporting Services. For
example, Reporting Services 32-bit is not supported on Windows 2003 64-bit Itanium.

For situations with heavy memory or I/O requirements, such as heavy graphics and PDF
rendering, customers can benefit from deploying SSRS on a 64-bit platform. Table 5.5 outlines
SSRS support on a 64-bit platform.

TABLE 5.5 Operating System Requirements, 64-Bit

Express
  Enterprise x64 Standard x64 Workgroup x64 Web x64
x64
Windows XP Pro x64 No Yes Yes Yes No
Windows Server 2003 Standard x64 Yes Yes Yes Yes Yes
Windows Server 2003 Data Center
Yes Yes Yes Yes Yes
x64
Windows Server 2003 Enterprise x64 Yes Yes Yes Yes Yes
Windows Vista x64 Ultimate No Yes Yes Yes Yes
Windows Vista x64 Home Premium No No Yes No Yes
Windows Vista x64 Home Basic No No Yes No Yes
Windows Vista x64 Enterprise No Yes Yes Yes Yes
Windows Vista x64 Business No Yes Yes Yes Yes
Windows Server 2008 Standard x64 Yes Yes Yes Yes Yes
Windows Server 2008 Data Center
Yes Yes Yes Yes Yes
x64
Windows Server 2008 Enterprise x64 Yes Yes Yes Yes Yes

The following operating systems are supported by SQL Server Enterprise/Developer Edition
IA64:

 Windows Server 2008 64-bit Itanium


 Windows Server 2003 SP2 64-bit Itanium Data Center
 Windows Server 2003 SP2 64-bit Itanium Enterprise

Note that with any 64-bit operating system, management tools may be supported in WOW64.
WOW64 allows native 32-bit code to execute natively on non-32-bit systems.

NOTE
Development tools such as Business Intelligence Development Studio (BIDS) are neither

BY:- Ermias Israel


Page 7
Using Basic Structured Query Language

installed nor supported on the IA64 platform. For IA64 deployments, use development tools
installed on a separate 32-bit or x64 workstation.

Table 5.6 outlines additional software requirements for both 32- and 64-bit platforms and
optional software that can be installed to benefit Reporting Services.

TABLE 5.6 Additional Software Requirements, 32- and 64-Bit

Sofware Requirement Notes

.NET Framework Windows 2003 IA63 requires .NET Framework 2.0 SP1.

  Every other version of requires the .NET Framework 3.5.

Microsoft Data Access Components (MDAC) All versions require MDAC 2.8 SP1 or higher.

Windows Installer All versions require Windows Installer 4.5 or later.

1.2.4 Install DBMS (SQL Server)


Download SQL Server 2008 Express Edition with tools (around 230 MB) and run the setup file.
If you are using windows XP SP3
 Remark: Microsoft regularly updates SQL Express, so screens could change a little over time.
1. Choose between 32 bbits version (XP, Vista) or 64 Bits version (Seven)
Launch installer : the installer extracted the data

2. SQL Server instalaltion Center opens.


Click on "System configuration Checker" to check for conditions that prevents a successful SQL
Server Installation

3. Setup Support Rules opens. Click on "show details to ensure that all the tests passed
succesfully
Then click on OK

If you have some tests failures:


- click on the test to have more informations about the error
- Ensure you have uninstalled correctly all previous versions of SQL Server (2000, 2005) and
rebooted your computer before

BY:- Ermias Israel


Page 8
Using Basic Structured Query Language

- Refer to online documentation on Microdoft SQL Server website


- refer to Octopus users forum

4. Go Back to SQL Server installation Center


On the left column, click on "Installation"
Then click on the first link : "new SQL Server stand-alone installation" (Unless you want to
make a specific network installation)

5.  Setup support rules reopen. 


Once all operations completed, click OK

6. The SQL Server 2008 Setup opens with a first "product key" tab
As we use a specific free version of SQL Serveur, no activation key is needed. 
Simply click "next"

7. Read the licence terms


Check the box "I accept the licence terms"
Click on "Next"

8. The "setup support files" tab opens.


Click on "install"

9. Once installed, the Setup Support Rules reopen.


Check that all operation passsed, then click "next"

10.  On the "features selection" tab choose "Data Engine Services" and "Management tools" (this
is the Management Studio Express)
check the features directory (no need to change normally) click "next"

11. On the "instance Configuration" check that the parameters are like the screenshot on the left
(nothing to change normally)
Click "Next"

12. Disk space requirements tap


-> Click Next

13. Server Configuration:


For the first service "SQL Server Database Engine", on the account name, choose the first result
of the listbox
(in our case NT AUTHORITY\NETWORK)
Then click "Next".

14. Database Engine Configuration:


- Chose "Mixed mode"
- Enter the  password octopus

BY:- Ermias Israel


Page 9
Using Basic Structured Query Language

- Specify SQL Server administratir : Click on "add current user"


- Click "Next"

15. Error and Usage Reporting


Click next

16. Installation Rules :


Once Operation completed, click "Next"

17. Ready to install:


Click "Install"

18. Installation Progress


- Wait until Installation is finished
- Ensure "Database Engine Services" and "Management Tools Basic" are successfully installed
- Click "Next"

19. Complete:
Once installed, click on "Close"

20. To ensure SQL Express is running correctly, run "SQL Server Configuration Manager"
On the left column click on "SQL Server Services
On the right column, ensure that SQL Server (SQLEXPRESS) is running correctly (otherwhise
right-click on the device to start it)

21. Browse the new directory "Microsoft SQL Server 2008" and open the SQL Server
Management Studio to ensure it has been  correctly installed

22. If you used to work with SQL Server 2000 our SQL Server 2005 before, you will probably
obtain this message
"Do you want to import your customized user settings...". Simply click Yes (or no as you prefer
it doesn't matters concerning Octopus)

23. The SQL Server Connexion Windows appears.


Choose the following parameters:
- Server Type: Database Engine
- Server Name: (Name of your computer)\SQLEXPRESS*
- Authentification: SQL Server Authentification (if you can only see windows authentification,
you probably missed to choose
"Mixed Mode" at the Database Engine Configuration step 
- Login: sa (by default)
- Password: the password you defined at the Database Engine Configuration step (octopus in our
case)

BY:- Ermias Israel


Page 10
Using Basic Structured Query Language

* You can find the name of your computer on the control panel>System
 
Does it opens ? -> Congratulations, you can now go to the next step: Install Octopus

1.3 Create Database


The SQL CREATE DATABASE statement is used to create new SQL database.
Syntax: Basic syntax of CREATE DATABASE statement is as follows:
CREATE DATABASE DatabaseName;
Always database name should be unique within the RDBMS.
Example:
If you want to create new database <testDB>, then CREATE DATABASE statement would be
as follows:
SQL> CREATE DATABASE testDB;
Make sure you have admin privilege before creating any database. Once a database is created,
you can check it in the list of databases as follows:

MySQL> SHOW DATABASES; Or Ms SQL> select * from sys.DATABASES


+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+--------------------+
7 rows in set (0.00 sec)
Drop Databases
The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.
Syntax: Basic syntax of DROP DATABASE statement is as follows:
DROP DATABASE DatabaseName;
Always database name should be unique within the RDBMS.
Example: If you want to delete an existing database <testDB>, then DROP DATABASE
statement would be as follows:
SQL> DROP DATABASE testDB;

NOTE: Be careful before using this operation because by deleting an existing database would
result in loss of complete information stored in the database.
Make sure you have admin privilege before dropping any database. Once a database is dropped,
you can check it in the list of databases as follows:
MySQL> SHOW DATABASES; Or Ms SQL> select * from sys.DATABASES
+--------------------+

BY:- Ermias Israel


Page 11
Using Basic Structured Query Language
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
+--------------------+
6 rows in set (0.00 sec)

1.3.1 Creating Tables


Creating a basic table involves naming the table and defining its columns and each column's data
type. The SQL CREATE TABLE statement is used to create a new table.

Syntax: Basic syntax of CREATE TABLE statement is as follows:


CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns ));

CREATE TABLE is the keyword telling the database system what you want to do. In this case,
you want to create a new table. The unique name or identifier for the table follows the CREATE
TABLE statement.

Then in brackets comes the list defining each column in the table and what sort of data type it is.
The syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.

Example: Following is an example, which creates a CUSTOMERS table with ID as primary key
and NOT NULL are the constraints showing that these fields can not be NULL while creating
records in this table:
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

You can verify if your table has been created successfully by looking at the message displayed
by the SQL server, otherwise you can use DESC command as follows:

SQL> DESC CUSTOMERS; or Sp_help CUSTOMERS; in Ms SQL

BY:- Ermias Israel


Page 12
Using Basic Structured Query Language
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
Now, you have CUSTOMERS table available in your database which you can use to store
required information related to customers.
You can check complete details at Create Table Using another Table.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. The new table has the same column definitions. All
columns or specific columns can be selected. When you create a new table using existing table,
new table would be populated using existing values in the old table.

Syntax: The basic syntax for creating a table from another table is as follows:
CREATE TABLE NEW_TABLE_NAME AS
SELECT [ column1, column2...columnN ]
FROM EXISTING_TABLE_NAME
[ WHERE ]
Here, column1, column2...are the fields of existing table and same would be used to create fields
of new table.

Example: Following is an example, which would create a table SALARY using CUSTOMERS
table and having fields customer ID and customer SALARY:
SQL> CREATE TABLE SALARY AS
SELECT ID, SALARY
FROM CUSTOMERS;
This would create new table SALARY, which would have the following records:
+----+----------+
| ID | SALARY |
+----+----------+
| 1 | 2000.00 |
| 2 | 1500.00 |
| 3 | 2000.00 |
| 4 | 6500.00 |
| 5 | 8500.00 |
| 6 | 4500.00 |
| 7 | 10000.00 |
+----+----------+

Drop Table
The SQL DROP TABLE statement is used to remove a table definition and all data, indexes,
triggers, constraints, and permission specifications for that table.

BY:- Ermias Israel


Page 13
Using Basic Structured Query Language

NOTE: You have to be careful while using this command because once a table is deleted then
all the information available in the table would also be lost forever.

Syntax: Basic syntax of DROP TABLE statement is as follows:


DROP TABLE table_name;

Example: Let us first verify CUSTOMERS table and then we would delete it from the database:
SQL> DESC CUSTOMERS; or Sp_help CUSTOMERS; in Ms SQL

+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

This means CUSTOMERS table is available in the database, so let us drop it as follows:
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)

Now, if you would try DESC command, then you would get error as follows:
SQL> DESC CUSTOMERS; or Sp_help CUSTOMERS; in Ms SQL
ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist

Here, TEST is database name which we are using for our examples.

Alter Table
The SQL ALTER TABLE command is used to add, delete or modify columns in an existing
table. You would also use ALTER TABLE command to add and drop various constraints on an
existing table.

Syntax: The basic syntax of ALTER TABLE to add a new column in an existing table is as
follows:
ALTER TABLE table_name ADD column_name datatype;

The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows:
ALTER TABLE table_name DROP COLUMN column_name;

The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as
follows:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;

BY:- Ermias Israel


Page 14
Using Basic Structured Query Language

The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as
follows:
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;

The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);

The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as
follows:
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);

The basic syntax of ALTER TABLE to DROP CONSTRAINT from a table is as follows:
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;

If you're using MySQL, the code is as follows:


ALTER TABLE table_name
DROP INDEX MyUniqueConstraint;

The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as
follows:
ALTER TABLE table_name
DROP CONSTRAINT MyPrimaryKey;

If you're using MySQL, the code is as follows:


ALTER TABLE table_name
DROP PRIMARY KEY;

Example: Consider the CUSTOMERS table having the following records:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example to ADD a new column in an existing table:
ALTER TABLE CUSTOMERS ADD SEX char(1);

BY:- Ermias Israel


Page 15
Using Basic Structured Query Language

Now, CUSTOMERS table is changed and following would be output from SELECT statement:
+----+---------+-----+-----------+----------+------+
| ID | NAME | AGE | ADDRESS | SALARY | SEX |
+----+---------+-----+-----------+----------+------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL |
| 2 | Ramesh | 25 | Delhi | 1500.00 | NULL |
| 3 | kaushik | 23 | Kota | 2000.00 | NULL |
| 4 | kaushik | 25 | Mumbai | 6500.00 | NULL |
| 5 | Hardik | 27 | Bhopal | 8500.00 | NULL |
| 6 | Komal | 22 | MP | 4500.00 | NULL |
| 7 | Muffy | 24 | Indore | 10000.00 | NULL |
+----+---------+-----+-----------+----------+------+
Following is the example to DROP sex column from existing table:
ALTER TABLE CUSTOMERS DROP SEX;
Now, CUSTOMERS table is changed and following would be output from SELECT statement:
+----+---------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+---------+-----+-----------+----------+
1.3.2 Inserting Records
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax: There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into which you
want to insert data.

You may not need to specify the column(s) name in the SQL query if you are adding values for
all the columns of the table. But make sure the order of the values is in the same order as the
columns in the table. The SQL INSERT INTO syntax would be as follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example: Following statements would create six records in CUSTOMERS table:


INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

BY:- Ermias Israel


Page 16
Using Basic Structured Query Language
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

You can create a record in CUSTOMERS table using second syntax as follows:
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

All the above statements would produce the following records in CUSTOMERS table:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Populate one table using another table:
You can populate data into a table through select statement over another table provided another
table has a set of fields, which are required to populate first table. Here is the syntax:
INSERT INTO first_table_name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];

1.3.3 Select Statements


SQL SELECT statement is used to fetch the data from a database table which returns data in the
form of result table. These result tables are called result-sets.

Syntax: The basic syntax of SELECT statement is as follows:


SELECT column1, column2, columnN FROM table_name;

Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to
fetch all the fields available in the field, then you can use the following syntax:
SELECT * FROM table_name;

Example: Consider the CUSTOMERS table having the following records:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |

BY:- Ermias Israel


Page 17
Using Basic Structured Query Language
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

Following is an example, which would fetch ID, Name and Salary fields of the customers
available in CUSTOMERS table:

SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;


This would produce the following result:

+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
If you want to fetch all the fields of CUSTOMERS table, then use the following query:
SQL> SELECT * FROM CUSTOMERS;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

1.3.3.1 Data Types


SQL data type is an attribute that specifies type of data of any object. Each column, variable and
expression has related data type in SQL. You would use these data types while creating your
tables. You would choose a particular data type for a table column based on your requirement.
SQL Server offers six categories of data types for your use:

Exact Numeric Data Types:


DATA TYPE FROM TO
bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807
int -2,147,483,648 2,147,483,647
BY:- Ermias Israel
Page 18
Using Basic Structured Query Language

smallint -32,768 32,767


tinyint 0 255
bit 0 1
decimal -10^38 +1 10^38 -1
numeric -10^38 +1 10^38 -1
money -922,337,203,685,477.5808 +922,337,203,685,477.580
7
smallmoney -214,748.3648 +214,748.3647

Approximate Numeric Data Types:


DATA TYPE FROM TO
float -1.79E + 308 1.79E + 308
real -3.40E + 38 3.40E + 38

Date and Time Data Types:


DATA TYPE FROM TO
datetime Jan 1, 1753 Dec 31, 9999
smalldatetime Jan 1, 1900 Jun 6, 2079
date Stores a date like June 30, 1991
time Stores a time of day like 12:30 P.M.

Note: Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute
accuracy.
Character Strings Data Types:
DATA FROM TO
TYPE
char char Maximum length of 8,000 characters.( Fixed length non-
Unicode characters)
varchar varchar Maximum of 8,000 characters.(Variable-length non-Unicode
data).
varchar(max varchar(max) Maximum length of 231characters, Variable-length non-
) Unicode data (SQL Server 2005 only).
text text Variable-length non-Unicode data with a maximum length of
2,147,483,647 characters.

Unicode Character Strings Data Types:


DATA Description
TYPE
nchar Maximum length of 4,000 characters.( Fixed length Unicode)
nvarchar Maximum length of 4,000 characters.(Variable length Unicode)
nvarchar(max Maximum length of 231characters (SQL Server 2005 only).( Variable length
) Unicode)
ntext Maximum length of 1,073,741,823 characters. ( Variable length Unicode )

BY:- Ermias Israel


Page 19
Using Basic Structured Query Language

Binary Data Types:


DATA TYPE Description
binary Maximum length of 8,000 bytes(Fixed-length binary data )
varbinary Maximum length of 8,000 bytes.(Variable length binary data)
varbinary(max) Maximum length of 231 bytes (SQL Server 2005 only). ( Variable
length Binary data)
image Maximum length of 2,147,483,647 bytes. ( Variable length Binary
Data)

Misc Data Types:


DATA TYPE Description
sql_variant Stores values of various SQL Server-supported data types, except text,
ntext, and timestamp.
timestamp Stores a database-wide unique number that gets updated every time a row
gets updated
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML data. You can store xml instances in a column or a variable
(SQL Server 2005 only).
cursor Reference to a cursor object
table Stores a result set for later processing

1.3.3.2 Expressions
An expression is a combination of one or more values, operators, and SQL functions that
evaluate to a value.
SQL EXPRESSIONs are like formulas and they are written in query language. You can also use
them to query the database for specific set of data.
Syntax:
Consider the basic syntax of the SELECT statement as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE [CONDITION|EXPRESSION];
There are different types of SQL expressions, which are mentioned below:

1.3.3.2.1 Comparison Operators


A comparison (or relational) operator is a mathematical symbol which is used to compare
between two values.
Comparison operators are used in conditions that compare one expression with another. The
result of a comparison can be TRUE, FALSE, or UNKNOWN (an operator that has one or two
NULL expressions returns UNKNOWN).

The following table describes different types of comparison operators -


Operato Description Example
r
= Checks if the values of two operands are equal or not, if yes (a = b) is not true.

BY:- Ermias Israel


Page 20
Using Basic Structured Query Language

then condition becomes true.


!= Checks if the values of two operands are equal or not, if (a != b) is true.
values are not equal then condition becomes true.
<> Checks if the values of two operands are equal or not, if (a <> b) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of (a > b) is not true.
right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (a < b) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (a >= b) is not true.
the value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the (a <= b) is true.
value of right operand, if yes then condition becomes true.
!< Checks if the value of left operand is not less than the value (a !< b) is false.
of right operand, if yes then condition becomes true.
!> Checks if the value of left operand is not greater than the (a !> b) is true.
value of right operand, if yes then condition becomes true.

Syntax
SELECT [column_name | * | expression] <comparison operator>
[column_name | * | expression ]
FROM <table_name>
WHERE <expression> [ comparison operator] <expression>;

1.3.3.2.2 SQL Logical/Boolean Operators


There are three Logical Operators namely, AND, OR, and NOT. These operators compare two
conditions at a time to determine whether a row can be selected for the output. When you are
retrieving data using a SELECT statement, you can use logical operators in the WHERE clause,
which allows you to combine more than one condition.

Operator Description
ALL The ALL operator is used to compare a value to all values in another value set.
AND The AND operator allows the existence of multiple conditions in an SQL
statement's WHERE clause.
ANY The ANY operator is used to compare a value to any applicable value in the list
according to the condition.
BETWEE The BETWEEN operator is used to search for values that are within a set of
N values, given the minimum value and the maximum value.
EXISTS The EXISTS operator is used to search for the presence of a row in a specified
table that meets certain criteria.
IN The IN operator is used to compare a value to a list of literal values that have
been specified.
LIKE The LIKE operator is used to compare a value to similar values using wildcard
operators.

BY:- Ermias Israel


Page 21
Using Basic Structured Query Language

NOT The NOT operator reverses the meaning of the logical operator with which it is
used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.
OR The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause.
IS NULL The NULL operator is used to compare a value with a NULL value.
UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness
(no duplicates).

Syntax
SELECT [column_name | * | expression] [logical operator]
[column_name | * | expression .....]
FROM <table_name>
WHERE <expressions> [ logical operator |
arithmetic operator | ...] <expressions>;

For example: if you want to find the names of students who are studying either Maths or Science,
the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject = 'Maths' OR subject = 'Science'

For Example: To find the names of the students between the age 10 to 15 years, the query would
be like:
SELECT first_name, last_name, age
FROM student_details
WHERE age >= 10 AND age <= 15;

1.3.3.2.3 Arithmetical operators


Arithmetic operators perform mathematical operations on two expressions of one or more of the
data types of the numeric data type category.
Operato Description Example
r
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand a - b will give -10
operand
* Multiplication - Multiplies values on either side of the operator a * b will give
200
/ Division - Divides left hand operand by right hand operand b / a will give 2
% Modulus - Divides left hand operand by right hand operand b % a will give 0
and returns remainder

1.3.3.2.4Mathematical Functions and Operators

BY:- Ermias Israel


Page 22
Using Basic Structured Query Language

Mathematical operators are provided for many PostgreSQL types. For types without common
mathematical conventions for all possible permutations (e.g., date/time types) we describe the
actual behavior in subsequent sections.

Table 9-3 shows the available mathematical functions. In the table, dp indicates double precision.
Many of these functions are provided in multiple forms with different argument types. Except
where noted, any given form of a function returns the same data type as its argument. The
functions working with double precision data are mostly implemented on top of the host system's
C library; accuracy and behavior in boundary cases may therefore vary depending on the host
system.

Table 9-3. Mathematical Functions


Function Return Type Description Example Result
abs(x) (same as x) absolute value abs(-17.4) 17.4
cbrt(dp) dp cube root cbrt(27.0) 3
ceil(dp or (same as smallest integer not ceil(-42.8) -42
numeric) input) less than argument
ceiling(dp or (same as smallest integer not ceiling(-95.3) -95
numeric) input) less than argument
(alias for ceil)
degrees(dp) dp radians to degrees degrees(0.5) 28.64788975
65412
exp(dp or (same as exponential exp(1.0) 2.718281828
numeric) input) 45905
floor(dp or (same as largest integer not floor(-42.8) -43
numeric) input) greater than
argument
ln(dp or (same as natural logarithm ln(2.0) 0.693147180
numeric) input) 559945
log(dp or (same as base 10 logarithm log(100.0) 2
numeric) input)
log(b numeric logarithm to base b log(2.0, 64.0) 6.000000000
numeric, x 0
numeric)
mod(y, x) (same as remainder of y/x mod(9,4) 1
argument
types)
pi() dp "π" constant pi() 3.141592653
58979
power(a dp, b dp a raised to the power(9.0, 729
dp) power of b 3.0)
power(a numeric a raised to the power(9.0, 729
numeric, b power of b 3.0)
numeric)

BY:- Ermias Israel


Page 23
Using Basic Structured Query Language
radians(dp) dp degrees to radians radians(45.0) 0.785398163
397448
random() dp random value random()  
between 0.0 and 1.0
round(dp or (same as round to nearest round(42.4) 42
numeric) input) integer
round(v numeric round to s decimal round(42.4382, 42.44
numeric, s places 2)
int)
setseed(dp) int set seed for setseed(0.5482 1177314959
subsequent 3)
random() calls
sign(dp or (same as sign of the argument sign(-8.4) -1
numeric) input) (-1, 0, +1)
sqrt(dp or (same as square root sqrt(2.0) 1.414213562
numeric) input) 3731
trunc(dp or (same as truncate toward trunc(42.8) 42
numeric) input) zero
trunc(v numeric truncate to s trunc(42.4382, 42.43
numeric, s decimal places 2)
int)
width_bucket( int return the bucket to width_bucket(5 3
op numeric, which operand .35, 0.024,
b1 numeric, would be assigned 10.06, 5)
b2 numeric, in an equidepth
count int)
histogram with
count buckets, an
upper bound of b1,
and a lower bound
of b2

Finally, Table 9-4 shows the available trigonometric functions. All trigonometric functions take
arguments and return values of type double precision.

Table 9-4. Trigonometric Functions


Function Description
acos(x) inverse cosine
asin(x) inverse sine
atan(x) inverse tangent
atan2(x, y) inverse tangent of x/y
cos(x) cosine
cot(x) cotangent
sin(x) sine
tan(x) tangent

BY:- Ermias Israel


Page 24
Using Basic Structured Query Language

1.3.3.3FROM Clause
SQL FROM Syntax
SQL FROM clause allows us to specify table name (or view) that we want to use to retrieve
certain fields. The most basic syntax is below:
SELECT * FROM TableName

The FROM clause specifies the target table(s) for SELECT, UPDATE, and DELETE statements.
Example Syntax:
 FROM table [[AS] alias]
 FROM table1 [INNER|LEFT OUTER|RIGHT OUTER|FULL OUTER] JOIN table2 ON
join-criteria
 FROM table1 CROSS JOIN table2
 FROM (subquery) [AS] alias
 FROM TABLE(subquery) [AS] alias

1.3.3.4 Where Clause


The SQL WHERE clause is used to specify a condition while fetching the data from single table
or joining with multiple tables. If the given condition is satisfied then only it returns specific
value from the table. You would use WHERE clause to filter the records and fetching only
necessary records.

The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE,
DELETE statement, etc.

Syntax: The basic syntax of SELECT statement with WHERE clause is as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc.
Below examples would make this concept clear.

Example: Consider the CUSTOMERS table having the following records:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example which would fetch ID, Name and Salary fields from the CUSTOMERS
table where salary is greater than 2000:
SQL> SELECT ID, NAME, SALARY

BY:- Ermias Israel


Page 25
Using Basic Structured Query Language
FROM CUSTOMERS
WHERE SALARY > 2000;
This would produce the following result:
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS
table for a customer with name Hardik. Here, it is important to note that all the strings should be
given inside single quotes ('') where as numeric values should be given without any quote as in
above example:
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE NAME = 'Hardik';
This would produce the following result:
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 5 | Hardik | 8500.00 |
+----+----------+----------+

SQL TOP:-
The SQL TOP clause is used to fetch a TOP N number or X percent records from a table.
Note: All the databases do not support TOP clause. For example MySQL supports LIMIT
clause to fetch limited number of records and Oracle uses ROWNUM to fetch limited number of
records.
Syntax:
The basic syntax of TOP clause with SELECT statement would be as follows:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE [condition]
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example on SQL server, which would fetch top 3 records from CUSTOMERS
table:
BY:- Ermias Israel
Page 26
Using Basic Structured Query Language
SQL> SELECT TOP 3 * FROM CUSTOMERS;
This would produce the following result:
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
If you are using MySQL server, then here is an equivalent example:
SQL> SELECT * FROM CUSTOMERS
LIMIT 3;
This would produce the following result:
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
If you are using Oracle server, then here is an equivalent example:
SQL> SELECT * FROM CUSTOMERS
WHERE ROWNUM <= 3;

This would produce the following result:


+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+

1.3.3.5 Updating Tables


The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows
would be affected.
Syntax: The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.

Example: Consider the CUSTOMERS table having the following records:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
BY:- Ermias Israel
Page 27
Using Basic Structured Query Language
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would update ADDRESS for a customer whose ID is 6:
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
Now, CUSTOMERS table would have the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you
do not need to use WHERE clause and UPDATE query would be as follows:
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;

Now, CUSTOMERS table would have the following records:


+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+

1.3.3.6 Deleting New Rows


The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise all the
records would be deleted.

Syntax: The basic syntax of DELETE query with WHERE clause is as follows:
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example: Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |

BY:- Ermias Israel


Page 28
Using Basic Structured Query Language
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would DELETE a customer, whose ID is 6:
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;
Now, CUSTOMERS table would have the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to DELETE all the records from CUSTOMERS table, you do not need to use
WHERE clause and DELETE query would be as follows:
SQL> DELETE FROM CUSTOMERS;
Now, CUSTOMERS table would not have any record.
Like Operator
The SQL LIKE clause is used to compare a value to similar values using wildcard operators.
There are two wildcards used in conjunction with the LIKE operator:
 The percent sign (%)
 The underscore (_)
SQL Wildcard Characters
In SQL, wildcard characters are used with the SQL LIKE operator.
SQL wildcards are used to search for data within a table. 
With SQL, the wildcards are:
Wildcard Description
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist] or [!charlist] Matches only a character NOT specified
within the brackets

Syntax: The basic syntax of % and _ is as follows:


SELECT FROM table_name
WHERE column LIKE 'XXXX%'
or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'

BY:- Ermias Israel


Page 29
Using Basic Structured Query Language
or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here, XXXX could be
any numeric or string value.
Example: Here are number of examples showing WHERE part having different LIKE clause
with '%' and '_' operators:

Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200
WHERE SALARY LIKE Finds any values that have 200 in any position
'%200%'
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with a 3
WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and end with 3

Let us take a real example, consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would display all the records from CUSTOMERS table where
SALARY starts with 200:
SQL> SELECT * FROM CUSTOMERS
WHERE SALARY LIKE '200%';
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+

BY:- Ermias Israel


Page 30
Using Basic Structured Query Language

SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y helados Constitución 2222 D.F.
3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico
Taquería Moreno D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

IN Operator Example: The following SQL statement selects all customers with a City of
"Paris" or "London":
SELECT * FROM Customers
WHERE City IN ('Paris','London');

SQL BETWEEN Operator


The BETWEEN operator is used to select values within a range. The BETWEEN operators
select values within a range. The values can be numbers, text, or dates.
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example: The following SQL statement selects all products with a price BETWEEN 10 and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

NOT BETWEEN Operator Example: to display the products outside the range of the
previous example, use NOT BETWEEN:
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

BY:- Ermias Israel


Page 31
Using Basic Structured Query Language

BETWEEN Operator with IN Example: The following SQL statement selects all products
with a price BETWEEN 10 and 20, but products with a CategoryID of 1,2, or 3 should not be
displayed:
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);

BETWEEN Operator with Text Value Example: - The following SQL statement selects
all products with a ProductName beginning with any of the letter BETWEEN 'C' and 'M':
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';
NOT BETWEEN Operator with Text Value Example:-The following SQL statement
selects all products with a ProductName beginning with any of the letter NOT BETWEEN 'C'
and 'M':
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
Sample Table: Below is a selection from the "Orders" table:
OrderI CustomerID EmployeeID OrderDate ShipperID
D
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2

BETWEEN Operator with Date Value Example: - The following SQL statement selects
all orders with an OrderDate BETWEEN '04-July-1996' and '09-July-1996':
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;

SQL Constraints
Constraints are the rules enforced on data columns on table. These are used to limit the type of
data that can go into a table. This ensures the accuracy and reliability of the data in the database.
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.
Following are commonly used constraints available in SQL.
 NOT NULL Constraint: Ensures that a column cannot have NULL value.
 DEFAULT Constraint: Provides a default value for a column when none is specified.
 UNIQUE Constraint: Ensures that all values in a column are different.
 PRIMARY Key: Uniquely identified each rows/records in a database table.
 FOREIGN Key: Uniquely identified a rows/records in any another database table.

BY:- Ermias Israel


Page 32
Using Basic Structured Query Language

 CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.
 INDEX: Use to create and retrieve data from the database very quickly.
Constraints can be specified when a table is created with the CREATE TABLE statement or you
can use ALTER TABLE statement to create constraints even after the table is created.

NOT NULL Constraint


By default, a column can hold NULL values. If you do not want a column to have a NULL
value, then you need to define such constraint on this column specifying that NULL is now not
allowed for that column.
A NULL is not the same as no data, rather, it represents unknown data.

Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns, three of which, ID and NAME and AGE, specify not to accept NULLs:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

If CUSTOMERS table has already been created, then to add a NOT NULL constraint to
SALARY column in Oracle and MySQL, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL;

DEFAULT Constraint
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.

Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO
statement does not provide a value for this column, then by default this column would be set to
5000.00.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID));

If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY
column, you would write a statement similar to the following:

BY:- Ermias Israel


Page 33
Using Basic Structured Query Language
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;
Drop Default Constraint:
To drop a DEFAULT constraint, use the following SQL:
ALTER TABLE CUSTOMERS
ALTER COLUMN SALARY DROP DEFAULT;

UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the CUSTOMERS table, for example, you might want to prevent two or more people
from having identical age.

Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with
same age:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);
DROP a UNIQUE Constraint:
To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myUniqueConstraint;
If you are using MySQL, then you can use the following syntax:
ALTER TABLE CUSTOMERS
DROP INDEX myUniqueConstraint;

PRIMARY Key
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key.

BY:- Ermias Israel


Page 34
Using Basic Structured Query Language

If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Note: You would use these concepts while creating database tables.
Example: Here is the syntax to define ID attribute as a primary key in a CUSTOMERS table.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already
exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table was first
created).
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME));

To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
Delete Primary Key:
You can clear the primary key constraints from the table, Use Syntax:
ALTER TABLE CUSTOMERS DROP PRIMARY KEY ;

FOREIGN Key
A foreign key is a key used to link two tables together. This is sometimes called a referencing
key. Foreign Key is a column or a combination of columns whose values match a Primary Key in
a different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a
Foreign Key in the second table.
If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Example: Consider the structure of the two tables as follows: CUSTOMERS table:
CREATE TABLE CUSTOMERS(

BY:- Ermias Israel


Page 35
Using Basic Structured Query Language
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
ORDERS table:
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID));

If ORDERS table has already been created, and the foreign key has not yet been set, use the
syntax for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);

DROP a FOREIGN KEY Constraint:


To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS
DROP FOREIGN KEY;

CHECK Constraint
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.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, we add a CHECK with AGE column, so that you can not have any
CUSTOMER below 18 years:

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
BY:- Ermias Israel
Page 36
Using Basic Structured Query Language
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);
DROP a CHECK Constraint:
To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myCheckConstraint;

INDEX
The INDEX is used to create and retrieve data from the database very quickly. Index can be
created by using single or group of columns in a table. When index is created, it is assigned a
ROWID for each row before it sorts out the data.

Proper indexes are good for performance in large databases, but you need to be careful while
creating index. Selection of fields depends on what you are using in your SQL queries.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

Now, you can create index on single or multiple columns using the following syntax:
CREATE INDEX index_name
ON table_name ( column1, column2.....);
To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL syntax:
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
DROP an INDEX Constraint:
To drop an INDEX constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;

1.4. Combining Table Expressions


1.4.1 SQL Using 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.
Consider the following two tables, (a) CUSTOMERS table is as follows:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
BY:- Ermias Israel
Page 37
Using Basic Structured Query Language
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:


+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result:


+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be
used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be
used to join tables. However, the most common operator is the equal symbol.
SQL Join Types:
There are different types of joins available in SQL:
 INNER JOIN: returns rows when there is a match in both tables.
 LEFT JOIN: returns all rows from the left table, even if there are no matches in the right
table.
 RIGHT JOIN: returns all rows from the right table, even if there are no matches in the
left table.
 FULL JOIN: returns rows when there is a match in one of the tables.
 SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
 CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or
more joined tables.

1. INNER JOIN

BY:- Ermias Israel


Page 38
Using Basic Structured Query Language

The most frequently used and important of the joins is the INNER JOIN. They are also referred
to as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate. The query compares each row of table1 with each row
of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a result
row.
Syntax: The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;

Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:


+-----+---------------------+-------------+--------+
| OID | DATE | ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using INNER JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+

2. LEFT JOIN
BY:- Ermias Israel
Page 39
Using Basic Structured Query Language

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if the ON clause matches 0 (zero) records in right table, the join will
still return a row in the result, but with NULL in each column from right table.
This means that a left join returns all the values from the left table, plus matched values from the
right table or NULL in case of no matching join predicate.

Syntax: The basic syntax of LEFT JOIN is as follows:


SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_filed = table2.common_field;
Here given condition could be any given expression based on your requirement.
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:


+-----+---------------------+-------------+--------+
| OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using LEFT JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |

BY:- Ermias Israel


Page 40
Using Basic Structured Query Language
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+----------+--------+---------------------+

3. RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the
left table. This means that if the ON clause matches 0 (zero) records in left table, the join will
still return a row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from
the left table or NULL in case of no matching join predicate.

Syntax: The basic syntax of RIGHT JOIN is as follows:


SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_filed = table2.common_field;
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:


+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using RIGHT JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |

BY:- Ermias Israel


Page 41
Using Basic Structured Query Language
+------+----------+--------+---------------------+
4. FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches
on either side.
Syntax: The basic syntax of FULL JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;
Here given condition could be any given expression based on your requirement.
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using FULL JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |

BY:- Ermias Israel


Page 42
Using Basic Structured Query Language
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
If your Database does not support FULL JOIN like MySQL does not support FULL JOIN, then
you can use UNION ALL clause to combine two JOINS as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

5. SELF JOIN
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.

Syntax: The basic syntax of SELF JOIN is as follows:


SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Here, WHERE clause could be any given expression based on your requirement.

Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us join this table using SELF JOIN as follows:
SQL> SELECT a.ID, b.NAME, a.SALARY
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;
This would produce the following result:
+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |

BY:- Ermias Israel


Page 43
Using Basic Structured Query Language
| 1 | Hardik | 2000.00 |
| 2 | Hardik | 1500.00 |
| 3 | Hardik | 2000.00 |
| 4 | Hardik | 6500.00 |
| 6 | Hardik | 4500.00 |
| 1 | Komal | 2000.00 |
| 2 | Komal | 1500.00 |
| 3 | Komal | 2000.00 |
| 1 | Muffy | 2000.00 |
| 2 | Muffy | 1500.00 |
| 3 | Muffy | 2000.00 |
| 4 | Muffy | 6500.00 |
| 5 | Muffy | 8500.00 |
| 6 | Muffy | 4500.00 |
+----+----------+---------+
6. CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records
from the two or more joined tables. Thus, it equates to an inner join where the join-condition
always evaluates to True or where the join-condition is absent from the statement.
Syntax: The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:

----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:


+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using INNER JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS;

BY:- Ermias Israel


Page 44
Using Basic Structured Query Language

This would produce the following result:


+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | 3000 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1500 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1560 | 2009-11-20 00:00:00 |
| 1 | Ramesh | 2060 | 2008-05-20 00:00:00 |
| 2 | Khilan | 3000 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 2 | Khilan | 2060 | 2008-05-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 2060 | 2008-05-20 00:00:00 |
| 4 | Chaitali | 3000 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | 3000 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1500 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1560 | 2009-11-20 00:00:00 |
| 5 | Hardik | 2060 | 2008-05-20 00:00:00 |
| 6 | Komal | 3000 | 2009-10-08 00:00:00 |
| 6 | Komal | 1500 | 2009-10-08 00:00:00 |
| 6 | Komal | 1560 | 2009-11-20 00:00:00 |
| 6 | Komal | 2060 | 2008-05-20 00:00:00 |
| 7 | Muffy | 3000 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1500 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1560 | 2009-11-20 00:00:00 |
| 7 | Muffy | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+

1.4.2 SQL Using UNIONS, INTERSECTION and EXCEPT


1. UNIONS: the SQL UNION clause/operator is used to combine the results of two or more
SELECT statements without returning any duplicate rows. To use UNION, each SELECT must
have the same number of columns selected, the same number of column expressions, the same
data type, and have them in the same order, but they do not have to be the same length.

Syntax: The basic syntax of UNION is as follows:


SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here given condition could be any given expression based on your requirement.

BY:- Ermias Israel


Page 45
Using Basic Structured Query Language

Example: Consider the following two tables; (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+------+----------+--------+---------------------+
The UNION ALL Clause:
The UNION ALL operator is used to combine the results of two SELECT statements including
duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator.

Syntax: The basic syntax of UNION ALL is as follows:


SELECT column1 [, column2 ]
FROM table1 [, table2 ]

BY:- Ermias Israel


Page 46
Using Basic Structured Query Language
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here given condition could be any given expression based on your requirement.
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:


+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+

Now, let us join these two tables in our SELECT statement as follows:

SQL> SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |

BY:- Ermias Israel


Page 47
Using Basic Structured Query Language
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
2. INTERSECT: the SQL INTERSECT clause/operator is used to combine two SELECT
statements, but returns rows only from the first SELECT statement that are identical to a row in
the second SELECT statement. This means INTERSECT returns only common rows returned by
the two SELECT statements. Just as with the UNION operator, the same rules apply when using
the INTERSECT operator. MySQL does not support INTERSECT operator
Syntax: The basic syntax of INTERSECT is as follows:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here given condition could be any given expression based on your requirement.
Example: Consider the following two tables; (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
INTERSECT
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS

BY:- Ermias Israel


Page 48
Using Basic Structured Query Language
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+---------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+---------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Ramesh | 1560 | 2009-11-20 00:00:00 |
| 4 | kaushik | 2060 | 2008-05-20 00:00:00 |
+------+---------+--------+---------------------+

3. EXCEPT: 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. MySQL does not support EXCEPT operator.

Syntax: The basic syntax of EXCEPT is as follows:


SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here given condition could be any given expression based on your requirement.

Example: Consider the following two tables, (a) CUSTOMERS table is as follows:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

(b) Another table is ORDERS as follows:


+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |

BY:- Ermias Israel


Page 49
Using Basic Structured Query Language
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
EXCEPT
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+----+---------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+---------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+---------+--------+---------------------+

Alias Name
You can rename a table or a column temporarily by giving another name known as alias.
The use of table aliases means to rename a table in a particular SQL statement. The renaming is a
temporary change and the actual table name does not change in the database. The column aliases
are used to rename a table's columns for the purpose of a particular SQL query.
Syntax: The basic syntax of table alias is as follows:
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
The basic syntax of column alias is as follows:
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Example: Consider the following two tables; (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:

BY:- Ermias Israel


Page 50
Using Basic Structured Query Language
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, following is the usage of table alias:
SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT
FROM CUSTOMERS AS C, ORDERS AS O
WHERE C.ID = O.CUSTOMER_ID;
This would produce the following result:
+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Following is the usage of column alias:
SQL> SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
This would produce the following result:
+-------------+---------------+
| CUSTOMER_ID | CUSTOMER_NAME |
+-------------+---------------+
| 1 | Ramesh |
| 2 | Khilan |
| 3 | kaushik |
| 4 | Chaitali |
| 5 | Hardik |
| 6 | Komal |
| 7 | Muffy |
+-------------+---------------+

LO2Write SQL Statements that Use Functions


2.1 Removing Duplicate Rows with DISTINICT When two Rows are Equal
SQL ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on
one or more columns. Some database sorts query results in ascending order by default.
BY:- Ermias Israel
Page 51
Using Basic Structured Query Language

Syntax: The basic syntax of ORDER BY clause is as follows:


SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you
are using to sort, that column should be in column-list.

Example: Consider the CUSTOMERS table having the following records:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would sort the result in ascending order by NAME and
SALARY:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

This would produce the following result:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would sort the result in descending order by NAME:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

This would produce the following result:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |

BY:- Ermias Israel


Page 52
Using Basic Structured Query Language
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

SQL GROUP BY
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. The GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.
Syntax: The basic syntax of GROUP BY clause is given below.
The GROUP BY clause must follow the conditions in the WHERE clause and must precede the
ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Example: Consider the CUSTOMERS table is having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to know the total amount of salary on each customer, then GROUP BY query would
be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
This would produce the following result:
+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
| kaushik | 2000.00 |
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 2000.00 |
+----------+-------------+
Now, let us have following table where CUSTOMERS table has the following records with
duplicate names:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+

BY:- Ermias Israel


Page 53
Using Basic Structured Query Language
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now again, if you want to know the total amount of salary on each customer, then GROUP BY
query would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
This would produce the following result:
+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+

SQL DISTINCT Keyword


The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all
the duplicate records and fetching only unique records. There may be a situation when you have
multiple duplicate records in a table. While fetching such records, it makes more sense to fetch
only unique records instead of fetching duplicate records.

Syntax: The basic syntax of DISTINCT keyword to eliminate duplicate records is as


follows:
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Example: Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

First, let us see how the following SELECT query returns duplicate salary records:
SQL> SELECT SALARY FROM CUSTOMERS
ORDER BY SALARY;

BY:- Ermias Israel


Page 54
Using Basic Structured Query Language

This would produce the following result where salary 2000 is coming twice which is a duplicate
record from the original table.
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
Now, let us use DISTINCT keyword with the above SELECT query and see the result:
SQL> SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY;
This would produce the following result where we do not have any duplicate entry:
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
2.2 Introduction to Functions
2.2.1 Date Functions
Date and Time Functions in SQL Server 2008
GETDATE()
The GETDATE() function returns the current date and time from the SQL Server.
Syntax: select GETDATE()

Example: The following SELECT statement:


SELECT GETDATE() AS CurrentDateTime
Will result in something like this:
CurrentDateTime
2008-11-11 12:45:34.243

Note: The time part above goes all the way to milliseconds.
Example: - The following SQL creates an "Orders" table with a datetime column (OrderDate):
CREATE TABLE Orders
( OrderId int NOT NULL PRIMARY KEY,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE())

BY:- Ermias Israel


Page 55
Using Basic Structured Query Language

Notice that the OrderDate column specifies GETDATE() as the default value. As a result, when
you insert a row into the table, the current date and time are automatically inserted into the
column.
Now we want to insert a record into the "Orders" table:
INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese')

The "Orders" table will now look something like this:


OrderI ProductName OrderDate
d
1 Jarlsberg Cheese 2008-11-11 13:23:44.657

SYSDATETIME()
This function works the same as GETDATE(); it returns date and time. The difference in both
functions is that SYSDATETIME returns a higher level of precision and also returns the
newer datetime2 data type. 
select SYSDATETIME()
DAY()
This function returns an integer representing the day part of the specified date.
select DAY(<date>)
MONTH()
This function returns an integer representing the month part of the specified date.
select MONTH(<date>)
YEAR()
This function returns an integer representing the year part of the specified date.
select YEAR(<date>)

DATEADD()
The DATEADD() function adds or subtracts a specified time interval from a date.
Syntax: - Select DATEADD(datepart,number,date)

Where date is a valid date expression and number is the number of interval you want to add. The
number can either be positive, for dates in the future, or negative, for dates in the past.
datepart can be one of the following:

Example:-Assume we have the following "Orders" table:


OrderI ProductName OrderDate
d
1 Jarlsberg Cheese 2008-11-11 13:23:44.657
Now we want to add 45 days to the "OrderDate", to find the payment date.
We use the following SELECT statement:
SELECT OrderId,DATEADD(day,45,OrderDate) AS OrderPayDate
FROM Orders
Result:

BY:- Ermias Israel


Page 56
Using Basic Structured Query Language

OrderId OrderPayDate
1 2008-12-26 13:23:44.657
DATEDIFF()
This function returns the difference between two specified dates in a specified unit of time.
 DATEDIFF(<datepart>, <startdate>, <enddate>)
Syntax:- select DATEDIFF(datepart,startdate,enddate)

Where startdate and enddate are valid date expressions and datepart can be one of the following:

Example: - Now we want to get the number of days between two dates.
We use the following SELECT statement:
SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate

Result:
DiffDate
61

Example:-Now we want to get the number of days between two dates (notice that the second
date is "earlier" than the first date, and will result in a negative number).

We use the following SELECT statement:


SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDate
Result:
DiffDate
-61

DATENAME()
This function returns a string representing the name of the specified datepart of the specified
date.
select DATENAME(<datepart>, <date>)

DATEPART()
The DATEPART() function is used to return a single part of a date/time, such as year, month,
day, hour, minute, etc.

Syntax: - select DATEPART(datepart,date)
Where date is a valid date expression and datepart can be one of the following:
datepart Abbreviation week wk, ww
year yy, yyyy weekday dw, w
quarter qq, q hour hh
month mm, m minute mi, n
dayofyear dy, y second ss, s
day dd, d millisecond ms
BY:- Ermias Israel
Page 57
Using Basic Structured Query Language

microsecon mcs nanosecond ns


d

Example: - Assume we have the following "Orders" table:


OrderI ProductName OrderDate
d
1 Jarlsberg Cheese 2008-11-11 13:23:44.657

The following SELECT statement:


SELECT DATEPART(yyyy,OrderDate) AS OrderYear,
DATEPART(mm,OrderDate) AS OrderMonth,
DATEPART(dd,OrderDate) AS OrderDay,
FROM Orders
WHERE OrderId=1

Will result in this:


OrderYear OrderMonth OrderDay
2008 11 11

CONVERT()
The CONVERT() function is a general function that converts an expression of one data type to
another. The CONVERT() function can be used to display date/time data in different formats.
Syntax:- CONVERT(data_type(length),expression,style)

Value Description
data_type(length) Specifies the target data type (with an optional length)
expression Specifies the value to be converted
style Specifies the output format for the date/time

The table below represent the style values for datetime or smalldatetime conversion to character
data:
Value Value Input/Output Standard
(century yy) (century yyyy)
- 0 or 100 mon dd yyyy hh:miAM (or PM) Default
1 101 mm/dd/yy USA
2 102 yy.mm.dd ANSI
3 103 dd/mm/yy British/French
4 104 dd.mm.yy German
5 105 dd-mm-yy Italian
6 106 dd mon yy  
7 107 Mon dd, yy  
8 108 hh:mm:ss  
- 9 or 109 mon dd yyyy hh:mi:ss:mmmAM (or PM) Default+millisec
10 110 mm-dd-yy USA

BY:- Ermias Israel


Page 58
Using Basic Structured Query Language

11 111 yy/mm/dd Japan


12 112 yymmdd ISO
- 13 or 113 dd mon yyyy hh:mi:ss:mmm (24h)  
14 114 hh:mi:ss:mmm (24h)  
- 20 or 120 yyyy-mm-dd hh:mi:ss (24h)  
- 21 or 121 yyyy-mm-dd hh:mi:ss.mmm (24h)  
- 126 yyyy-mm-ddThh:mi:ss.mmm (no spaces) ISO8601
- 130 dd mon yyyy hh:mi:ss:mmmAM Hijiri
- 131 dd/mm/yy hh:mi:ss:mmmAM Hijiri

Example:- The following script uses the CONVERT() function to display different formats. We
will use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)

The result would look something like this:


Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243

2.2.2 Aggregation Function


SQL aggregate functions return a single value, calculated from values in a column.
1. SQL COUNT Function
SQL COUNT Function is the simplest function and very useful in counting the number of
records, which are expected to be returned by a SELECT statement.
To understand COUNT function, consider an employee_tbl table, which is having the following
records:
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |

BY:- Ermias Israel


Page 59
Using Basic Structured Query Language
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now suppose based on the above table you want to count total number of rows in this table, then
you can do it as follows:

SQL>SELECT COUNT(*) FROM employee_tbl ;


+----------+
| COUNT(*) |
+----------+
| 7 |
+----------+
1 row in set (0.01 sec)
Similarly, if you want to count the number of records for Zara, then it can be done as follows:
SQL>SELECT COUNT(*) FROM employee_tbl
-> WHERE name="Zara";
+----------+
| COUNT(*) |
+----------+
| 2 |
+----------+
1 row in set (0.04 sec)
NOTE: All the SQL queries are case insensitive, so it does not make any difference if you give
ZARA or Zara in WHERE CONDITION.

2. SQL MAX Function


SQL MAX function is used to find out the record with maximum value among a record set.
To understand MAX function, consider an employee_tbl table, which is having the following
records:
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)

Now suppose based on the above table you want to fetch maximum value of daily_typing_pages,
then you can do so simply using the following command:

SQL> SELECT MAX(daily_typing_pages)


-> FROM employee_tbl;
+-------------------------+
| MAX(daily_typing_pages) |
+-------------------------+
| 350 |

BY:- Ermias Israel


Page 60
Using Basic Structured Query Language
+-------------------------+
1 row in set (0.00 sec)
You can find all the records with maxmimum value for each name using GROUP BY clause as
follows:
SQL> SELECT id, name, MAX(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;

+------+------+-------------------------+
| id | name | MAX(daily_typing_pages) |
+------+------+-------------------------+
| 3 | Jack | 170 |
| 4 | Jill | 220 |
| 1 | John | 250 |
| 2 | Ram | 220 |
| 5 | Zara | 350 |
+------+------+-------------------------+
5 rows in set (0.00 sec)
You can use MIN Function along with MAX function to find out minimum value as well. Try
out the following example:

SQL> SELECT MIN(daily_typing_pages) least,


MAX(daily_typing_pages) max
-> FROM employee_tbl;
+-------+------+
| least | max |
+-------+------+
| 100 | 350 |
+-------+------+
1 row in set (0.01 sec)

3. SQL MIN Function


SQL MIN function is used to find out the record with minimum value among a record set.
To understand MIN function, consider an employee_tbl table, which is having the following
records:
Now suppose based on the above table you want to fetch minimum value of daily_typing_pages,
then you can do so simply using the following command:

SQL> SELECT MIN(daily_typing_pages)


-> FROM employee_tbl;
+-------------------------+
| MIN(daily_typing_pages) |
+-------------------------+
| 100 |
+-------------------------+
1 row in set (0.00 sec)
You can find all the records with minimum value for each name using GROUP BY clause as
follows:
SQL> SELECT id, name, work_date, MIN(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;
+------+------+-------------------------+

BY:- Ermias Israel


Page 61
Using Basic Structured Query Language
| id | name | MIN(daily_typing_pages) |
+------+------+-------------------------+
| 3 | Jack | 100 |
| 4 | Jill | 220 |
| 1 | John | 250 |
| 2 | Ram | 220 |
| 5 | Zara | 300 |
+------+------+-------------------------+
5 rows in set (0.00 sec)
You can use MIN Function along with MAX function to find out minimum value as well. Try
out the following example:

SQL> SELECT MIN(daily_typing_pages) least,


-> MAX(daily_typing_pages) max
-> FROM employee_tbl;

+-------+------+
| least | max |
+-------+------+
| 100 | 350 |
+-------+------+
1 row in set (0.01 sec)

4. SQL AVG Function


SQL AVG function is used to find out the average of a field in various records.
To understand AVG function, consider an employee_tbl table, which is having the following
records:
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)

Now suppose based on the above table you want to calculate average of all the
dialy_typing_pages, then you can do so by using the following command:
SQL> SELECT AVG(daily_typing_pages)
-> FROM employee_tbl;
+-------------------------+
| AVG(daily_typing_pages) |
+-------------------------+
| 230.0000 |
+-------------------------+
1 row in set (0.03 sec)

BY:- Ermias Israel


Page 62
Using Basic Structured Query Language

You can take average of various records set using GROUP BY clause. Following example will
take average all the records related to a single person and you will have average typed pages by
every person.

SQL> SELECT name, AVG(daily_typing_pages)


-> FROM employee_tbl GROUP BY name;

+------+-------------------------+
| name | AVG(daily_typing_pages) |
+------+-------------------------+
| Jack | 135.0000 |
| Jill | 220.0000 |
| John | 250.0000 |
| Ram | 220.0000 |
| Zara | 325.0000 |
+------+-------------------------+
5 rows in set (0.20 sec)

5. SQL SUM Function


SQL SUM function is used to find out the sum of a field in various records.
To understand SUM function, consider an employee_tbl table, which is having the following
records:
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)

Now suppose based on the above table you want to calculate total of all the dialy_typing_pages,
then you can do so by using the following command:
SQL> SELECT SUM(daily_typing_pages)
-> FROM employee_tbl;
+-------------------------+
| SUM(daily_typing_pages) |
+-------------------------+
| 1610 |
+-------------------------+
1 row in set (0.00 sec)
You can take sum of various records set using GROUP BY clause. Following example will sum
up all the records related to a single person and you will have total typed pages by every person.
SQL> SELECT name, SUM(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;
BY:- Ermias Israel
Page 63
Using Basic Structured Query Language
+------+-------------------------+
| name | SUM(daily_typing_pages) |
+------+-------------------------+
| Jack | 270 |
| Jill | 220 |
| John | 250 |
| Ram | 220 |
| Zara | 650 |
+------+-------------------------+
5 rows in set (0.17 sec)
6. SQL CONCAT Function
SQL CONCAT function is used to concatenate two strings to form a single string.
To understand CONCAT function in more detail, consider an employee_tbl table, which is
having the following records:

SQL> SELECT * FROM employee_tbl;


+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)

Now suppose based on the above table you want to concatenate all the names employee ID and
work_date, then you can do it using the following command:

SQL> SELECT CONCAT(id, name, work_date)


-> FROM employee_tbl;
+-----------------------------+
| CONCAT(id, name, work_date) |
+-----------------------------+
| 1John2007-01-24 |
| 2Ram2007-05-27 |
| 3Jack2007-05-06 |
| 3Jack2007-04-06 |
| 4Jill2007-04-06 |
| 5Zara2007-06-06 |
| 5Zara2007-02-06 |
+-----------------------------+
7 rows in set (0.00 sec)

BY:- Ermias Israel


Page 64
Using Basic Structured Query Language

LO3 Write SQL Statements that Use Aggregation and Filtering


3.1 Aggregating Data by Multiple columns using “group by”
Aggregate functions often need an added GROUP BY statement.
The GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

In this tutorial we will use the well-known Northwind sample database.


Below is a selection from the "Orders" table:
OrderI CustomerI EmployeeID OrderDate ShipperID
D D
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2

And a selection from the "Shippers" table:


ShipperID ShipperName Phone
1 Speedy Express (503) 555-9831
2 United Package (503) 555-3199
3 Federal (503) 555-9931
Shipping

And a selection from the "Employees" table:


EmployeeI LastNam FirstName BirthDate Photo Notes
D e
1 Davolio Nancy 1968-12-08 EmpID1.pic Education includes a BA....
2 Fuller Andrew 1952-02-19 EmpID2.pic Andrew received his BTS....
3 Leverling Janet 1963-08-30 EmpID3.pic Janet has a BS degree....

SQL GROUP BY Example


Now we want to find the number of orders sent by each shipper.

BY:- Ermias Israel


Page 65
Using Basic Structured Query Language

The following SQL statement counts as orders grouped by shippers:


SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;

3.2 Sorting Aggregated Data in the Query Output


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on
one or more columns. Some database sorts query results in ascending order by default.

Syntax: The basic syntax of ORDER BY clause which would be used to sort result in
ascending or descending order is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you
are using to sort, that column should be in column-list.
Example: Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would sort the result in ascending order by NAME and
SALARY:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

This would produce the following result:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would sort the result in descending order by NAME:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

BY:- Ermias Israel


Page 66
Using Basic Structured Query Language

This would produce the following result:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+
To fetch the rows with own preferred order, the SELECT query would as follows:
SQL> SELECT * FROM CUSTOMERS
ORDER BY (CASE ADDRESS
WHEN 'DELHI' THEN 1
WHEN 'BHOPAL' THEN 2
WHEN 'KOTA' THEN 3
WHEN 'AHMADABAD' THEN 4
WHEN 'MP' THEN 5
ELSE 100 END) ASC, ADDRESS DESC;

This would produce the following result:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
This will sort customers by ADDRESS in your ownoOrder of preference first and in a natural
order for the remaining addresses. Also remaining Addresses will be sorted in the reverse alpha
order.

3.3 Filtering Aggregated Data using the “Having” Clause


The HAVING clause enables you to specify conditions that filter which group results appear in
the final results. The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY clause.

Syntax: The following is the position of the HAVING clause in a query:


SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

BY:- Ermias Israel


Page 67
Using Basic Structured Query Language

The HAVING clause must follow the GROUP BY clause in a query and must also precede the
ORDER BY clause if used. The following is the syntax of the SELECT statement, including the
HAVING clause:
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

Example: Consider the CUSTOMERS table having the following records:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example, which would display record for which similar age count would be
more than or equal to 2:
SQL > SELECT *
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;
This would produce the following result:
+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
+----+--------+-----+---------+---------+

BY:- Ermias Israel


Page 68
Using Basic Structured Query Language

LO4 Write and Execute SQL Queries


4.1 Single and Nested Queries
A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause. A subquery is used to return data that will be used in the main query
as a condition to further restrict the data to be retrieved. Subqueries can be used with the
SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >,
>=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
 An ORDER BY cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the ORDER
BY in a subquery.
 Subqueries that return more than one row can only be used with multiple value operators,
such as the IN operator.
 The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery; however, the BETWEEN
operator can be used within the subquery.

Subqueries with the SELECT Statement:


Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example: Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
BY:- Ermias Israel
Page 69
Using Basic Structured Query Language
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check following subquery with SELECT statement:
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Subqueries with the INSERT Statement:


Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
The basic syntax is as follows:
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

Example: Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table.


Now to copy complete CUSTOMERS table into CUSTOMERS_BKP, following is the syntax:
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

Subqueries with the UPDATE Statement:


The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows:
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME

BY:- Ermias Israel


Page 70
Using Basic Structured Query Language
FROM TABLE_NAME)
[ WHERE) ]

Example: Assuming, we have CUSTOMERS_BKP table available which is backup of


CUSTOMERS table.
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27:
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );

This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Subqueries with the DELETE Statement:


The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows:
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]

Example: Assuming, we have CUSTOMERS_BKP table available which is backup of


CUSTOMERS table.
Following example deletes records from CUSTOMERS table for all the customers whose AGE
is greater than or equal to 27:
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE > 27 );

This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+

BY:- Ermias Israel


Page 71
Using Basic Structured Query Language
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Using Subqueries to solve Queries


A subquery is best defined as a query within a query. Subqueries enable you to write queries that
select data rows for criteria that are actually developed while the query is executing at run time.
More formally, it is the use of a SELECT statement inside one of the clauses of another SELECT
statement. n fact, a subquery can be contained inside another subquery, which is inside another
subquery, and so forth. A subquery can also be nested inside INSERT, UPDATE, and DELETE
statements. Subqueries must be enclosed within parentheses.

A subquery can be used any place where an expression is allowed providing it returns a single
value. This means that a subquery that returns a single value can also be listed as an object in a
FROM clause listing. This is termed an inline view because when a subquery is used as part of a
FROM clause, it is treated like a virtual table or view. Subquery can be placed either in FROM
clause, WHERE clause or HAVING clause of the main query.

Oracle allows a maximum nesting of 255 subquery levels in a WHERE clause. There is no limit
for nesting subqueries expressed in a FROM clause.In practice, the limit of 255 levels is not
really a limit at all because it is rare to encounter subqueries nested beyond three or four levels.

A subquery SELECT statement is very similar to the SELECT statement used to begin a regular
or outer query.The complete syntax of a subquery is:

( SELECT [DISTINCT] subquery_select_parameter


FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ] ...]
[HAVING search_conditions] )

Types of Subqueries
Single Row Sub Query: Sub query which returns single row output. They mark the usage of
single row comparison operators, when used in WHERE conditions.

BY:- Ermias Israel


Page 72
Using Basic Structured Query Language

Multiple row sub query: Sub query returning multiple row output. They make use of multiple
row comparison operators like IN, ANY, ALL. There can be sub queries returning multiple
columns also.

Correlated Sub Query: Correlated subqueries depend on data provided by the outer query.This
type of subquery also includes subqueries that use the EXISTS operator to test the existence of
data rows satisfying specified criteria.

Single Row Sub Query


A single-row subquery is used when the outer query's results are based on a single, unknown
value. Although this query type is formally called "single-row," the name implies that the query
returns multiple columns-but only one row of results. However, a single-row subquery can return
only one row of results consisting of only one column to the outer query.

In the below SELECT query, inner SQL returns only one row i.e. the minimum salary for the
company. It in turn uses this value to compare salary of all the employees and displays only
those, whose salary is equal to minimum salary.

SELECT first_name, salary, department_id


FROM employees
WHERE salary = (SELECT MIN (salary)
FROM employees);

A HAVING clause is used when the group results of a query need to be restricted based on some
condition. If a subquery's result must be compared with a group function, you must nest the inner
query in the outer query's HAVING clause.

SELECT department_id, MIN (salary)


FROM employees
GROUP BY department_id
HAVING MIN (salary) < (SELECT AVG (salary)
FROM employees)

Multiple Row Sub Query


Multiple-row subqueries are nested queries that can return more than one row of results to the
parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING
clauses. Since it returns multiple rows,it must be handled by set comparison operators (IN, ALL,
ANY).While IN operator holds the same meaning as discussed in earlier chapter, ANY operator
compares a specified value to each value returned by the sub query while ALL compares a value
to every value returned by a sub query.

Below query shows the error when single row sub query returns multiple rows.

SELECT first_name, department_id


FROM employees
WHERE department_id = (SELECT department_id
BY:- Ermias Israel
Page 73
Using Basic Structured Query Language
FROM employees
WHERE LOCATION_ID = 100)
department_id = (select
*
ERROR at line 4:
ORA-01427: single-row subquery returns more than one row

Usage of Multiple Row operators


 [> ALL] More than the highest value returned by the subquery

 [< ALL] Less than the lowest value returned by the subquery

 [< ANY] Less than the highest value returned by the subquery

 [> ANY] More than the lowest value returned by the subquery

 [= ANY] Equal to any value returned by the subquery (same as IN)

Above SQL can be rewritten using IN operator like below.

SELECT first_name, department_id


FROM employees
WHERE department_id IN (SELECT department_id
FROM departments
WHERE LOCATION_ID = 100)

Note in the above query, IN matches department ids returned from the sub query,compares it
with that in the main query and returns employee's name who satisfy the condition. A join would
be better solution for above query, but for purpose of illustration, sub query has been used in it.

Correlated Sub Query


As opposed to a regular subquery, where the outer query depends on values provided by the
inner query,a correlated subquery is one where the inner query depends on values provided by
the outer query. This means that in a correlated subquery,the inner query is executed repeatedly,
once for each row that might be selected by the outer query.

Correlated subqueries can produce result tables that answer complex management questions.

Consider the below SELECT query. Unlike the subqueries previously considered, the subquery
in this SELECT statement cannot be resolved independently of the main query. Notice that the
outer query specifies that rows are selected from the employee table with an alias name of e1.
The inner query compares the employee department number column (DepartmentNumber) of the
employee table with alias e2 to the same column for the alias table name e1.

SELECT EMPLOYEE_ID, salary, department_id


FROM employees E
BY:- Ermias Israel
Page 74
Using Basic Structured Query Language
WHERE salary > (SELECT AVG(salary)
FROM EMP T
WHERE E.department_id = T.department_id)

Multiple Column Sub Query


A multiple-column subquery returns more than one column to the outer query and can be listed
in the outer query’s FROM, WHERE, or HAVING clause. For example, the following below
query shows the employee's historical details for the ones whose current salary is in range of
1000 and 2000 and working in department 10 or 20.
SELECT first_name, job_id, salary
FROM emp_history
WHERE (salary, department_id) in (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000
AND department_id BETWEEN 10 and 20)
ORDER BY first_name;

When a multiple-column subquery is used in the outer query's FROM clause, it creates a
temporary table that can be referenced by other clauses of the outer query. This temporary table
is more formally called an inline view. The subquery's results are treated like any other table in
the FROM clause. If the temporary table contains grouped data, the grouped subsets are treated
as separate rows of data in a table. Consider the FROM clause in the below query. The inline
view formed by the subquery is the data source for the main query.

SELECT *
FROM (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000);

4.2 Views
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from
one or many tables which depend on the written SQL query to create a view.
Views, which are kind of virtual tables, allow users to do the following:
 Structure data in a way that users or classes of users find natural or intuitive.
 Restrict access to the data such 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.

4.2.1 Creating Views:


Database views are created using the CREATE VIEW statement. Views can be created from a
single table, multiple tables, or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows:
BY:- Ermias Israel
Page 75
Using Basic Structured Query Language
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in very similar way as you use them
in normal SQL SELECT query.
Example: Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, following is the example to create a view from CUSTOMERS table. This view would be
used to have customer name and age from CUSTOMERS table:
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;

Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table.
Following is the example:
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result:
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+

The WITH CHECK OPTION:


The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH
CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the
view definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following is an example of creating same view CUSTOMERS_VIEW with the WITH
CHECK OPTION:
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
BY:- Ermias Israel
Page 76
Using Basic Structured Query Language
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the
view's AGE column, because the view is defined by data that does not have a NULL value in the
AGE column.

Updating a View:
A view can be updated under certain conditions:
 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 subqueries.
 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 a view. Following is an
example to update the age of Ramesh:
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name='Ramesh';
This would ultimately update the base table CUSTOMERS and same would reflect in the view
itself. Now, try to query base table, and SELECT statement would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

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.
Here we can not insert rows in CUSTOMERS_VIEW because we have not included all the NOT
NULL columns in this view, otherwise you can insert rows in a view in similar way as you insert
them in a table.
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.

BY:- Ermias Israel


Page 77
Using Basic Structured Query Language

Following is an example to delete a record having AGE= 22.


SQL > DELETE FROM CUSTOMERS_VIEW
WHERE age = 22;

This would ultimately delete a row from the base table CUSTOMERS and same would reflect in
the view itself. Now, try to query base table, and SELECT statement would produce the
following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
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 as given below:
DROP VIEW view_name;
Following is an example to drop CUSTOMERS_VIEW from CUSTOMERS table:
DROP VIEW CUSTOMERS_VIEW;

BY:- Ermias Israel


Page 78

You might also like