SQL - Quick Guide
SQL - Quick Guide
SQL - Overview
SQL is a language to operate databases; it
includes database creation, deletion, fetching
rows, modifying rows, etc. SQL is an ANSI
(American National Standards Institute)
standard language, but there are many different
versions of the SQL language.
What is SQL?
SQL is Structured Query Language, which is a
computer language for storing, manipulating
and retrieving data stored in a relational
database.
Why SQL?
SQL is widely popular because it offers the
following advantages −
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.
Query Dispatcher
Optimization Engines
Classic Query Engine
SQL Query Engine, etc.
CREATE
ALTER
2 Modifies an existing database
object, such as a table.
DROP
SELECT
1 Retrieves certain records from one
or more tables.
INSERT
2
Creates a record.
UPDATE
3
Modifies records.
DELETE
4
Deletes records.
GRANT
1
Gives a privilege to user.
REVOKE
2 Takes back privileges granted from
user.
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.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
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.
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
+----+----------+-----+-----------+-
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.
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+
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.
Data Integrity
The following categories of data integrity exist
with each RDBMS −
Database Normalization
Database normalization is the process of
efficiently organizing data in a database. There
are two reasons of this normalization process −
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."
History
Development of MySQL by Michael
Widenius & David Axmark beginning in
1994.
Features
High Performance.
High Availability.
Scalability and Flexibility Run anything.
Robust Transactional Support.
Web and Data Warehouse Strengths.
Strong Data Protection.
Comprehensive Application Development.
Management Ease.
Open Source Freedom and 24 x 7 Support.
Lowest Total Cost of Ownership.
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.
Features
High Performance
High Availability
Database mirroring
Database snapshots
CLR integration
Service Broker
DDL triggers
Ranking functions
Row version-based isolation levels
XML integration
TRY...CATCH
Database Mail
ORACLE
It is a very large multi-user based database
management system. Oracle is a relational
database management system developed by
'Oracle Corporation'.
History
Oracle began in 1977 and celebrating its 32
wonderful years in the industry (from 1977 to
2009).
Features
Concurrency
Read Consistency
Locking Mechanisms
Quiesce Database
Portability
Self-managing database
SQL*Plus
ASM
Scheduler
Resource Manager
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.
Features
Users can create tables, queries, forms
and reports and connect them together
with macros.
SQL - Syntax
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.
FROM table_name;
FROM table_name
WHERE CONDITION;
FROM table_name
SQL IN Clause
SELECT column1, column2....columnN
FROM table_name
FROM table_name
FROM table_name
FROM table_name
WHERE CONDITION
FROM table_name
WHERE CONDITION
GROUP BY column_name;
FROM table_name
WHERE CONDITION;
FROM table_name
WHERE CONDITION
GROUP BY column_name
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
WHERE {CONDITION};
tinyint 0 255
bit 0 1
char
varchar
2 Maximum of 8,000 characters.
(Variable-length non-Unicode data).
varchar(max)
Maximum length of 2E + 31
3 characters, Variable-length non-
Unicode data (SQL Server 2005
only).
text
nchar
1 Maximum length of 4,000
characters.( Fixed length Unicode)
nvarchar
2 Maximum length of 4,000
characters.(Variable length Unicode)
nvarchar(max)
Maximum length of 2E + 31
3
characters (SQL Server 2005 only).(
Variable length Unicode)
ntext
4
Maximum length of 1,073,741,823
characters. ( Variable length Unicode
)
binary
1 Maximum length of 8,000
bytes(Fixed-length binary data )
varbinary
2 Maximum length of 8,000 bytes.
(Variable length binary data)
varbinary(max)
image
4 Maximum length of 2,147,483,647
bytes. ( Variable length Binary Data)
sql_variant
1
Stores values of various SQL Server-
supported data types, except text,
ntext, and timestamp.
timestamp
uniqueidentifier
3 Stores a globally unique identifier
(GUID)
xml
4
Stores XML data. You can store xml
instances in a column or a variable
(SQL Server 2005 only).
cursor
5
Reference to a cursor object
table
6 Stores a result set for later
processing
SQL - Operators
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions
Show Examples
Subtracts right
a - b will
- (Subtraction) hand operand from
give -10
left hand operand.
Multiplies values
* a * b will
on either side of
(Multiplication) give 200
the operator.
Show Examples
Operator Description Example
Show Examples
Sr.No. Operator & Description
ALL
AND
ANY
3
The ANY operator is used to
compare a value to any applicable
value in the list as per the condition.
BETWEEN
EXISTS
IN
6
The IN operator is used to compare
a value to a list of literal values that
have been specified.
7 LIKE
NOT
OR
9
The OR operator is used to combine
multiple conditions in an SQL
statement's WHERE clause.
IS NULL
10 The NULL operator is used to
compare a value with a NULL value.
UNIQUE
SQL - Expressions
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 −
FROM table_name
WHERE [CONDITION|EXPRESSION];
Boolean
Numeric
Date
Boolean Expressions
SQL Boolean Expressions fetch the data based
on matching a single value. Following is the
syntax −
FROM table_name
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| | | | |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
7 rows in set (0.00 sec)
Numeric Expression
These expressions are used to perform any
mathematical operation in any query. Following
is the syntax −
WHERE CONDITION] ;
+----------+
| ADDITION |
+----------+
| 21 |
+----------+
| RECORDS |
+---------+
| 7 |
+---------+
Date Expressions
Date Expressions return current system date
and time values −
+---------------------+
| Current_Timestamp |
+---------------------+
| 2009-11-12 06:40:23 |
+---------------------+
+-------------------------+
| GETDATE |
+-------------------------+
| 2009-10-22 12:07:18.140 |
+-------------------------+
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 −
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+--------------------+
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 −
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
+--------------------+
Syntax
The basic syntax of the USE statement is as
shown below −
USE DatabaseName;
Example
You can check the available databases as
shown below −
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
+--------------------+
Syntax
The basic syntax of the CREATE TABLE
statement is as follows −
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
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 −
);
+---------+---------------+------+-----
| Field | Type | Null | Key
+---------+---------------+------+-----
| ID | int(11) | NO | PRI
| NAME | varchar(20) | NO |
| AGE | int(11) | NO |
| ADDRESS | char(25) | YES |
| SALARY | decimal(18,2) | YES |
+---------+---------------+------+-----
5 rows in set (0.00 sec)
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 −
+---------+---------------+------+--
| Field | Type | Null | Ke
+---------+---------------+------+--
| ID | int(11) | NO | P
| NAME | varchar(20) | NO |
| AGE | int(11) | NO |
| ADDRESS | char(25) | YES |
| SALARY | decimal(18,2) | YES |
+---------+---------------+------+--
5 rows in set (0.00 sec)
Syntax
There are two basic syntaxes of the INSERT
INTO statement which are shown below.
Example
The following statements would create six
records in the CUSTOMERS table.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
[WHERE condition];
Syntax
The basic syntax of the SELECT statement is as
follows −
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+----+----------+----------+
| 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 |
+----+----------+----------+
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
Syntax
The basic syntax of the SELECT statement with
the WHERE clause is as shown below.
FROM table_name
WHERE [condition]
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 5 | Hardik | 8500.00 |
+----+----------+----------+
Syntax
The basic syntax of the AND operator with a
WHERE clause is as follows −
FROM table_name
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | M ff | 24 | I d | 100
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
+----+-------+----------+
| 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 −
FROM table_name
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
Syntax
The basic syntax of the UPDATE query with a
WHERE clause is as follows −
UPDATE table_name
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
WHERE ID = 6;
Now, the CUSTOMERS table would have the
following records −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | Pune | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
+----+----------+-----+---------+------
| ID | NAME | AGE | ADDRESS | SALAR
+----+----------+-----+---------+------
| 1 | Ramesh | 32 | Pune | 1000.
| 2 | Khilan | 25 | Pune | 1000.
| 3 | kaushik | 23 | Pune | 1000.
| 4 | Chaitali | 25 | Pune | 1000.
| 5 | Hardik | 27 | Pune | 1000.
| 6 | Komal | 22 | Pune | 1000.
| 7 | Muffy | 24 | Pune | 1000.
+----+----------+-----+---------+------
SQL - DELETE Query
The SQL DELETE Query is used to delete the
existing records from a table.
Syntax
The basic syntax of the DELETE query with the
WHERE clause is as follows −
WHERE [condition];
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
WHERE ID = 6;
Now, the CUSTOMERS table would have the
following records.
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
Syntax
The basic syntax of % and _ is as follows −
or
or
or
or
Example
The following table has a few examples
showing the WHERE part having different LIKE
clause with '%' and '_' operators −
Sr.No. Statement & Description
4
Finds any values that start with 2
and are at least 3 characters in
length.
7
Finds any values in a five-digit
number that start with 2 and end
with 3.
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 3 | kaushik | 23 | Kota | 20
+----+----------+-----+-----------+----
WHERE [condition]
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
+----+---------+-----+-----------+-----
| ID | NAME | AGE | ADDRESS | SALA
+----+---------+-----+-----------+-----
| 1 | Ramesh | 32 | Ahmedabad | 2000
| 2 | Khilan | 25 | Delhi | 1500
| 3 | kaushik | 23 | Kota | 2000
+----+---------+-----+-----------+-----
If you are using MySQL server, then here is an
equivalent example −
LIMIT 3;
+----+---------+-----+-----------+-----
| ID | NAME | AGE | ADDRESS | SALA
+----+---------+-----+-----------+-----
| 1 | Ramesh | 32 | Ahmedabad | 2000
| 2 | Khilan | 25 | Delhi | 1500
| 3 | kaushik | 23 | Kota | 2000
+----+---------+-----+-----------+-----
+----+---------+-----+-----------+-----
| ID | NAME | AGE | ADDRESS | SALA
+----+---------+-----+-----------+-----
| 1 | Ramesh | 32 | Ahmedabad | 2000
| 2 | Khilan | 25 | Delhi | 1500
| 3 | kaushik | 23 | Kota | 2000
+----+---------+-----+-----------+-----
SELECT column-list
FROM table_name
[WHERE condition]
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
| | | | |
+----+----------+-----+-----------+----
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 3 | kaushik | 23 | Kota | 20
| 2 | Khilan | 25 | Delhi | 15
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
| 1 | Ramesh | 32 | Ahmedabad | 20
+----+----------+-----+-----------+----
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 7 | Muffy | 24 | Indore | 100
| 6 | Komal | 22 | MP | 45
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 5 | Hardik | 27 | Bhopal | 85
| 4 | Chaitali | 25 | Mumbai | 65
+----+----------+-----+-----------+----
SQL - Group By
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.
FROM table_name
WHERE [ conditions ]
Example
Consider the CUSTOMERS table is having the
following records −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
| kaushik | 2000.00 |
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 2000.00 |
+----------+-------------+
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Ramesh | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | kaushik | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+
Syntax
The basic syntax of DISTINCT keyword to
eliminate the duplicate records is as follows −
WHERE [condition]
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
First, let us see how the following SELECT query
returns the duplicate salary records.
ORDER BY SALARY;
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
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]
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
Following is an example, which would sort the
result in an ascending order by NAME and
SALARY.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 3 | kaushik | 23 | Kota |
| 2 | Khilan | 25 | Delhi |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
| 1 | Ramesh | 32 | Ahmedabad |
+----+----------+-----+-----------+-
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 7 | Muffy | 24 | Indore |
| 6 | Komal | 22 | MP |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 5 | Hardik | 27 | Bhopal |
| 4 | Chaitali | 25 | Mumbai |
+----+----------+-----+-----------+-
To fetch the rows with their own preferred order,
the SELECT query used would be as follows −
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 2 | Khilan | 25 | Delhi | 15
| 5 | Hardik | 27 | Bhopal | 85
| 3 | kaushik | 23 | Kota | 20
| 6 | Komal | 22 | MP | 45
| 4 | Chaitali | 25 | Mumbai | 65
| 7 | Muffy | 24 | Indore | 100
| 1 | Ramesh | 32 | Ahmedabad | 20
+----+----------+-----+-----------+----
SQL - Constraints
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.
Dropping Constraints
Any constraint that you have defined can be
dropped using the ALTER TABLE command with
the DROP CONSTRAINT option.
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.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+-----+---------------------+-------
|OID | DATE | CUSTOM
+-----+---------------------+-------
| 102 | 2009-10-08 00:00:00 |
| 100 | 2009-10-08 00:00:00 |
| 101 | 2009-11-20 00:00:00 |
| 103 | 2008-05-20 00:00:00 |
+-----+---------------------+-------
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Syntax
The basic syntax of a UNION clause is as
follows −
[WHERE condition]
UNION
[WHERE condition]
Example
Consider the following two tables.
+----+----------+-----+-----------+-
| | | | |
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+-----+---------------------+-------
|OID | DATE | CUSTOM
+-----+---------------------+-------
| 102 | 2009-10-08 00:00:00 |
| 100 | 2009-10-08 00:00:00 |
| 101 | 2009-11-20 00:00:00 |
| 103 | 2008-05-20 00:00:00 |
+-----+---------------------+-------
FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_
UNION
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_
+------+----------+--------+-----------
| ID | NAME | AMOUNT | DATE
+------+----------+--------+-----------
| 1 | Ramesh | NULL | NULL
| 2 | Khilan | 1560 | 2009-11-20
| 3 | kaushik | 3000 | 2009-10-08
| 3 | kaushik | 1500 | 2009-10-08
| 4 | Chaitali | 2060 | 2008-05-20
| 5 | Hardik | NULL | NULL
| 6 | Komal | NULL | NULL
Syntax
The basic syntax of the UNION ALL is as
follows.
[WHERE condition]
UNION ALL
[WHERE condition]
Example
Consider the following two tables,
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+-----+---------------------+-------
|OID | DATE | CUSTOM
+-----+---------------------+-------
| 102 | 2009-10-08 00:00:00 |
| 100 | 2009-10-08 00:00:00 |
| 101 | 2009-11-20 00:00:00 |
| 103 | 2008-05-20 00:00:00 |
+-----+---------------------+-------
FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_
+------+----------+--------+-----------
| ID | NAME | AMOUNT | DATE
+------+----------+--------+-----------
| 1 | Ramesh | NULL | NULL
| 2 | Khilan | 1560 | 2009-11-20
| 3 | kaushik | 3000 | 2009-10-08
| 3 | kaushik | 1500 | 2009-10-08
| 3 | kaushik | 1500 | 2009 10 08
| 4 | Chaitali | 2060 | 2008-05-20
| 5 | Hardik | NULL | NULL
| 6 | Komal | NULL | NULL
| 7 | Muffy | NULL | NULL
| 3 | kaushik | 3000 | 2009-10-08
| 3 | kaushik | 1500 | 2009-10-08
| 2 | Khilan | 1560 | 2009-11-20
Syntax
The basic syntax of NULL while creating a
table.
SQL> CREATE TABLE CUSTOMERS(
);
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.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
Now, following is the usage of the IS NOT
NULLoperator.
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
+----+----------+-----+-----------+----
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+----
Syntax
The basic syntax of a table alias is as follows.
WHERE [condition];
FROM table_name
WHERE [condition];
Example
Consider the following two tables.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+-----+---------------------+-------
|OID | DATE | CUSTOM
+-----+---------------------+-------
| 102 | 2009-10-08 00:00:00 |
| 100 | 2009-10-08 00:00:00 |
+----+----------+-----+--------+
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
+-------------+---------------+
| CUSTOMER_ID | CUSTOMER_NAME |
+-------------+---------------+
| 1 | Ramesh |
| 2 | Khilan |
| 3 | kaushik |
| 4 | Chaitali |
| 5 | Hardik |
| 6 | Komal |
| 7 | Muffy |
+-------------+---------------+
SQL - Indexes
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.
Single-Column Indexes
A single-column index is created based on only
one table column. The basic syntax is as
follows.
ON table_name (column_name);
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.
on table_name (column_name);
Composite Indexes
A composite index is an index on two or more
columns of a table. Its basic syntax is as
follows.
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.
Syntax
The basic syntax of an ALTER TABLE command
to add a New Column in an existing table is as
follows.
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
+----+---------+-----+-----------+-----
| ID | NAME | AGE | ADDRESS | SALA
+----+---------+-----+-----------+-----
| 1 | Ramesh | 32 | Ahmedabad | 200
| 2 | Ramesh | 25 | Delhi | 150
| 3 | kaushik | 23 | Kota | 200
| 4 | kaushik | 25 | Mumbai | 650
| 5 | Hardik | 27 | Bhopal | 850
| 6 | Komal | 22 | MP | 450
| 7 | Muffy | 24 | Indore | 1000
+----+---------+-----+-----------+-----
+----+---------+-----+-----------+-----
| ID | NAME | AGE | ADDRESS | SALA
+----+---------+-----+-----------+-----
| 1 | Ramesh | 32 | Ahmedabad | 200
| 2 | Ramesh | 25 | Delhi | 150
| 3 | kaushik | 23 | Kota | 200
| 4 | kaushik | 25 | Mumbai | 650
| 5 | Hardik | 27 | Bhopal | 850
| 6 | Komal | 22 | MP | 450
| 7 | Muffy | 24 | Indore | 1000
+----+---------+-----+-----------+-----
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 | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
Creating Views
Database views are created using the CREATE
VIEW statement. Views can be created from a
single table, multiple tables or another view.
FROM table_name
WHERE [condition];
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
FROM CUSTOMERS;
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
FROM CUSTOMERS
Updating a View
A view can be updated under certain conditions
which are given below −
SET AGE = 35
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 35 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 35 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
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 −
Syntax
The following code block shows the position of
the HAVING Clause in a query.
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
WHERE [ conditions ]
HAVING [ conditions ]
Example
Consider the CUSTOMERS table having the
following records.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
GROUP BY age
+----+--------+-----+---------+--------
| ID | NAME | AGE | ADDRESS | SALARY
+----+--------+-----+---------+--------
| 2 | Khilan | 25 | Delhi | 1500.00
+----+--------+-----+---------+--------
SQL - Transactions
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.
Properties of Transactions
Transactions have the following four standard
properties, usually referred to by the acronym
ACID.
Transactional Control
Commands
Transactional control commands are only used
with the DML Commands such as - INSERT,
UPDATE and DELETE only. They cannot be used
while creating tables or dropping them because
these operations are automatically committed
in the database.
COMMIT;
Example
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
SQL> COMMIT;
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 3 | kaushik | 23 | Kota | 20
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
ROLLBACK;
Example
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
SQL> ROLLBACK;
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 85
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
SAVEPOINT SAVEPOINT_NAME;
ROLLBACK TO SAVEPOINT_NAME;
Example
Consider the CUSTOMERS table having the
following records.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=
1 row deleted.
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=
1 row deleted.
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3
1 row deleted.
Rollback complete.
Notice that only the first deletion took place
since you rolled back to SP2.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
6 rows selected.
Syntax
The basic syntax of a '%' and a '_' operator is as
follows.
SELECT * FROM table_name
or
or
or
or
Example
The following table has a number of examples
showing the WHERE part having different LIKE
clauses with '%' and '_' operators.
Sr.No. Statement & Description
4
Finds any values that start with 2
and are at least 3 characters in
length.
7
Finds any values in a five-digit
number that start with 2 and end
with 3.
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 32 | Ahmedabad | 20
| 3 | kaushik | 23 | Kota | 20
+----+----------+-----+-----------+----
ADDDATE()
1
Adds dates
ADDTIME()
2
Adds time
CONVERT_TZ()
CURDATE()
4
Returns the current date
CURRENT_DATE(), CURRENT_DATE
5
Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME
6
Synonyms for CURTIME()
CURRENT_TIMESTAMP(),
CURRENT_TIMESTAMP
7
Synonyms for NOW()
CURTIME()
8
Returns the current time
DATE_ADD()
9
Adds two dates
DATE_FORMAT()
10
Formats date as specified
11 DATE_SUB()
DATEDIFF()
13
Subtracts two dates
DAY()
14
Synonym for DAYOFMONTH()
DAYNAME()
15
Returns the name of the weekday
DAYOFMONTH()
16
Returns the day of the month (1-31)
DAYOFWEEK()
DAYOFYEAR()
18
Returns the day of the year (1-366)
EXTRACT
19
Extracts part of a date
FROM_DAYS()
20
Converts a day number to a date
FROM_UNIXTIME()
21
Formats date as a UNIX timestamp
HOUR()
22
Extracts the hour
23 LAST_DAY
LOCALTIME(), LOCALTIME
24
Synonym for NOW()
LOCALTIMESTAMP,
LOCALTIMESTAMP()
25
Synonym for NOW()
MAKEDATE()
MAKETIME
27
MAKETIME()
MICROSECOND()
MINUTE()
MONTH()
MONTHNAME()
31
Returns the name of the month
NOW()
32
Returns the current date and time
33 PERIOD_ADD()
PERIOD_DIFF()
QUARTER()
SEC_TO_TIME()
SECOND()
37
Returns the second (0-59)
STR_TO_DATE()
38
Converts a string to a date
SUBDATE()
SUBTIME()
40
Subtracts times
SYSDATE()
TIME_FORMAT()
42
Formats as time
43 TIME_TO_SEC()
Returns the argument converted to
seconds
TIME()
TIMEDIFF()
45
Subtracts time
TIMESTAMP()
TIMESTAMPADD()
TIMESTAMPDIFF()
TO_DAYS()
UNIX_TIMESTAMP()
50
Returns a UNIX timestamp
UTC_DATE()
51
Returns the current UTC date
52 UTC_TIME()
WEEK()
54
Returns the week number
WEEKDAY()
55
Returns the weekday index
WEEKOFYEAR()
YEAR()
57
Returns the year
YEARWEEK()
58
Returns the year and week
ADDDATE(date,INTERVAL expr
unit), ADDDATE(expr,days)
When invoked with the INTERVAL form of the
second argument, ADDDATE() is a synonym for
DATE_ADD(). The related function SUBDATE() is
a synonym for DATE_SUB(). For information on
the INTERVAL unit argument, see the
discussion for DATE_ADD().
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.
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.
+-----------------------------------
| CURDATE()
+-----------------------------------
| 1997-12-15
+-----------------------------------
1 row in set (0.00 sec)
+-----------------------------------
| CURDATE() + 0
+-----------------------------------
| 19971215
+-----------------------------------
1 row in set (0.00 sec)
CURRENT_DATE and
CURRENT_DATE()
CURRENT_DATE and CURRENT_DATE() are
synonyms for CURDATE()
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.
+-----------------------------------
| CURTIME()
+-----------------------------------
| 23:50:26
+-----------------------------------
1 row in set (0.00 sec)
+-----------------------------------
| CURTIME() + 0
+-----------------------------------
| 235026
+-----------------------------------
1 row in set (0.00 sec)
CURRENT_TIME and
CURRENT_TIME()
CURRENT_TIME and CURRENT_TIME() are
synonyms for CURTIME().
CURRENT_TIMESTAMP and
CURRENT_TIMESTAMP()
CURRENT_TIMESTAMP and
CURRENT_TIMESTAMP() are synonyms for
NOW().
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.
DATE_ADD(date,INTERVAL expr
unit), DATE_SUB(date,INTERVAL
expr unit)
These functions perform date arithmetic. The
date is a DATETIME or DATE value specifying
the starting date. The expr is an expression
specifying the interval value to be added or
subtracted from the starting date. The expr is a
string; it may start with a '-' for negative
intervals.
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'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
DAY_MICROSECOND 'DAYS.MICROSECONDS'
DAY_SECOND 'DAYS
HOURS:MINUTES:SECONDS'
YEAR_MONTH 'YEARS-MONTHS'
+-----------------------------------
| DATE_ADD('1997-12-31 23:59:59', INT
+-----------------------------------
| 1998-01-01 00:01:00
+-----------------------------------
DATE_FORMAT(date,format)
This command formats the date value as per
the format string.
%a
1 Abbreviated weekday name
(Sun..Sat)
%b
2
Abbreviated month name (Jan..Dec)
%c
3
Month, numeric (0..12)
%D
4 Day of the month with English suffix
(0th, 1st, 2nd, 3rd, .)
%d
5
Day of the month, numeric (00..31)
%e
6
Day of the month, numeric (0..31)
%f
7
Microseconds (000000..999999)
%H
8
Hour (00..23)
%h
9
Hour (01..12)
10
%I
Hour (01..12)
%i
11
Minutes, numeric (00..59)
%j
12
Day of year (001..366)
%k
13
Hour (0..23)
%l
14
Hour (1..12)
%M
15
Month name (January..December)
%m
16
Month, numeric (00..12)
%p
17
AM or PM
%r
18 Time, 12-hour (hh:mm:ss followed by
AM or PM)
%S
19
Seconds (00..59)
20 %s
Seconds (00..59)
%T
21
Time, 24-hour (hh:mm:ss)
%U
22 Week (00..53), where Sunday is the
first day of the week
%u
23 Week (00..53), where Monday is the
first day of the week
%V
24 Week (01..53), where Sunday is the
first day of the week; used with %X
%v
25 Week (01..53), where Monday is the
first day of the week; used with %x
%W
26
Weekday name (Sunday..Saturday)
%w
27 Day of the week
(0=Sunday..6=Saturday)
28
%X
%x
29
Year for the week, where Monday is
the first day of the week, numeric,
four digits; used with %v
%Y
30
Year, numeric, four digits
%y
31
Year, numeric (two digits)
%%
32
A literal .%. character
%x
33
x, for any.x. not listed above
+-----------------------------------
| DATE_FORMAT('1997-10-04 22:23:00..
+-----------------------------------
| 22 22 10 10:23:00 PM 22:23:00 00
+-----------------------------------
1 row in set (0.00 sec)
DATE_SUB(date,INTERVAL expr
unit)
This is similar to the DATE_ADD() function.
DAY(date)
The DAY() is a synonym for the
DAYOFMONTH() function.
DAYNAME(date)
Returns the name of the weekday for date.
+-----------------------------------
| DAYNAME('1998-02-05')
+-----------------------------------
| Thursday
+-----------------------------------
1 row in set (0.00 sec)
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.
+-----------------------------------
| FROM_DAYS(729669)
+-----------------------------------
| 1997-10-07
+-----------------------------------
1 row in set (0.00 sec)
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.
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.
+-----------------------------------
| HOUR('10:05:03')
+-----------------------------------
| 10
+-----------------------------------
1 row in set (0.00 sec)
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.
LOCALTIMESTAMP and
LOCALTIMESTAMP()
LOCALTIMESTAMP and LOCALTIMESTAMP()
are synonyms for NOW().
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.
+-----------------------------------
| MAKETIME(12,15,30)
+-----------------------------------
| '12:15:30'
+-----------------------------------
1 row in set (0.00 sec)
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.
MONTH(date)
Returns the month for date, in the range 0 to 12.
+-----------------------------------
| MONTH('1998-02-03')
+-----------------------------------
| 2
+-----------------------------------
1 row in set (0.00 sec)
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.
+-----------------------------------
| NOW()
+-----------------------------------
| 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. Note that the period
argument P is not a date value.
+-----------------------------------
| PERIOD_ADD(9801,2)
+-----------------------------------
| 199803
+-----------------------------------
1 row in set (0.00 sec)
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.
+-----------------------------------
| SECOND('10:05:03')
+-----------------------------------
| 3
+-----------------------------------
1 row in set (0.00 sec)
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.
+-----------------------------------
| SEC TO TIME(2378)
| SEC_TO_TIME(2378)
+-----------------------------------
| 00:39:38
+-----------------------------------
1 row in set (0.00 sec)
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.
SUBDATE(date,INTERVAL expr
unit) and SUBDATE(expr,days)
When invoked with the INTERVAL form of the
second argument, SUBDATE() is a synonym for
DATE_SUB(). For information on the INTERVAL
unit argument, see the discussion for
DATE_ADD().
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.
+-----------------------------------
| SUBTIME('1997-12-31 23:59:59.99999
+-----------------------------------
| 1997-12-30 22:58:58.999997
+-----------------------------------
1 row in set (0.00 sec)
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.
+-----------------------------------
| SYSDATE()
+-----------------------------------
| 2006-04-12 13:47:44
+-----------------------------------
1 row in set (0.00 sec)
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.
+-----------------------------------
| TIMEDIFF('1997-12-31 23:59:59.0000
+-----------------------------------
| 46:58:57.999999
+-----------------------------------
1 row in set (0.00 sec)
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.
mysql> SELECT TIMESTAMP('2003-12-31'
+-----------------------------------
| TIMESTAMP('2003-12-31')
+-----------------------------------
| 2003-12-31 00:00:00
+-----------------------------------
1 row in set (0.00 sec)
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
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.
TIME_TO_SEC(time)
Returns the time argument converted to
seconds.
TO_DAYS(date)
Given a date, returns a day number (the number
of days since year 0).
+-----------------------------------
| TO_DAYS(950501)
+-----------------------------------
| 728779
+-----------------------------------
1 row in set (0.00 sec)
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.
+-----------------------------------
| UNIX_TIMESTAMP()
+-----------------------------------
| 882226357
+-----------------------------------
1 row in set (0.00 sec)
+-----------------------------------
| UNIX_TIMESTAMP('1997-10-04 22:23:0
+-----------------------------------
| 875996580
+-----------------------------------
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.
| 2003-08-14, 20030814
+-----------------------------------
1 row in set (0.00 sec)
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.
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
Mode First Day Range Week 1 is the
of week first week.
+-----------------------------------
| WEEK('1998-02-20')
+-----------------------------------
| 7
+-----------------------------------
1 row in set (0.00 sec)
WEEKDAY(date)
Returns the weekday index for date (0 =
Monday, 1 = Tuesday, . 6 = Sunday).
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.
+-----------------------------------
| YEAR('98-02-03')
+-----------------------------------
| 1998
+-----------------------------------
1 row in set (0.00 sec)
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.
mysql> SELECT YEARWEEK('1987-01-01')
+-----------------------------------
| YEAR('98-02-03')YEARWEEK('1987-01-
+-----------------------------------
| 198653
+-----------------------------------
1 row in set (0.00 sec)
Example
Here is an example showing you the usage of a
temporary table.
+--------------+-------------+------
| product_name | total_sales | avg_u
+--------------+-------------+------
| cucumber | 100.25 |
+--------------+-------------+------
1 row in set (0.00 sec)
+--------------+-------------+------
| product_name | total_sales | avg_u
+--------------+-------------+------
| cucumber | 100.25 |
+--------------+-------------+------
1 row in set (0.00 sec)
mysql> DROP TABLE SALESSUMMARY;
Example
Try out the following example to create a clone
table for TUTORIALS_TBL whose structure is
as follows −
[WHERE])
Example
Consider the CUSTOMERS table having the
following records −
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 35 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
+----+----------+-----+---------+------
| ID | NAME | AGE | ADDRESS | SALAR
+----+----------+-----+---------+------
| 4 | Ch it li | 25 | M b i | 6500
| 4 | Chaitali | 25 | Mumbai | 6500
| 5 | Hardik | 27 | Bhopal | 8500
| 7 | Muffy | 24 | Indore | 10000
+----+----------+-----+---------+------
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.
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
UPDATE table
(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.
+----+----------+-----+-----------+----
| ID | NAME | AGE | ADDRESS | SAL
+----+----------+-----+-----------+----
| 1 | Ramesh | 35 | Ahmedabad | 1
| 2 | Khilan | 25 | Delhi | 15
| 3 | kaushik | 23 | Kota | 20
| 4 | Chaitali | 25 | Mumbai | 65
| 5 | Hardik | 27 | Bhopal | 21
| 6 | Komal | 22 | MP | 45
| 7 | Muffy | 24 | Indore | 100
+----+----------+-----+-----------+----
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
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.
+----+----------+-----+---------+------
| ID | NAME | AGE | ADDRESS | SALAR
+----+----------+-----+---------+------
| 2 | Khilan | 25 | Delhi | 1500
| 3 | kaushik | 23 | Kota | 2000
| 4 | Chaitali | 25 | Mumbai | 6500
| 6 | Komal | 22 | MP | 4500
| 7 | Muffy | 24 | Indore | 10000
+----+----------+-----+---------+------
Using AUTO_INCREMENT
column
The simplest way in MySQL to use sequences
is to define a column as AUTO_INCREMENT
and leave the rest to MySQL to take care.
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.
-> (
-> id INT UNSIGNED NOT NULL AUTO_
-> PRIMARY KEY (id),
Obtain AUTO_INCREMENT
Values
The LAST_INSERT_ID( ) is an SQL function, so
you can use it from within any client that
understands how to issue SQL statements.
Otherwise PERL and PHP scripts provide
exclusive functions to retrieve auto-
incremented value of last record.
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. The
following example references it through the
database handle.
PHP Example
After issuing a query that generates an
AUTO_INCREMENT value, retrieve the value by
calling the mysql_insert_id( ) function.
Starting a Sequence at a
Particular Value
By default, MySQL will start the sequence from
1, but you can specify any other number as well
at the time of table creation.
-> (
-> id INT UNSIGNED NOT NULL AUTO_
-> PRIMARY KEY (id),
Syntax
The basic syntax of a DISTINCT keyword to
eliminate duplicate records is as follows.
WHERE [condition]
Example
Consider the CUSTOMERS table having the
following records.
+----+----------+-----+-----------+-
| ID | NAME | AGE | ADDRESS |
+----+----------+-----+-----------+-
| 1 | Ramesh | 32 | Ahmedabad |
| 2 | Khilan | 25 | Delhi |
| 3 | kaushik | 23 | Kota |
| 3 | kaushik | 23 | Kota |
| 4 | Chaitali | 25 | Mumbai |
| 5 | Hardik | 27 | Bhopal |
| 6 | Komal | 22 | MP |
| 7 | Muffy | 24 | Indore |
+----+----------+-----+-----------+-
ORDER BY SALARY;
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
SQL - Injection
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.
if (preg_match("/^\w{8,20}$/", $_GET
$result = mysql_query("SELECT * F
WHERE name = $matches[0]");
} else {
echo "user name not accepted";
if (get_magic_quotes_gpc()) {
$name = stripslashes($name);
}
$name = mysql_real_escape_string($nam
mysql query("SELECT * FROM CUSTOMERS
mysql_query( SELECT FROM CUSTOMERS
$sub = addcslashes(mysql_real_escape_
// $sub == \%str\_
Print Page