SQL Tutorials Guide by Tutorialspoint 1661697501
SQL Tutorials Guide by Tutorialspoint 1661697501
i
SQL
This tutorial will give you a quick start to SQL. It covers most of the topics required for a
basic understanding of SQL and to get a feel of how it works.
Audience
This tutorial is prepared for beginners to help them understand the basic as well as the
advanced concepts related to SQL languages. This tutorial will give you enough
understanding on the various components of SQL along with suitable examples.
Prerequisites
Before you start practicing with various types of examples given in this tutorial, I am
assuming that you are already aware about what a database is, especially the RDBMS and
what is a computer programming language.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
SQL
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Compile/Execute SQL Programs ....................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
1. SQL ─ O er ie ......................................................................................................................................... 1
What is SQL? .................................................................................................................................................... 1
SQL Process ..................................................................................................................................................... 2
SQL Commands................................................................................................................................................ 2
ii
SQL
iv
1. SQL ─ Overview SQL
What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating
and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational Database
Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres
and SQL Server use SQL as their standard database language.
Why SQL?
SQL is widely popular because it offers the following advantages:
Allows users to define the data in a database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries &
pre-compilers.
1978 – IBM worked to develop Codd's ideas and released a product named
System/R.
1986 – IBM developed the first prototype of relational database and standardized
by ANSI. The first relational database was released by Relational Software which
later came to be known as Oracle.
1
SQL
SQL Process
When you are executing an SQL command for any RDBMS, the system determines the
best way to carry out your request and SQL engine figures out how to interpret the task.
There are various components included in this process.
Query Dispatcher
Optimization Engines
Classic Query Engine
SQL Query Engine, etc.
A classic query engine handles all the non-SQL queries, but a SQL query engine won't
handle logical files.
SQL Commands
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into the following
groups based on their nature:
2
SQL
Command Description
Command Description
Command Description
3
2. SQL ─ RDBMS Concepts SQL
What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL,
and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
What is a table?
The data in an RDBMS is stored in database objects which are called as tables. This table
is basically a collection of related data entries and it consists of numerous columns and
rows.
Remember, a table is the most common and simplest form of data storage in a relational
database. The following program is an example of a 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 |
+----+----------+-----+-----------+----------+
What is a field?
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS
table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every
record in the table.
4
SQL
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
What is a column?
A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents location
description and would be as shown below:
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+
It is very important to understand that a NULL value is different than a zero value or a
field that contains spaces. A field with a NULL value is the one that has been left blank
during a record creation.
SQL Constraints
Constraints are the rules enforced on data columns on a 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 can either be column level or table level. Column level constraints are applied
only to one column whereas, table level constraints are applied to the entire table.
Following are some of the most commonly used constraints available in SQL:
5
SQL
NOT NULL Constraint: Ensures that a column cannot have a NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all the values in a column are different.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX: Used to create and retrieve data from the database very quickly.
Data Integrity
The following categories of data integrity exist with each RDBMS:
Domain Integrity: Enforces valid entries for a given column by restricting the
type, the format, or the range of values.
Referential integrity: Rows cannot be deleted, which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall
into entity, domain or referential integrity.
Database Normalization
Database normalization is the process of efficiently organizing data in a database. There
are two reasons of this normalization process:
Eliminating redundant data. For example, storing the same data in more than one
table.
Both these reasons are worthy goals as they reduce the amount of space a database
consumes and ensures that data is logically stored. Normalization consists of a series of
guidelines that help guide you in creating a good database structure.
Normalization guidelines are divided into normal forms; think of a form as the format or
the way a database structure is laid out. The aim of normal forms is to organize the
database structure, so that it complies with the rules of first normal form, then second
normal form and finally the third normal form.
It is your choice to take it further and go to the fourth normal form, fifth normal form and
so on, but in general, the third normal form is more than enough.
6
SQL
Define the data items required, because they become the columns in a table.
For example, you put all the columns relating to locations of meetings in the Location
table, those relating to members in the MemberDetails table and so on.
So, if we populate this table for a single customer having multiple orders, then it would be
something as shown below:
But as per the 1NF, we need to ensure that there are no repeating groups of data. So, let
us break the above table into two parts and then join them using a key as shown in the
following program:
7
SQL
CUSTOMERS Table
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
);
ORDERS Table
CREATE TABLE ORDERS(
ID INT NOT NULL,
CUSTOMER_ID INT NOT NULL,
ORDERS VARCHAR(155),
PRIMARY KEY (ID)
);
ID CUSTOMER_ID ORDERS
8
SQL
Consider a customer-order relation and you want to store customer ID, customer name,
order ID and order detail and the date of purchase:
This table is in the first normal form; in that it obeys all the rules of the first normal form.
In this table, the primary key consists of the CUST_ID and the ORDER_ID. Combined, they
are unique assuming the same customer would hardly order the same thing.
However, the table is not in the second normal form because there are partial
dependencies of primary keys and columns. CUST_NAME is dependent on CUST_ID and
there's no real link between a customer's name and what he purchased. The order detail
and purchase date are also dependent on the ORDER_ID, but they are not dependent on
the CUST_ID, because there is no link between a CUST_ID and an ORDER_DETAIL or their
SALE_DATE.
To make this table comply with the second normal form, you need to separate the columns
into three tables.
First, create a table to store the customer details as shown in the code block below:
The next step is to create a table to store the details of each order:
9
SQL
Finally, create a third table storing just the CUST_ID and the ORDER_ID to keep a track
of all the orders for a customer:
The dependency of these non-primary fields is between the data. For example, in the
following table – the street name, city and the state are unbreakably bound to their zip
code.
The dependency between the zip code and the address is called as a transitive dependency.
To comply with the third normal form, all you need to do is to move the Street, City and
the State fields into their own table, which you can call as the Zip Code table.
The advantages of removing transitive dependencies are mainly two-fold. First, the
amount of data duplication is reduced and therefore your database becomes smaller.
The second advantage is data integrity. When duplicated data changes, there is a big risk
of updating only some of the data, especially if it is spread out in many different places in
the database.
For example, if the address and the zip code data were stored in three or four different
tables, then any changes in the zip codes would need to ripple out to every record in those
three or four tables.
11
3. SQL ─ RDBMS Databases SQL
There are many popular RDBMS available to work with. This tutorial gives a brief overview
of some of the most popular RDBMS’s. This would help you to compare their basic features.
MySQL
MySQL is an open source SQL database, which is developed by a Swedish company –
MySQL AB. MySQL is pronounced as "my ess-que-ell," in contrast with SQL, pronounced
"sequel."
MySQL is supporting many different platforms including Microsoft Windows, the major
Linux distributions, UNIX, and Mac OS X.
MySQL has free and paid versions, depending on its usage (non-commercial/commercial)
and features. MySQL comes with a very fast, multi-threaded, multi-user and robust SQL
database server.
History
Development of MySQL by Michael Widenius & David Axmark beginning in 1994.
Windows Version was released on the 8th January 1998 for Windows 95 and NT.
Version 3.23: beta from June 2000, production release January 2001.
Version 4.0: beta from August 2002, production release March 2003 (unions).
Version 4.01: beta from August 2003, Jyoti adopts MySQL for database tracking.
Version 4.1: beta from June 2004, production release October 2004.
Version 5.0: beta from March 2005, production release October 2005.
Features
High Performance.
High Availability.
Management Ease.
MS SQL Server
MS SQL Server is a Relational Database Management System developed by Microsoft Inc.
Its primary query languages are:
T-SQL
ANSI SQL
History
1987 - Sybase releases SQL Server for UNIX.
1989 - Microsoft, Sybase, and Aston-Tate release SQL Server 1.0 for OS/2.
1990 - SQL Server 1.1 is released with support for Windows 3.0 clients.
2001 - Microsoft releases XML for SQL Server Web Release 1 (download).
2002 - Microsoft releases SQLXML 2.0 (renamed from XML for SQL Server).
Features
High Performance
High Availability
Database mirroring
Database snapshots
CLR integration
Service Broker
DDL triggers
Ranking functions
XML integration
TRY...CATCH
Database Mail
13
SQL
ORACLE
It is a very large multi-user based database management system. Oracle is a relational
database management system developed by 'Oracle Corporation'.
Oracle works to efficiently manage its resources, a database of information among the
multiple clients requesting and sending data in the network.
It is an excellent database server choice for client/server computing. Oracle supports all
major operating systems for both clients and servers, including MSDOS, NetWare,
UnixWare, OS/2 and most UNIX flavors.
History
Oracle began in 1977 and celebrating its 32 wonderful years in the industry (from 1977 to
2009).
1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development
Laboratories to undertake development work.
1979 - Version 2.0 of Oracle was released and it became first commercial relational
database and first SQL database. The company changed its name to Relational
Software Inc. (RSI).
1983 - Oracle released version 3.0, rewritten in C language and ran on multiple
platforms.
1984 - Oracle version 4.0 was released. It contained features like concurrency
control - multi-version read consistency, etc.
1985 - Oracle version 4.0 was released. It contained features like concurrency
control - multi-version read consistency, etc.
2007 - Oracle released Oracle11g. The new version focused on better partitioning,
easy migration, etc.
Features
Concurrency
Read Consistency
Locking Mechanisms
Quiesce Database
Portability
Self-managing database
SQL*Plus
ASM
Scheduler
Resource Manager
14
SQL
Data Warehousing
Materialized views
Bitmap indexes
Table compression
Parallel Execution
Analytic SQL
Data mining
Partitioning
MS ACCESS
This is one of the most popular Microsoft products. Microsoft Access is an entry-level
database management software. MS Access database is not only inexpensive but also a
powerful database for small-scale projects.
MS Access uses the Jet database engine, which utilizes a specific SQL language dialect
(sometimes referred to as Jet SQL).
MS Access comes with the professional edition of MS Office package. MS Access has easy-
to-use intuitive graphical interface.
1993 - Access 1.1 released to improve compatibility with inclusion the Access Basic
programming language.
2007 - Access 2007, a new database format was introduced ACCDB which supports
complex data types such as multi valued and attachment fields.
Features
Users can create tables, queries, forms and reports and connect them together with
macros.
Option of importing and exporting the data to many formats including Excel,
Outlook, ASCII, dBase, Paradox, FoxPro, SQL Server, Oracle, ODBC, etc.
There is also the Jet Database format (MDB or ACCDB in Access 2007), which can
contain the application and data in one file. This makes it very convenient to
distribute the entire application to another user, who can run it in disconnected
environments.
Microsoft Access offers parameterized queries. These queries and Access tables can
be referenced from other programs like VB6 and .NET through DAO or ADO.
The desktop editions of Microsoft SQL Server can be used with Access as an
alternative to the Jet Database Engine.
15
4. SQL – Syntax SQL
SQL is followed by a unique set of rules and guidelines called Syntax. This tutorial gives
you a quick start with SQL by listing all the basic SQL Syntax.
All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE,
DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon
(;).
The most important point to be noted here is that SQL is case insensitive, which means
SELECT and select have same meaning in SQL statements. Whereas, MySQL makes
difference in table names. So, if you are working with MySQL, then you need to give table
names as they exist in the database.
16
SQL
SQL IN Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
17
SQL
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
DESC table_name;
18
SQL
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
USE database_name;
COMMIT;
ROLLBACK;
19
5. SQL ─ Data Types SQL
SQL Data Type is an attribute that specifies the type of data of any object. Each column,
variable and expression has a related data type in SQL. You can use these data types while
creating your tables. You can choose a data type for a table column based on your
requirement.
SQL Server offers six categories of data types for your use which are listed below −
tinyint 0 255
bit 0 1
20
SQL
Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1
minute accuracy.
21
SQL
22
6. SQL – Operators SQL
Arithmetic operators
Comparison operators
Logical operators
a + b will
+ Addition - Adds values on either side of the operator.
give 30
b / a will
/ Division - Divides left hand operand by right hand operand.
give 2
23
SQL
Example 1:
Output:
+--------+
| 10+ 20 |
+--------+
| 30 |
+--------+
1 row in set (0.00 sec)
Example 2:
Output:
+---------+
| 10 * 20 |
+---------+
| 200 |
+---------+
1 row in set (0.00 sec)
Example 3:
SQL> select 10 / 5;
Output:
+--------+
| 10 / 5 |
+--------+
| 2.0000 |
+--------+
1 row in set (0.03 sec)
Example 4:
24
SQL
SQL> select 12 % 5;
Output:
+---------+
| 12 % 5 |
+---------+
| 2 |
+---------+
1 row in set (0.00 sec)
<> Checks if the values of two operands are equal or not, if (a <> b)
values are not equal then condition becomes true. is true.
> Checks if the value of left operand is greater than the value (a > b) is
of right operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of (a < b) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to (a >= b)
the value of right operand, if yes then condition becomes true. is not
true.
25
SQL
<= Checks if the value of left operand is less than or equal to the (a <= b)
value of right operand, if yes then condition becomes true. is true.
!< Checks if the value of left operand is not less than the value (a !< b) is
of right operand, if yes then condition becomes true. false.
!> Checks if the value of left operand is not greater than the (a !> b) is
value of right operand, if yes then condition becomes true. true.
Here are some simple examples showing the usage of SQL Comparison Operators:
Example 1:
26
SQL
Output:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
3 rows in set (0.00 sec)
Example 2:
Output:
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
2 rows in set (0.00 sec)
Example 3:
Output:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.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 |
+----+----------+-----+---------+----------+
5 rows in set (0.00 sec)
27
SQL
Example 4:
Output:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.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 |
+----+----------+-----+---------+----------+
5 rows in set (0.00 sec)
Example 5:
Output:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
3 rows in set (0.00 sec)
28
SQL
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 as per the condition.
BETWEEN The BETWEEN operator is used to search for values that are within a set
of 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 a certain criterion.
LIKE The LIKE operator is used to compare a value to similar values using
wildcard operators.
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.
IS NULL The NULL operator is used to compare a value with a NULL value.
29
SQL
UNIQUE The UNIQUE operator searches every row of a specified table for
uniqueness (no duplicates).
Here are some simple examples showing usage of SQL Comparison Operators:
Example 1:
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;
Output:
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
2 rows in set (0.00 sec)
30
SQL
Example 2:
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;
Output:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
5 rows in set (0.00 sec)
Example 3:
Output:
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
7 rows in set (0.00 sec)
31
SQL
Example 4:
Output:
+----+-------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+-------+-----+---------+---------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+-------+-----+---------+---------+
1 row in set (0.00 sec)
Example 5:
Output:
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
3 rows in set (0.00 sec)
Example 6:
Output:
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
3 rows in set (0.00 sec)
Example 7:
32
SQL
Output:
+-----+
| AGE |
+-----+
| 32 |
| 25 |
| 23 |
| 25 |
| 27 |
| 22 |
| 24 |
+-----+
7 rows in set (0.02 sec)
Example 8:
Output:
+----+--------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+--------+-----+-----------+---------+
1 row in set (0.02 sec)
Example 9:
33
SQL
Output:
+----+----------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+-----------+---------+
4 rows in set (0.00 sec)
34
7. SQL – Expressions SQL
An expression is a combination of one or more values, operators and SQL functions that
evaluate to a value. These SQL EXPRESSIONs are like formulae and they are written in
query language. You can also use them to query the database for a specific set of data.
Syntax
Consider the basic syntax of the SELECT statement as follows:
There are different types of SQL expressions, which are mentioned below:
Boolean
Numeric
Date
Boolean Expressions
SQL Boolean Expressions fetch the data based on matching a single value. Following is the
syntax:
35
SQL
The following table is a simple example showing the usage of various SQL Boolean
Expressions:
Numeric Expressions
These expressions are used to perform any mathematical operation in any query. Following
is the syntax:
There are several built-in functions like avg(), sum(), count(), etc., to perform what is
known as the aggregate data calculations against a table or a specific table column.
36
SQL
Date Expressions
Date Expressions return the current system date and time values:
37
8. SQL – CREATE Database SQL
The SQL CREATE DATABASE statement is used to create a new SQL database.
Syntax
The basic syntax of this CREATE DATABASE statement is as follows:
Example
If you want to create a new database <testDB>, then the CREATE DATABASE statement
would be as shown below:
Make sure you have the admin privilege before creating any database. Once a database is
created, you can check it in the list of databases as follows:
38
9. SQL ─ DROP or DELETE Database SQL
The SQL DROP DATABASE statement is used to drop an existing database in SQL
schema.
Syntax
The basic syntax of DROP DATABASE statement is as follows:
Example
If you want to delete an existing database <testDB>, then the DROP DATABASE statement
would be as shown below:
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 the admin privilege before dropping any database. Once a database
is dropped, you can check it in the list of the databases as shown below:
39
10. SQL ─ SELECT Database, USE Statement SQL
When you have multiple databases in your SQL Schema, then before starting your
operation, you would need to select a database where all the operations would be
performed.
The SQL USE statement is used to select any existing database in the SQL schema.
Syntax
The basic syntax of the USE statement is as shown below:
USE DatabaseName;
Example
You can check the available databases as shown below:
Now, if you want to work with the AMROOD database, then you can execute the following
SQL command and start working with the AMROOD database.
40
11. SQL ─ CREATE Table SQL
Creating a basic table involves naming the table and defining its columns and each
column's data type.
Syntax
The basic syntax of the CREATE TABLE statement is as follows:
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 the following example.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. You can check the complete details at Create Table
Using another Table.
Example
The following code block is an example, which creates a CUSTOMERS table with an ID as
a primary key and NOT NULL are the constraints showing that these fields cannot be NULL
while creating records in this table:
41
SQL
You can verify if your table has been created successfully by looking at the message
displayed by the SQL server, otherwise you can use the DESC command as follows:
Now, you have CUSTOMERS table available in your database which you can use to store
the required information related to customers.
Syntax
The basic syntax for creating a table from another table is as follows:
Here, column1, column2... are the fields of the existing table and the same would be used
to create fields of the new table.
Example
Following is an example which would create a table SALARY using the CUSTOMERS table
and having the fields – customer ID and customer SALARY:
42
SQL
This would create a new table SALARY which will 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 |
+----+----------+
43
12. SQL ─ DROP or DELETE Table SQL
The SQL DROP TABLE statement is used to remove a table definition and all the data,
indexes, triggers, constraints and permission specifications for that table.
NOTE: You should be very careful while using this command because once a table is
deleted then all the information available in that table will also be lost forever.
Syntax
The basic syntax of this DROP TABLE statement is as follows:
Example
Let us first verify the CUSTOMERS table and then we will delete it from the database as
shown below.
This means that the CUSTOMERS table is available in the database, so let us now drop it
as shown below.
Now, if you would try the DESC command, then you will get the following error:
Here, TEST is the database name which we are using for our examples.
44
13. SQL ─ INSERT Query SQL
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 the INSERT INTO statement which are shown below.
Here, column1, column2, column3,...columnN are the names of the columns in the table
into which you want to insert the 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.
Example
The following statements would create six records in the CUSTOMERS table.
45
SQL
You can create a record in the CUSTOMERS table by using the second syntax as shown
below.
All the above statements would produce the following records in the CUSTOMERS table as
shown below.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
46
14. SQL ─ SELECT Query SQL
The SQL SELECT statement is used to fetch the data from a database table which returns
this data in the form of a result table. These result tables are called result-sets.
Syntax
The basic syntax of the SELECT statement is as follows.:
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.
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 |
+----+----------+-----+-----------+----------+
The following code is an example, which would fetch the ID, Name and Salary fields of the
customers available in CUSTOMERS table.
47
SQL
+----+----------+----------+
| 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 the CUSTOMERS table, then you should use the
following query.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
48
15. SQL ─ WHERE Clause SQL
The SQL WHERE clause is used to specify a condition while fetching the data from a single
table or by joining with multiple tables. If the given condition is satisfied, then only it
returns a specific value from the table. You should use the WHERE clause to filter the
records and fetching only the necessary records.
The WHERE clause is not only used in the SELECT statement, but it is also used in the
UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.
Syntax
The basic syntax of the SELECT statement with the WHERE clause is as shown below.
You can specify a condition using the comparison or logical operators like >, <, =, LIKE,
NOT, etc. The following 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 |
+----+----------+-----+-----------+----------+
The following code is an example which would fetch the ID, Name and Salary fields from
the CUSTOMERS table, where the salary is greater than 2000:
49
SQL
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
The following query is an example, which would fetch the ID, Name and Salary fields from
the CUSTOMERS table for a customer with the name Hardik.
Here, it is important to note that all the strings should be given inside single quotes ('').
Whereas, numeric values should be given without any quote as in the above example.
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 5 | Hardik | 8500.00 |
+----+----------+----------+
50
16. SQL ─ AND & OR Conjunctive Operators SQL
The SQL AND & OR operators are used to combine multiple conditions to narrow data in
an SQL statement. These two operators are called as the conjunctive operators.
These operators provide a means to make multiple comparisons with different operators
in the same SQL statement.
Syntax
The basic syntax of the AND operator with a WHERE clause is as follows:
You can combine N number of conditions using the AND operator. For an action to be taken
by the SQL statement, whether it be a transaction or a query, all conditions separated by
the AND must be TRUE.
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 |
+----+----------+-----+-----------+----------+
51
SQL
Following is an example, which would fetch the ID, Name and Salary fields from the
CUSTOMERS table, where the salary is greater than 2000 and the age is less than 25
years.
+----+-------+----------+
| ID | NAME | SALARY |
+----+-------+----------+
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+-------+----------+
The OR Operator
The OR operator is used to combine multiple conditions in an SQL statement's WHERE
clause.
Syntax
The basic syntax of the OR operator with a WHERE clause is as follows:
You can combine N number of conditions using the OR operator. For an action to be taken
by the SQL statement, whether it be a transaction or query, the only any ONE of the
conditions separated by the OR must be TRUE.
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 |
52
SQL
The following code block has a query, which would fetch the ID, Name and Salary fields
from the CUSTOMERS table, where the salary is greater than 2000 OR the age is less than
25 years.
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
53
17. SQL ─ UPDATE Query SQL
The SQL UPDATE Query is used to modify the existing records in a table. You can use the
WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows
would be affected.
Syntax
The basic syntax of the UPDATE query with a 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 the AND or the 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 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following query will update the ADDRESS for a customer whose ID number is 6 in the
table.
54
SQL
+----+----------+-----+-----------+----------+
| 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 the ADDRESS and the SALARY column values in the CUSTOMERS
table, you do not need to use the WHERE clause as the UPDATE query would be enough
as shown in the following code block.
+----+----------+-----+---------+---------+
| 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 |
+----+----------+-----+---------+---------+
55
18. SQL ─ DELETE Query SQL
The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise
all the records would be deleted.
Syntax
The basic syntax of the DELETE query with the WHERE clause is as follows:
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 |
+----+----------+-----+-----------+----------+
The following code has a query, which will DELETE a customer, whose ID is 6.
56
SQL
+----+----------+-----+-----------+----------+
| 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 the CUSTOMERS table, you do not need to use
the WHERE clause and the DELETE query would be as follows:
57
19. SQL ─ LIKE Clause SQL
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 represents zero, one or multiple characters. The underscore represents
a single number or character. These symbols can be used in combinations.
Syntax
The basic syntax of % and _ is as follows:
or
or
or
or
You can combine N number of conditions using AND or OR operators. Here, XXXX could
be any numeric or string value.
58
SQL
Example
The following table has a few examples showing the 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 '%200%' Finds any values that have 200 in any position.
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 records as shown
below.
+----+----------+-----+-----------+----------+
| 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 the CUSTOMERS table,
where the SALARY starts with 200.
59
SQL
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
60
20. SQL ─ TOP, LIMIT or ROWNUM Clause SQL
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 the TOP clause. For example, MySQL supports the
LIMIT clause to fetch a limited number of records, while Oracle uses the
ROWNUM command to fetch a limited number of records.
Syntax
The basic syntax of the TOP clause with a SELECT statement would be as follows.
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 |
+----+----------+-----+-----------+----------+
The following query is an example on the SQL server, which would fetch the top 3 records
from the CUSTOMERS table.
61
SQL
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
+----+---------+-----+-----------+---------+
| 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 an Oracle server, then the following code block has an equivalent example.
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
62
21. SQL ─ ORDER BY Clause SQL
The SQL ORDER BY clause is used to sort the data in ascending or descending order,
based on one or more columns. Some databases sort the query results in an ascending
order by default.
Syntax
The basic syntax of the 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 the 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 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in an ascending
order by the NAME and the SALARY.
63
SQL
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in the descending
order by NAME.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
64
22. SQL ─ Group By SQL
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.
Syntax
The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP
BY clause must follow the conditions in the WHERE clause and must precede the ORDER
BY clause if one is used.
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 the salary on each customer, then the GROUP BY
query would be as follows.
65
SQL
+----------+-------------+
| 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 look at a table where the CUSTOMERS table has the following records with
duplicate names:
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
Now again, if you want to know the total amount of salary on each customer, then the
GROUP BY query would be as follows:
66
SQL
+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+
67
23. SQL ─ Distinct Keyword SQL
The SQL DISTINCT keyword is used in conjunction with the 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 those unique records instead of
fetching duplicate records.
Syntax
The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows:
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 the duplicate salary records.
68
SQL
This would produce the following result, where the 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 the DISTINCT keyword with the above SELECT query and then see the
result.
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 |
+----------+
69
24. SQL ─ SORTING Results SQL
The SQL ORDER BY clause is used to sort the data in ascending or descending order,
based on one or more columns. Some databases sort the query results in an ascending
order by default.
Syntax
The basic syntax of the ORDER BY clause which would be used to sort the result in an
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 that whatever
column you are using to sort, that column should be in the 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 an ascending order by NAME and
SALARY.
70
SQL
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in a descending
order by NAME.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
71
SQL
To fetch the rows with their own preferred order, the SELECT query used would be as
follows:
+----+----------+-----+-----------+----------+
| 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 the customers by ADDRESS in your ownoOrder of preference first and in a
natural order for the remaining addresses. Also, the remaining Addresses will be sorted in
the reverse alphabetical order.
72
25. SQL ─ Constraints SQL
Constraints are the rules enforced on the data columns of a 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 either on a column level or a table level. The column level constraints
are applied only to one column, whereas the table level constraints are applied to the
whole table.
Following are some of the most commonly used constraints available in SQL. These
constraints have already been discussed in SQL - RDBMS Concepts chapter, but it’s worth
to revise them at this point.
NOT NULL Constraint: Ensures that a column cannot have a NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
FOREIGN Key: Uniquely identifies row/record in any of the given database tables.
CHECK Constraint: The CHECK constraint ensures that all the values in a column
satisfies certain conditions.
INDEX: Used 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 the ALTER TABLE statement to create constraints even after the table is
created.
Example
For example, the following SQL query creates a new table called CUSTOMERS and adds
five columns, three of which are – ID, NAME and AGE. In this we specify not to accept
NULLs:
73
SQL
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to the
SALARY column in Oracle and MySQL, you would write a query like the one that is shown
in the following code block.
Example
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, the SALARY column is set to 5000.00 by default, so in case the INSERT
INTO statement does not provide a value for this column, then by default this column
would be set to 5000.00.
If the CUSTOMERS table has already been created, then to add a DEFAULT constraint to
the SALARY column, you would write a query like the one which is shown in the code block
below.
74
SQL
Example
For example, the following SQL query creates a new table called CUSTOMERS and adds
five columns. Here, the AGE column is set to UNIQUE, so that you cannot have two records
with the same age.
If the CUSTOMERS table has already been created, then to add a UNIQUE constraint to
the AGE column. You would write a statement like the query that is given in the code block
below.
You can also use the following syntax, which supports naming the constraint in multiple
columns as well.
75
SQL
If you are using MySQL, then you can use the following syntax:
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.
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.
To create a PRIMARY KEY constraint on the "ID" column when the CUSTOMERS table
already exists, use the following SQL syntax:
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) should have already been declared to not contain NULL values (when the table
was first created).
76
SQL
For defining a PRIMARY KEY constraint on multiple columns, use the SQL syntax given
below.
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS
table already exists, use the following SQL syntax.
A 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).
77
SQL
Example
Consider the structure of the following two tables.
CUSTOMERS Table:
ORDERS Table
If the ORDERS table has already been created and the foreign key has not yet been set,
the use the syntax for specifying a foreign key by altering a table.
78
SQL
Example
For example, the following program creates a new table called CUSTOMERS and adds five
columns. Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER
who is below 18 years.
If the CUSTOMERS table has already been created, then to add a CHECK constraint to AGE
column, you would write a statement like the one given below.
You can also use the following syntax, which supports naming the constraint in multiple
columns as well:
79
SQL
Proper indexes are good for performance in large databases, but you need to be careful
while creating an index. A selection of fields depends on what you are using in your SQL
queries.
Example
For example, the following SQL syntax creates a new table called CUSTOMERS and adds
five columns:
Now, you can create an index on a single or multiple columns using the syntax given
below.
To create an INDEX on the AGE column, to optimize the search on customers for a specific
age, follow the SQL syntax which is given below.
80
SQL
Dropping Constraints
Any constraint that you have defined can be dropped using the ALTER TABLE command
with the DROP CONSTRAINT option.
For example, to drop the primary key constraint in the EMPLOYEES table, you can use the
following command.
Some implementations may provide shortcuts for dropping certain constraints. For
example, to drop the primary key constraint for a table in Oracle, you can use the following
command.
Integrity Constraints
Integrity constraints are used to ensure accuracy and consistency of the data in a relational
database. Data integrity is handled in a relational database through the concept of
referential integrity.
There are many types of integrity constraints that play a role in Referential Integrity
(RI). These constraints include Primary Key, Foreign Key, Unique Constraints and other
constraints which are mentioned above.
81
26. SQL ─ Using Joins SQL
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.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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 shown below.
82
SQL
+----+----------+-----+--------+
| 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 to
symbol.
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.
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
83
SQL
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
| 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 |
+-----+---------------------+-------------+--------+
84
SQL
Now, let us join these two tables using the INNER JOIN as follows:
+----+----------+--------+---------------------+
| 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 |
+----+----------+--------+---------------------+
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 a LEFT JOIN is as follows.
Here, the given condition could be any given expression based on your requirement.
85
SQL
Example
Consider the following two tables,
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
| 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 the LEFT JOIN as follows.
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
86
SQL
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 a RIGHT JOIN is as follow.
Example
Consider the following two tables,
+----+----------+-----+-----------+----------+
| 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 |
87
SQL
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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 the RIGHT JOIN as follows.
+------+----------+--------+---------------------+
| 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 |
+------+----------+--------+---------------------+
The joined table will contain all records from both the tables and fill in NULLs for missing
matches on either side.
88
SQL
Syntax
The basic syntax of a FULL JOIN is as follows:
Here, the given condition could be any given expression based on your requirement.
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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 |
+-----+---------------------+-------------+--------+
89
SQL
Now, let us join these two tables using FULL JOIN as follows.
+------+----------+--------+---------------------+
| 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 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
If your Database does not support FULL JOIN (MySQL does not support FULL JOIN), then
you can use UNION ALL clause to combine these two JOINS as shown below.
90
SQL
Syntax
The basic syntax of SELF JOIN is as follows:
Here, the WHERE clause could be any given expression based on your requirement.
Example
Consider the following 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 |
+----+----------+-----+-----------+----------+
91
SQL
+----+----------+---------+
| 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 |
| 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 |
+----+----------+---------+
Syntax
The basic syntax of the CARTESIAN JOIN or the CROSS JOIN is as follows:
92
SQL
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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:
+----+----------+--------+---------------------+
| 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 |
+----+----------+--------+---------------------+
94
27. SQL ─ UNIONS CLAUSE SQL
The SQL UNION clause/operator is used to combine the results of two or more SELECT
statements without returning any duplicate rows.
Syntax
The basic syntax of a UNION clause is as follows:
UNION
Here, the given condition could be any given expression based on your requirement.
95
SQL
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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:
96
SQL
+------+----------+--------+---------------------+
| 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 same rules that apply to the UNION clause will apply to the UNION ALL operator.
Syntax
The basic syntax of the UNION ALL is as follows.
UNION ALL
Here, the given condition could be any given expression based on your requirement.
Example
97
SQL
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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:
98
SQL
+------+----------+--------+---------------------+
| 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 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
There are two other clauses (i.e., operators), which are like the UNION clause.
SQL INTERSECT Clause: This 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.
SQL EXCEPT Clause: This combines two SELECT statements and returns rows from
the first SELECT statement that are not returned by the second SELECT statement.
Just as with the UNION operator, the same rules apply when using the INTERSECT
operator. MySQL does not support the INTERSECT operator.
Syntax
The basic syntax of INTERSECT is as follows.
99
SQL
INTERSECT
Here, the given condition could be any given expression based on your requirement.
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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.
100
SQL
+------+---------+--------+---------------------+
| 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 |
+------+---------+--------+---------------------+
Just as with the UNION operator, the same rules apply when using the EXCEPT operator.
MySQL does not support the EXCEPT operator.
Syntax
The basic syntax of EXCEPT is as follows.
EXCEPT
101
SQL
[WHERE condition]
Here, the given condition could be any given expression based on your requirement.
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|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 shown below.
EXCEPT
102
SQL
+----+---------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+---------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+---------+--------+---------------------+
103
28. SQL ─ NULL Values SQL
The SQL NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that
a NULL value is different than a zero value or a field that contains spaces.
Syntax
The basic syntax of NULL while creating a table.
Here, NOT NULL signifies that column should always accept an explicit value of the given
data type. There are two columns where we did not use NOT NULL, which means these
columns could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
Example
The NULL value can cause problems when selecting data. However, because when
comparing an unknown value to any other value, the result is always unknown and not
included in the results. You must use the IS NULL or IS NOT NULL operators to check
for a NULL value.
Consider the following CUSTOMERS table having the records as shown below.
+----+----------+-----+-----------+----------+
| 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 |
104
SQL
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
105
29. SQL ─ Alias Syntax SQL
You can rename a table or a column temporarily by giving another name known as Alias.
The use of table aliases is to rename a table in a specific 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 a table alias is as follows.
Example
Consider the following two tables.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
106
SQL
+-----+---------------------+-------------+--------+
|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, the following code block shows the usage of a table alias.
+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
107
SQL
+-------------+---------------+
| CUSTOMER_ID | CUSTOMER_NAME |
+-------------+---------------+
| 1 | Ramesh |
| 2 | Khilan |
| 3 | kaushik |
| 4 | Chaitali |
| 5 | Hardik |
| 6 | Komal |
| 7 | Muffy |
+-------------+---------------+
108
30. SQL – Indexes SQL
Indexes are special lookup tables that the database search engine can use to speed up
data retrieval. Simply put, an index is a pointer to data in a table. An index in a database
is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic,
you first refer to the index, which lists all the topics alphabetically and are then referred
to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data
input, with the UPDATE and the INSERT statements. Indexes can be created or dropped
with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the
index, to specify the table and which column or columns to index, and to indicate whether
the index is in an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there is an index.
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as
follows.
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique
index does not allow any duplicate values to be inserted into the table. The basic syntax
is as follows.
109
SQL
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as
follows.
Whether to create a single-column index or a composite index, take into consideration the
column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should
there be two or more columns that are frequently used in the WHERE clause as filters, the
composite index would be the best choice.
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when
an object is created. Indexes are automatically created for primary key constraints and
unique constraints.
You can check the INDEX Constraint chapter to see some actual examples on Indexes.
The following guidelines indicate when the use of an index should be reconsidered.
Indexes should not be used on columns that contain a high number of NULL values.
110
SQL
Proper indexes are good for performance in large databases, but you need to be careful
while creating an 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 in it.
Now, you can create an index on a single or multiple columns using the syntax given
below.
To create an INDEX on the AGE column, to optimize the search on customers for a specific
age, you can use the following SQL syntax:
111
31. SQL ─ ALTER TABLE Command SQL
The SQL ALTER TABLE command is used to add, delete or modify columns in an existing
table. You should also use the ALTER TABLE command to add and drop various constraints
on an existing table.
Syntax
The basic syntax of an ALTER TABLE command to add a New Column in an existing table
is as follows.
The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is
as follows.
The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in
a table is as follows.
The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column
in a table is as follows.
The basic syntax of an ALTER TABLE command to ADD UNIQUE CONSTRAINT to a table
is as follows.
The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table
is as follows.
112
SQL
The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a
table is as follows.
The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is as
follows.
The basic syntax of an ALTER TABLE command to DROP PRIMARY KEY constraint from
a table is as follows.
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 |
113
SQL
+----+----------+-----+-----------+----------+
Now, the CUSTOMERS table is changed and following would be output from the 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 the existing table.
Now, the CUSTOMERS table is changed and following would be the output from the 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 |
+----+---------+-----+-----------+----------+
114
SQL
115
32. SQL - TRUNCATE TABLE Command SQL
The SQL TRUNCATE TABLE command is used to delete complete data from an existing
table.
You can also use DROP TABLE command to delete complete table but it would remove
complete table structure form the database and you would need to re-create this table
once again if you wish you store some data.
Syntax
The basic syntax of a TRUNCATE TABLE command is as follows.
Example
Consider a 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, the CUSTOMERS table is truncated and the output from SELECT statement will be as
shown in the code block below:
116
33. SQL ─ Using Views SQL
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 depends on the written SQL query to create a view.
Views, which are a type 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 in such a way that a user can see and (sometimes)
modify exactly what they need and no more.
Summarize data from various tables which can be used to generate reports.
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.
You can include multiple tables in your SELECT statement in a similar way as you use them
in a 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 |
117
SQL
Following is an example to create a view from the CUSTOMERS table. This view would be
used to have customer name and age from the CUSTOMERS table.
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table.
Following is an example for the same.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating same view CUSTOMERS_VIEW with
the WITH CHECK OPTION.
118
SQL
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 which are given below –
All NOT NULL columns from the base table must be included in the view in order
for the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The
following code block has an example to update the age of Ramesh.
This would ultimately update the base table CUSTOMERS and the same would reflect in
the view itself. Now, try to query the base table and the SELECT statement would produce
the following result.
119
SQL
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all
the NOT NULL columns in this view, otherwise you can insert rows in a view in a similar
way as you insert them in a table.
This would ultimately delete a row from the base table CUSTOMERS and the same would
reflect in the view itself. Now, try to query the base table and the 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 |
120
SQL
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer
needed. The syntax is very simple and is given below:
121
34. SQL ─ Having Clause SQL
The HAVING Clause enables you to specify conditions that filter which group results
appear in the 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 code block shows the position of the HAVING Clause in a query.
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
The HAVING clause must follow the GROUP BY clause in a query and must also precede
the ORDER BY clause if used. The following code block has the syntax of the SELECT
statement including the HAVING clause:
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 |
122
SQL
Following is an example, which would display a record for a similar age count that would
be more than or equal to 2.
+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
+----+--------+-----+---------+---------+
123
35. SQL – Transactions SQL
A transaction is a unit of work that is performed against a database. Transactions are units
or sequences of work accomplished in a logical order, whether in a manual fashion by a
user or automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if
you are creating a record or updating a record or deleting a record from the table, then
you are performing a transaction on that table. It is important to control these transactions
to ensure the data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them
together as a part of a transaction.
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID.
Atomicity: ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and all the
previous operations are rolled back to their former state.
Transaction Control
The following commands are used to control transactions.
124
SQL
COMMIT;
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 delete those records from the table which have age
= 25 and then COMMIT the changes in the database.
Thus, two rows from the table would be deleted and the SELECT statement would produce
the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
125
SQL
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
ROLLBACK;
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 delete those records from the table which have the
age = 25 and then ROLLBACK the changes in the database.
126
SQL
Thus, the delete operation would not impact the table and the SELECT statement 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 |
+----+----------+-----+-----------+----------+
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the transactional
statements. The ROLLBACK command is used to undo a group of transactions.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records from the
CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original
state.
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 |
127
SQL
Now that the three deletions have taken place, let us assume that you have changed your
mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because
SP2 was created after the first deletion, the last two deletions are undone:
Notice that only the first deletion took place since you rolled back to SP2.
128
SQL
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
6 rows selected.
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to
undo transactions performed since the last SAVEPOINT.
129
36. SQL ─ Wildcard Operators SQL
We have already discussed about the SQL LIKE operator, which is used to compare a
value to similar values using the wildcard operators.
SQL supports two wildcard operators in conjunction with the LIKE operator which are
explained in detail in the following table .
The percent sign represents zero, one or multiple characters. The underscore represents
a single number or a character. These symbols can be used in combinations.
Syntax
The basic syntax of a '%' and a '_' operator is as follows.
or
or
or
130
SQL
or
You can combine N number of conditions using the AND or the OR operators. Here, XXXX
could be any numeric or string value.
Example
The following table has a number of examples showing the WHERE part having different
LIKE clauses with '%' and '_' operators.
Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200.
WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position.
WHERE SALARY LIKE '%2' Finds any values that end with 2.
131
SQL
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 |
+----+----------+-----+-----------+----------+
The following code block is an example, which would display all the records from the
CUSTOMERS table where the SALARY starts with 200.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
132
37. SQL ─ Date Functions SQL
The following table has a list of all the important Date and Time related functions available
through SQL. There are various other functions supported by your RDBMS. The given list
is based on MySQL RDBMS.
Name Description
CURRENT_DATE(),
Synonyms for CURDATE()
CURRENT_DATE
CURRENT_TIME(),
Synonyms for CURTIME()
CURRENT_TIME
CURRENT_TIMESTAMP(),
Synonyms for NOW()
CURRENT_TIMESTAMP
133
SQL
LAST_DAY Returns the last day of the month for the argument
LOCALTIMESTAMP,
Synonym for NOW()
LOCALTIMESTAMP()
MAKETIME MAKETIME()
134
SQL
135
SQL
136
SQL
When invoked with the days form of the second argument, MySQL treats it as an integer
number of days to be added to expr.
ADDTIME(expr1,expr2)
ADDTIME() adds expr2 to expr1 and returns the result. The expr1 is a time or datetime
expression, while the expr2 is a time expression.
CONVERT_TZ(dt,from_tz,to_tz)
This converts a datetime value dt from the time zone given by from_tz to the time zone
given by to_tz and returns the resulting value. This function returns NULL if the arguments
are invalid.
137
SQL
+---------------------------------------------------------+
| 2004-01-01 22:00:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on
whether the function is used in a string or in a numeric context.
CURTIME()
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or in a numeric context. The value is expressed in
the current time zone.
138
SQL
+---------------------------------------------------------+
1 row in set (0.00 sec)
DATE(expr)
Extracts the date part of the date or datetime expression expr.
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the
other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts
of the values are used in the calculation.
139
SQL
A Unit is a keyword indicating the units in which the expression should be interpreted.
The INTERVAL keyword and the unit specifier are not case sensitive.
The following table shows the expected form of the expr argument for each unit value.
MICROSECOND MICROSECONDS
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
MINUTE_MICROSECOND 'MINUTES.MICROSECONDS'
MINUTE_SECOND 'MINUTES:SECONDS'
HOUR_MICROSECOND 'HOURS.MICROSECONDS'
140
SQL
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
DAY_MICROSECOND 'DAYS.MICROSECONDS'
YEAR_MONTH 'YEARS-MONTHS'
The values QUARTER and WEEK are available from the MySQL 5.0.0 version.
141
SQL
DATE_FORMAT(date,format)
This command formats the date value as per the format string. The following specifiers
may be used in the format string. The '%' character is required before the format specifier
characters.
Specifier Description
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, .)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%k Hour (0..23)
%l Hour (1..12)
142
SQL
%p AM or PM
%S Seconds (00..59)
%s Seconds (00..59)
Week (01..53), where Sunday is the first day of the week; used with
%V
%X
Week (01..53), where Monday is the first day of the week; used with
%v
%x
Year for the week where Sunday is the first day of the week, numeric,
%X
four digits; used with %V
Year for the week, where Monday is the first day of the week, numeric,
%x
four digits; used with %v
143
SQL
144
SQL
DAY(date)
The DAY() is a synonym for the DAYOFMONTH() function.
DAYNAME(date)
Returns the name of the weekday for date.
145
SQL
DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.
DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These
index values correspond to the ODBC standard.
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or
DATE_SUB(), but extracts parts from the date rather than performing date arithmetic.
FROM_DAYS(N)
Given a day number N, returns a DATE value.
Note: Use FROM_DAYS() with caution on old dates. It is not intended for use with values
that precede the advent of the Gregorian calendar (1582).
FROM_UNIXTIME(unix_timestamp)
FROM_UNIXTIME(unix_timestamp,format)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD
HH:MM:SS or YYYYMMDDHHMMSS format, depending on whether the function is used in
a string or in a numeric context. The value is expressed in the current time zone. The
unix_timestamp argument is an internal timestamp values, which are produced by the
UNIX_TIMESTAMP() function.
147
SQL
If the format is given, the result is formatted according to the format string, which is used
in the same way as is listed in the entry for the DATE_FORMAT() function.
HOUR(time)
Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values.
However, the range of TIME values actually is much larger, so HOUR can return values
greater than 23.
LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last day of the
month. Returns NULL if the argument is invalid.
148
SQL
MAKEDATE(year,dayofyear)
Returns a date, given year and day-of-year values. The dayofyear value must be greater
than 0 or the result will be NULL.
MAKETIME(hour,minute,second)
Returns a time value calculated from the hour, minute and second arguments.
MICROSECOND(expr)
Returns the microseconds from the time or datetime expression (expr) as a number in the
range from 0 to 999999.
MINUTE(time)
Returns the minute for time, in the range 0 to 59.
149
SQL
MONTH(date)
Returns the month for date, in the range 0 to 12.
MONTHNAME(date)
Returns the full name of the month for a date.
NOW()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context. This value is expressed in the current time zone.
150
SQL
+---------------------------------------------------------+
| 1997-12-15 23:50:26 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
PERIOD_ADD(P,N)
Adds N months to a period P (in the format YYMM or YYYYMM). Returns a value in the
format YYYYMM.
PERIOD_DIFF(P1,P2)
Returns the number of months between periods P1 and P2. These periods P1 and P2 should
be in the format YYMM or YYYYMM.
Note that the period arguments P1 and P2 are not date values.
QUARTER(date)
Returns the quarter of the year for date, in the range 1 to 4.
+---------------------------------------------------------+
| QUARTER('98-04-01') |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SECOND(time)
Returns the second for time, in the range 0 to 59.
SEC_TO_TIME(seconds)
Returns the seconds argument, converted to hours, minutes and seconds, as a value in
'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or
numeric context.
STR_TO_DATE(str,format)
This is the inverse of the DATE_FORMAT() function. It takes a string str and a format
string format. The STR_TO_DATE() function returns a DATETIME value if the format string
contains both date and time parts. Else, it returns a DATE or TIME value if the string
contains only date or time parts.
152
SQL
SUBTIME(expr1,expr2)
The SUBTIME() function returns expr1 . expr2 expressed as a value in the same format as
expr1. The expr1 value is a time or a datetime expression, while the expr2 value is a time
expression.
153
SQL
SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a
numeric context.
TIME(expr)
Extracts the time part of the time or datetime expression expr and returns it as a string.
TIMEDIFF(expr1,expr2)
The TIMEDIFF() function returns expr1 . expr2 expressed as a time value. These expr1
and expr2 values are time or date-and-time expressions, but both must be of the same
type.
TIMESTAMP(expr), TIMESTAMP(expr1,expr2)
With a single argument, this function returns the date or datetime expression expr as a
datetime value. With two arguments, it adds the time expression expr2 to the date or
datetime expression expr1 and returns the result as a datetime value.
TIMESTAMPADD(unit,interval,datetime_expr)
This function adds the integer expression interval to the date or datetime expression –
datetime_expr. The unit for interval is given by the unit argument, which should be one
of the following values –
FRAC_SECOND
SECOND, MINUTE
HOUR, DAY
WEEK
MONTH
QUARTER or
YEAR
The unit value may be specified using one of the keywords as shown or with a prefix of
SQL_TSI_.
155
SQL
+---------------------------------------------------------+
| 2003-01-02 00:01:00 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns the integer difference between the date or datetime expressions datetime_expr1
and datetime_expr2. The unit for the result is given by the unit argument. The legal values
for the unit are the same as those listed in the description of the TIMESTAMPADD()
function.
TIME_FORMAT(time,format)
This function is used like the DATE_FORMAT() function, but the format string may contain
format specifiers only for hours, minutes and seconds.
If the time value contains an hour part that is greater than 23, the %H and %k hour
format specifiers produce a value larger than the usual range of 0 to 23. The other hour
format specifiers produce the hour value modulo 12.
TIME_TO_SEC(time)
Returns the time argument converted to seconds.
156
SQL
+---------------------------------------------------------+
| TIME_TO_SEC('22:23:00') |
+---------------------------------------------------------+
| 80580 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TO_DAYS(date)
Given a date, returns a day number (the number of days since year 0).
UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
If called with no argument, this function returns a Unix timestamp (seconds since '1970-
-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date
argument, it returns the value of the argument as seconds, since '1970-01-01 00:00:00'
UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the
format YYMMDD or YYYYMMDD.
| 875996580 |
157
SQL
+---------------------------------------------------------+
1 row in set (0.00 sec)
UTC_DATE, UTC_DATE()
Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending
on whether the function is used in a string or numeric context.
UTC_TIME, UTC_TIME()
Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or numeric context.
UTC_TIMESTAMP, UTC_TIMESTAMP()
Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or in a
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in a
numeric context.
158
SQL
+---------------------------------------------------------+
| 2003-08-14 18:08:04, 20030814180804 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
WEEK(date[,mode])
This function returns the week number for date. The two-argument form of WEEK() allows
you to specify whether the week starts on a Sunday or a Monday and whether the return
value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted,
the value of the default_week_format system variable is used
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday).
159
SQL
WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53.
WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).
YEAR(date)
Returns the year for date, in the range 1000 to 9999 or 0 for the .zero. date.
YEARWEEK(date), YEARWEEK(date,mode)
Returns the year and the week for a date. The mode argument works exactly like the mode
argument to the WEEK() function. The year in the result may be different from the year in
the date argument for the first and the last week of the year.
160
SQL
| YEAR('98-02-03')YEARWEEK('1987-01-01') |
+---------------------------------------------------------+
| 198653 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
Note: The week number is different from what the WEEK() function would return (0) for
optional arguments 0 or 1, as WEEK() then returns the week in the context of the given
year.
161
38. SQL ─ Temporary Tables SQL
The temporary tables could be very useful in some cases to keep temporary data. The
most important thing that should be known for temporary tables is that they will be deleted
when the current client session terminates.
Temporary tables are available in MySQL version 3.23 onwards. If you use an older version
of MySQL than 3.23, you can't use temporary tables, but you can use heap tables.
As stated earlier, temporary tables will only last as long as the session is alive. If you run
the code in a PHP script, the temporary table will be destroyed automatically when the
script finishes executing. If you are connected to the MySQL database server through the
MySQL client program, then the temporary table will exist until you close the client or
manually destroy the table.
Example
Here is an example showing you the usage of a temporary table.
162
SQL
When you issue a SHOW TABLES command, then your temporary table will not be listed
out in the list. Now, if you log out of the MySQL session and then issue a SELECT command,
you will find no data available in the database. Even your temporary table will not be
existing.
163
39. SQL – Clone Tables SQL
There may be a situation when you need an exact copy of a table and the CREATE TABLE
... or the SELECT... commands does not suit your purposes because the copy must include
the same indexes, default values and so forth.
If you are using MySQL RDBMS, you can handle this situation by adhering to the steps
given below:
Use SHOW CREATE TABLE command to get a CREATE TABLE statement that
specifies the source table's structure, indexes and all.
Modify the statement to change the table name to that of the clone table and
execute the statement. This way you will have an exact clone table.
Optionally, if you need the table contents copied as well, issue an INSERT INTO or
a SELECT statement too.
Example
Try out the following example to create a clone table for TUTORIALS_TBL whose
structure is as follows:
164
SQL
Step 3: After executing step 2, you will clone a table in your database. If you want to
copy data from an old table, then you can do it by using the INSERT INTO... SELECT
statement.
Finally, you will have an exact clone table as you wanted to have.
165
40. SQL – Sub Queries SQL
A Subquery or Inner query or a 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.
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.
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.
The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
166
SQL
Example
Consider the CUSTOMERS table having the following records.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
167
SQL
Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS
table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for
all the customers whose AGE is greater than or equal to 27.
168
SQL
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 |
+----+----------+-----+-----------+----------+
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the CUSTOMERS table
for all the customers whose AGE is greater than or equal to 27.
This would impact two rows and finally the CUSTOMERS table would have the following
records.
169
SQL
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 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 |
+----+----------+-----+---------+----------+
170
41. SQL – Using Sequences SQL
Example
Try out the following example. This will create a table and after that it will insert a few
rows in this table where it is not required to give a record ID because its auto-incremented
by MySQL.
171
SQL
PERL Example
Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a
query. This attribute is accessed through either a database handle or a statement handle,
depending on how you issue the query.
PHP Example
After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by
calling the mysql_insert_id( ) function.
The following example shows how to renumber the id values in the insect table using this
technique.
172
SQL
The following code block has an example where MySQL will start sequence from 100.
Alternatively, you can create the table and then set the initial sequence value with ALTER
TABLE.
173
42. SQL – Handling Duplicates SQL
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.
The SQL DISTINCT keyword, which we have already discussed is used in conjunction with
the SELECT statement to eliminate all the duplicate records and by fetching only the unique
records.
Syntax
The basic syntax of a DISTINCT keyword to eliminate duplicate records is as follows.
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.
174
SQL
This would produce the following result where the salary of 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 the DISTINCT keyword with the above SELECT query and see the result.
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 |
+----------+
175
43. SQL – Injection SQL
If you take a user input through a webpage and insert it into a SQL database, there is a
chance that you have left yourself wide open for a security issue known as the SQL
Injection. This chapter will teach you how to help prevent this from happening and help
you secure your scripts and SQL statements in your server side scripts such as a PERL
Script.
Injection usually occurs when you ask a user for input, like their name and instead of a
name they give you a SQL statement that you will unknowingly run on your database.
Never trust user provided data, process this data only after validation; as a rule, this is
done by Pattern Matching.
In the example below, the name is restricted to the alphanumerical characters plus
underscore and to a length between 8 and 20 characters (modify these rules as needed).
// supposed input
$name = "Qadir'; DELETE FROM CUSTOMERS;";
mysql_query("SELECT * FROM CUSTOMSRS WHERE name='{$name}'");
The function call is supposed to retrieve a record from the CUSTOMERS table where the
name column matches the name specified by the user. Under normal circumstances,
$name would only contain alphanumeric characters and perhaps spaces, such as the
string ilia. But here, by appending an entirely new query to $name, the call to the database
turns into disaster; the injected DELETE query removes all records from the CUSTOMERS
table.
Fortunately, if you use MySQL, the mysql_query() function does not permit query
stacking or executing multiple SQL queries in a single function call. If you try to stack
queries, the call fails.
However, other PHP database extensions, such as SQLite and PostgreSQL happily
perform stacked queries, executing all the queries provided in one string and creating a
serious security problem.
176
SQL
if (get_magic_quotes_gpc())
{
$name = stripslashes($name);
}
$name = mysql_real_escape_string($name);
mysql_query("SELECT * FROM CUSTOMERS WHERE name='{$name}'");
177