Structured Query Language (SQL) by Joshua Godspower - 043945
Structured Query Language (SQL) by Joshua Godspower - 043945
LANGUAGE (SQL)
Hands on Practical
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.
Also, they are using different dialects, such as: MS SQL Server using T-SQL,
Oracle using PL/SQL, MS Access version of SQL is called JET SQL (native format)
etc.
Why SQL?
SQL is widely popular because it offers the following advantages:
Allows users to access data in the relational database management
systems.
Allows users to describe the data.
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.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a database.
Allows users to set permissions on tables, procedures and views.
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:
DDL - Data Definition Language
Command Description
CREATE Creates a new table, a view of a table, or other object in the database.
ALTER Modifies an existing database object, such as a table.
DROP Deletes an entire table, a view of a table or other objects in the database.
2 STRUCTURED QUERY LANGUAGE (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.
A Relational database management system (RDBMS) is a database management
system (DBMS) that is based on the relational model as introduced by E. F. Codd.
What is 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 |
+----+----------+-----+-----------+----------+
3 STRUCTURED QUERY LANGUAGE (SQL)
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.
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 |
+----+------+
What is a NULL value?
A NULL value in a table is a value in a field that appears to be blank, which means
a field with a NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value
or a field that contains spaces. A field with a NULL value is the one that has been
left blank during a record creation.
4 STRUCTURED QUERY LANGUAGE (SQL)
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:
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.
PRIMARY Key: Uniquely identifies each row/record in a database table.
FOREIGN Key: Uniquely identifies a row/record in any another database
table.
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:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the type,
the format, or the range of values.
Referential integrity: Rows cannot be deleted, which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall into
entity, domain or referential integrity.
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.
5 STRUCTURED QUERY LANGUAGE (SQL)
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.
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.
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
SQL LIKE Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SQL ORDER BY Clause
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
SQL GROUP BY Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SQL COUNT Clause
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
SQL HAVING Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
SQL CREATE TABLE Statement
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns ) );
7 STRUCTURED QUERY LANGUAGE (SQL)
| 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:
SQL> select 12 % 5;
Output:
+---------+
| 12 % 5 |
+---------+
|2|
+---------+
1 row in set (0.00 sec)
+----+---------+-----+-----------+---------+
| 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:
SQL> SELECT * FROM CUSTOMERS WHERE SALARY != 2000;
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 4:
SQL> SELECT * FROM CUSTOMERS WHERE SALARY <> 2000;
Output:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
13 STRUCTURED QUERY LANGUAGE (SQL)
+----+----------+-----+---------+----------+
| 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:
SQL> SELECT * FROM CUSTOMERS WHERE SALARY >= 6500;
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)
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.
OR: The OR operator is used to combine multiple conditions in an SQL
Statement’s WHERE clause.
IS NULL: The NULL operator is used to compare a value with a NULL value.
UNIQUE: The UNIQUE operator searches every row of a specified table for
uniqueness (no duplicates).
Logical Operators – Examples
Consider the CUSTOMERS table having the following records:
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| 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)
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)
15 STRUCTURED QUERY LANGUAGE (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:
SQL> SELECT * FROM CUSTOMERS WHERE AGE IS NOT NULL;
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)
Example 4:
SQL> SELECT * FROM CUSTOMERS WHERE NAME LIKE 'Ko%';
Output:
+----+-------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+-------+-----+---------+---------+
| 6 | Komal | 22 | MP | 4500.00 |
16 STRUCTURED QUERY LANGUAGE (SQL)
+----+-------+-----+---------+---------+
1 row in set (0.00 sec)
Example 5:
SQL> SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
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:
SQL> SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;
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:
SQL> SELECT AGE FROM CUSTOMERS
WHERE EXISTS (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
Output:
+-----+
| AGE |
+-----+
| 32 |
| 25 |
| 23 |
| 25 |
| 27 |
17 STRUCTURED QUERY LANGUAGE (SQL)
| 22 |
| 24 |
+-----+
7 rows in set (0.02 sec)
Example 8:
SQL> SELECT * FROM CUSTOMERS
WHERE AGE > ALL (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
Output:
+----+--------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+--------+-----+-----------+---------+
1 row in set (0.02 sec)
Example 9:
SQL> SELECT * FROM CUSTOMERS
WHERE AGE > ANY (SELECT AGE FROM CUSTOMERS WHERE 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 |
+----+----------+-----+-----------+---------+
4 rows in set (0.00 sec)
Expression
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
18 STRUCTURED QUERY LANGUAGE (SQL)
+---------------------+
1 row in set (0.00 sec)
Another date expression is as shown below:
SQL> SELECT GETDATE();;
+-------------------------+
| GETDATE |
+-------------------------+
| 2009-10-22 12:07:18.140 |
+-------------------------+
1 row in set (0.00 sec)
CREATE DATABASE
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:
CREATE DATABASE DatabaseName;
Always the database name should be unique within the RDBMS.
Example
If you want to create a new database <testDB>, then the CREATE DATABASE
statement would be as shown below:
SQL> CREATE DATABASE testDB;
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:
SQL> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+--------------------+
21 STRUCTURED QUERY LANGUAGE (SQL)
column2 datatype,
column3 datatype,
.....
columnN datatype, PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do.
In this case, you want to create a new table. The unique name or identifier for the
table follows the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of
data type it is. The syntax becomes clearer with 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:
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
You can verify if your table has been created successfully by looking at the
message displayed by the SQL server, otherwise you can use the DESC command
as follows:
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
24 STRUCTURED QUERY LANGUAGE (SQL)
Example
Following is an example which would create a table SALARY using the
CUSTOMERS table and having the fields – customer ID and customer SALARY:
SQL> CREATE TABLE SALARY AS
SELECT ID, SALARY
FROM CUSTOMERS;
This would create a new table SALARY which will have the following records.
+----+----------+
| ID | SALARY |
+----+----------+
| 1 | 2000.00 |
| 2 | 1500.00 |
25 STRUCTURED QUERY LANGUAGE (SQL)
| 3 | 2000.00 |
| 4 | 6500.00 |
| 5 | 8500.00 |
| 6 | 4500.00 |
| 7 | 10000.00 |
+----+----------+
This means that the CUSTOMERS table is available in the database, so let us now
drop it as shown below.
Example
The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
27 STRUCTURED QUERY LANGUAGE (SQL)
You can create a record in the CUSTOMERS table by using the second syntax as
shown below.
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
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 |
+----+----------+-----+-----------+----------+
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.
28 STRUCTURED QUERY LANGUAGE (SQL)
Syntax
The basic syntax of the SELECT statement is as follows.
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values you want to fetch.
If you want to fetch all the fields available in the field, then you can use the
following syntax.
SELECT * FROM table_name;
Example
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 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.
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;
\
This would produce the following result:
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
29 STRUCTURED QUERY LANGUAGE (SQL)
| 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.
SQL> SELECT * FROM CUSTOMERS;
This would produce the result 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 |
+----+----------+-----+-----------+----------+
Syntax
The basic syntax of the SELECT statement with the WHERE clause is as shown
below.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
30 STRUCTURED QUERY LANGUAGE (SQL)
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:
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;
15. SQL ─ WHERE Clause
This would produce the following result:
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
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.
31 STRUCTURED QUERY LANGUAGE (SQL)
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 |
32 STRUCTURED QUERY LANGUAGE (SQL)
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
16. SQL ─ AND & OR Conjunctive Operators
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.
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 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.
Syntax
The basic syntax of the UPDATE query with a WHERE clause is as follows:
34 STRUCTURED QUERY LANGUAGE (SQL)
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.
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
Now, the CUSTOMERS table would have the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
35 STRUCTURED QUERY LANGUAGE (SQL)
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.
Syntax
The basic syntax of % and _ is as follows:
SELECT FROM table_name
WHERE column LIKE 'XXXX%'
Or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
Or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
Or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
Or
SELECT FROM table_name
WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here, XXXX
could be any numeric or string value.
Example
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.
38 STRUCTURED QUERY LANGUAGE (SQL)
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.
The basic syntax of the TOP clause with a SELECT statement would be as follows.
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE [condition]
Example
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following query is an example on the SQL server, which would fetch the top 3
records from the CUSTOMERS table.
SQL> SELECT TOP 3 * FROM CUSTOMERS;
20. SQL ─ TOP, LIMIT or ROWNUM Clause
This would produce the following result:
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
If you are using MySQL server, then here is an equivalent example:
SQL ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending or descending
order, based on one or more columns. Some 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 |
41 STRUCTURED QUERY LANGUAGE (SQL)
+----+----------+-----+-----------+----------+
| 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.
To fetch the rows with their own preferred order, the SELECT query used would
be as follows:
SQL> SELECT * FROM CUSTOMERS
ORDER BY (CASE ADDRESS
WHEN 'DELHI' THEN 1
WHEN 'BHOPAL' THEN 2
WHEN 'KOTA' THEN 3
WHEN 'AHMADABAD' THEN 4
WHEN 'MP' THEN 5
ELSE 100 END) ASC, ADDRESS DESC;
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.
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.
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+
Syntax
The basic syntax of DISTINCT keyword to eliminate the duplicate records is as
follows:
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Example
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
First, let us see how the following SELECT query returns the duplicate salary
records.
ORDER BY SALARY;
23. SQL ─ Distinct Keyword
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 |
+----------+
47 STRUCTURED QUERY LANGUAGE (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.
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 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.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identifies each row/record in a database table.
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.
You can also use the following syntax, which supports naming the constraint in
multiple columns as well.
If you are using MySQL, then you can use the following 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).
For defining a PRIMARY KEY constraint on multiple columns, use the SQL syntax
given below.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME)
);
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax.
If a table has a primary key defined on any field(s), then you cannot have two
records having the same value of that field(s).
Example
Consider the structure of the following two tables.
CUSTOMERS Table:
If the condition evaluates to false, the record violates the constraint and isn't
entered the table.
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.
You can also use the following syntax, which supports naming the constraint in
multiple columns as well:
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.
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.
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.
The SQL Joins clause is used to combine records from two or more tables in a
database.
A JOIN is a means for combining fields from two tables by using values common
to each.
Consider the following two tables:
Example
Consider the following two tables.
Table 1: CUSTOMERS Table is as follows.
58 STRUCTURED QUERY LANGUAGE (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 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS Table is as follows.
+-----+---------------------+-------------+--------+
| OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the INNER JOIN as follows:
Example
Consider the following two tables,
Table 1: CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS Table is as follows.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the RIGHT JOIN as follows.
Here, the given condition could be any given expression based on your
requirement.
Example
Consider the following two tables.
Table 1: CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS Table is as follows.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
63 STRUCTURED QUERY LANGUAGE (SQL)
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using FULL JOIN as follows.
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
Here, the WHERE clause could be any given expression based on your
requirement.
Example
Consider the following table.
CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us join this table using SELF JOIN as follows:
65 STRUCTURED QUERY LANGUAGE (SQL)
The basic syntax of the CARTESIAN JOIN or the CROSS JOIN is as follows:
Example
Consider the following two tables.
Table 1: CUSTOMERS table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS Table is as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using INNER JOIN as follows:
Here, the given condition could be any given expression based on your
requirement.
Example
Consider the following two tables.
Table 1: CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS Table is as follows.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
69 STRUCTURED QUERY LANGUAGE (SQL)
Here, the given condition could be any given expression based on your
requirement.
Example
Consider the following two tables,
Table 1: CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS table is as follows.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
71 STRUCTURED QUERY LANGUAGE (SQL)
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.
Here, the given condition could be any given expression based on your
requirement.
Example
Consider the following two tables.
Table 1: CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
73 STRUCTURED QUERY LANGUAGE (SQL)
Here, the given condition could be any given expression based on your
requirement.
Example
Consider the following two tables.
Table 1: CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS table is as follows.
75 STRUCTURED QUERY LANGUAGE (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, let us join these two tables in our SELECT statement as shown below.
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.
76 STRUCTURED QUERY LANGUAGE (SQL)
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.
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 |
| 6 | Komal | 22 | MP | |
77 STRUCTURED QUERY LANGUAGE (SQL)
| 7 | Muffy | 24 | Indore | |
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.
+-----+---------------------+-------------+--------+
Now, the following code block shows the usage of a table alias.
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.
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax
is as follows.
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:
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.
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
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 |
86 STRUCTURED QUERY LANGUAGE (SQL)
Now, the CUSTOMERS table is truncated and the output from SELECT statement
will be as shown in the code block below:
87 STRUCTURED QUERY LANGUAGE (SQL)
Creating Views
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to
the specific implementation.
The basic CREATE VIEW syntax is as follows:
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 |
88 STRUCTURED QUERY LANGUAGE (SQL)
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual
table. Following is an example for the same.
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 –
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY clause.
The FROM clause may not contain multiple tables.
The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or HAVING.
Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in order
for the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update 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.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
90 STRUCTURED QUERY LANGUAGE (SQL)
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 |
91 STRUCTURED QUERY LANGUAGE (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:
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 |
34. SQL ─ Having Clause
| 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 a record for a similar age count that
would be more than or equal to 2.
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.
Consistency: ensures that the database properly changes states upon a
successfully committed transaction.
Isolation: enables transactions to operate independently of and transparent to
each other.
Durability: ensures that the result or effect of a committed transaction persists in
case of a system failure.
TRANSACTION CONTROL
The following commands are used to control transactions.
COMMIT: to save the changes.
ROLLBACK: to roll back the changes.
SAVEPOINT: creates points within the groups of transactions in which to
ROLLBACK.
SET TRANSACTION: Places a name on a transaction.
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.
+----+----------+-----+-----------+----------+
| 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 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
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.
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 |
+----+----------+-----+-----------+----------+
96 STRUCTURED QUERY LANGUAGE (SQL)
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.
The syntax for rolling back to a SAVEPOINT is as shown below.
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 |
| 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 contains the series of operations.
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.
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
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.
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.
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 '_00%'
Finds any values that have 00 in the second and third positions.
WHERE SALARY LIKE '2_%_%'
Finds any values that start with 2 and are at least 3 characters in length.
WHERE SALARY LIKE '%2' Finds any values that end with 2.
WHERE SALARY LIKE '_2%3'
Finds any values that have a 2 in the second position and end with a 3.
WHERE SALARY LIKE '2___3'
Finds any values in a five-digit number that start with
2 and end with 3.
Let us take a real example, consider the CUSTOMERS table having the following
records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
100 STRUCTURED QUERY LANGUAGE (SQL)
Name Description
ADDDATE() Adds dates
ADDTIME() Adds time
CONVERT_TZ() Converts from one timezone to another
CURDATE() Returns the current date
CURRENT_DATE(),
CURRENT_DATE
Synonyms for CURDATE()
CURRENT_TIME(),
CURRENT_TIME
Synonyms for CURTIME()
CURRENT_TIMESTAMP(),
CURRENT_TIMESTAMP
Synonyms for NOW()
CURTIME() Returns the current time
DATE_ADD() Adds two dates
101 STRUCTURED QUERY LANGUAGE (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.
mysql> SELECT CURDATE();
+---------------------------------------------------------+
| CURDATE() |
+---------------------------------------------------------+
| 1997-12-15 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT CURDATE() + 0;
+---------------------------------------------------------+
| CURDATE() + 0 |
+---------------------------------------------------------+
| 19971215 |
+---------------------------------------------------------+
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.
mysql> SELECT DATE('2003-12-31 01:02:03');
+---------------------------------------------------------+
| DATE('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 2003-12-31 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
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.
The values QUARTER and WEEK are available from the MySQL 5.0.0 version.
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
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, .)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
108 STRUCTURED QUERY LANGUAGE (SQL)
%V
Week (01..53), where Sunday is the first day of the week; used with
%X
%v
Week (01..53), where Monday is the first day of the week; used with
%x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X
Year for the week where Sunday is the first day of the week, numeric, four digits;
used with %V
%x
Year for the week, where Monday is the first day of the week, numeric, four digits;
used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal .%. character
%x x, for any.x. not listed above
DAY(date)
The DAY() is a synonym for the DAYOFMONTH() function.
DAYNAME(date)
Returns the name of the weekday for date.
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.
+---------------------------------------------------------+
1 row in set (0.00 sec)
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
mysql> SELECT DAYOFYEAR('1998-02-03');
+---------------------------------------------------------+
| DAYOFYEAR('1998-02-03') |
+---------------------------------------------------------+
| 34 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
FROM_DAYS(N)
Given a day number N, returns a DATE value.
mysql> SELECT FROM_DAYS(729669);
111 STRUCTURED QUERY LANGUAGE (SQL)
+---------------------------------------------------------+
| FROM_DAYS(729669) |
+---------------------------------------------------------+
| 1997-10-07 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
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).
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.
MAKETIME(hour,minute,second)
Returns a time value calculated from the hour, minute and second arguments.
mysql> SELECT MAKETIME(12,15,30);
+---------------------------------------------------------+
| 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.
113 STRUCTURED QUERY LANGUAGE (SQL)
MONTH(date)
Returns the month for date, in the range 0 to 12.
mysql> SELECT MONTH('1998-02-03')
+---------------------------------------------------------+
| MONTH('1998-02-03') |
+---------------------------------------------------------+
|2|
+---------------------------------------------------------+
1 row in set (0.00 sec)
MONTHNAME(date)
Returns the full name of the month for a date.
mysql> SELECT MONTHNAME('1998-02-05');
+---------------------------------------------------------+
| MONTHNAME('1998-02-05') |
+---------------------------------------------------------+
| February |
+---------------------------------------------------------+
1 row in set (0.00 sec)
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.
mysql> SELECT NOW();
+---------------------------------------------------------+
| NOW() |
+---------------------------------------------------------+
| 1997-12-15 23:50:26 |
114 STRUCTURED QUERY LANGUAGE (SQL)
+---------------------------------------------------------+
1 row in set (0.00 sec)
QUARTER(date)
Returns the quarter of the year for date, in the range 1 to 4.
mysql> SELECT QUARTER('98-04-01');
+---------------------------------------------------------+
| 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.
mysql> SELECT SECOND('10:05:03');
+---------------------------------------------------------+
| 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.
mysql> SELECT 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
115 STRUCTURED QUERY LANGUAGE (SQL)
TIME(expr)
Extracts the time part of the time or datetime expression expr and returns it as a
string.
mysql> SELECT TIME('2003-12-31 01:02:03');
+---------------------------------------------------------+
| TIME('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 01:02:03 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
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.
mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001','1997-12-30
01:01:01.000002');
+---------------------------------------------------------+
| TIMEDIFF('1997-12-31 23:59:59.000001'..... |
+---------------------------------------------------------+
| 46:58:57.999999 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIMESTAMPADD(unit,interval,datetime_expr)
117 STRUCTURED QUERY LANGUAGE (SQL)
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_.
For example, DAY and SQL_TSI_DAY both are legal.
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_TO_SEC(time)
Returns the time argument converted to seconds.
mysql> SELECT TIME_TO_SEC('22:23:00');
+---------------------------------------------------------+
| TIME_TO_SEC('22:23:00') |
+---------------------------------------------------------+
| 80580 |
+---------------------------------------------------------+
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.
mysql> SELECT UTC_DATE(), UTC_DATE() + 0;
+---------------------------------------------------------+
| UTC_DATE(), UTC_DATE() + 0 |
+---------------------------------------------------------+
| 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.
mysql> SELECT UTC_TIME(), UTC_TIME() + 0;
+---------------------------------------------------------+
| UTC_TIME(), UTC_TIME() + 0 |
+---------------------------------------------------------+
| 18:07:53, 180753 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
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.
119 STRUCTURED QUERY LANGUAGE (SQL)
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 of week Range Week 1 is the first week.
0 Sunday 0-53 with a Sunday in this year
1 Monday 0-53 with more than 3 days this year
2 Sunday 1-53 with a Sunday in this year
3 Monday 1-53 with more than 3 days this year
4 Sunday 0-53 with more than 3 days this year
5 Monday 0-53 with a Monday in this year
6 Sunday 1-53 with more than 3 days this year
7 Monday 1-53 with a Monday in this year
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday).
mysql> SELECT WEEKDAY('1998-02-03 22:23:00');
+---------------------------------------------------------+
120 STRUCTURED QUERY LANGUAGE (SQL)
| WEEKDAY('1998-02-03 22:23:00') |
+---------------------------------------------------------+
|1|
1 row in set (0.00 sec)
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.
mysql> SELECT YEAR('98-02-03');
+---------------------------------------------------------+
| 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.
+---------------------------------------------------------+
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.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
in the subquery can be modified with any of the character, date or number
functions.
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
124 STRUCTURED QUERY LANGUAGE (SQL)
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.
125 STRUCTURED QUERY LANGUAGE (SQL)
This would impact two rows and finally the CUSTOMERS table would have the
following records.
+----+----------+-----+---------+----------+
| 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 |
+----+----------+-----+---------+----------+
A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand.
Sequences are frequently used in databases because many applications require
each row in a table to contain a unique value and sequences provide an easy way
to generate them.
This chapter describes how to use sequences in MySQL.
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.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Example
128 STRUCTURED QUERY LANGUAGE (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.
129 STRUCTURED QUERY LANGUAGE (SQL)
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+