LO1 Write An SQL Statement To Retrieve and Sort Data: Using Basic Structured Query Language
LO1 Write An SQL Statement To Retrieve and Sort Data: Using Basic Structured Query Language
Most Relational Database Management Systems like MS SQL Server, Microsoft Access, Oracle,
MySQL, DB2, Sybase, PostgreSQL and Informix use SQL as a database querying language.
Even though SQL is defined by both ISO and ANSI there are many SQL implementation, which
do not fully comply with those definitions.
SQL, is a standardized computer language that was originally developed by IBM for querying,
altering and defining relational databases, using declarative statements. SQL is relatively simple
language, but it’s also very powerful.
SQL is pronounced SEQUEL. SQL was developed during the early 70’s at IBM.
Even if SQL is a standard, many of the database systems that exist today implement their own
version of the SQL language.
MS SQL Server is a paid database server, but it has a free limited version called MSDE
(Microsoft SQL Server Desktop Engine). MSDE version of MS SQL Server is free for re-
distribution with desktop applications. As we mentioned MSDE has certain restrictions, like:
The maximum size of a database is 2 GB
MSDE comes with no administration tools.
MSDE has has a governor which will slower the db server response once you exceed 5
concurrent connections to it.
MS SQL Server uses SQL as its standard database language. The SQL dialect used by MS SQL
Server is called T-SQL.
The latest MS SQL Server version available on the market is MS SQL Server 2008.
2. Oracle
Oracle is aObject- relational database management system developed by Oracle Corporation.The
Oracle RDBMS is used in many database applications on sevarl OS platforms, including Unix
and Windows.
Founding of Oracle
In 1977, Larry Ellison, Bob Miner, and Ed Oates started the consultancy Software Development
Laboratories, which became Relational Software, Inc. (RSI). In 1983, RSI became Oracle
Systems Corporation and then later Oracle Corporation.
First commercially available RDBMS
In 1979, RSI introduced Oracle V2 (Version 2) as the first commercially available SQL-based
RDBMS, a landmark event in the history of relational databases.
Objects and partitioning
Oracle8 was released in 1997 as the object-relational database, supporting many new data types.
Additionally, Oracle8 supported partitioning of large tables.
The Oracle database was the first commercial RDBMS that became available on Linux during
the summer of1999. The Oracle datatabase is more expensive compared to MS SQL Server.
MySQL is most commonly used for Web applications and for embedded applications and has
become a popular alternative to proprietary database systems because of its speed and reliability.
MySQL can run on UNIX, Windows and Mac OS. MySQL is developed, supported and
marketed by MySQL AB.
4. Microsoft Access
it’s one of the most popular Microsoft products. MS Access comes with the professional edition
of MS Office package. MS Access is a paid product and runs only on Windows platform.
MS Access has easy to use intuitive graphical interface, which makes it one of the most popular
database software among small business.
5. IBM DB2
DB2 is relational database management system developed by IBM. DB2 is the first database
product that used SQL language. DB2 was first available on the mainframe and later moved to
UNIX, Linux and Windows platforms.
DB2 has the ability to handle millions of transactions and huge sets of data. DB2 is very scalable
and can handle serious workloads.DB2’s main competitor is Oracle. DB2 is a low cost
alternative to MS SQL Server and Oracle databases. DB2 is usually administered through multi-
platform java client GUI.
Data storage and definition language – special type of DDL in which the storage structure and
access methods used by the database system are specified.
The most basic items of DDL are the CREATE, ALTER, RENAME and DROP statements:
CREATE creates an object (a table, for example) in the database.
DROP deletes an object in the database, usually irretrievably.
ALTER modifies the structure an existing object in various ways—for example, adding a
column to an existing table
TRUNCATE - remove all records from a table, including all spaces allocated for the records
are removed
COMMENT - add comments to the data dictionary
RENAME - rename an object
2. Data Manipulation Language (DML)
The DML Language for accessing and manipulating the data organized by the appropriate data
model. It is the subset of SQL used to add, update and delete data and statements are used for
managing data within schema objects.
The acronym CRUD refers to all of the major functions that need to be implemented in a
relational database application to consider it complete. Each letter in the acronym can be mapped
to a standard SQL statement:
Windows Server 2008 also provides the Hyper-V virtualization systems. SQL Server 2008 and
all of its components, including SSRS, are supported in virtual environments created using
Hyper-V, provided of course sufficient CPU and RAM resources are allocated to the virtual
machine and that the virtual machine runs an operating system supported by SQL Server
Reporting Services (SSRS).
Tables 5.4, 5.5, and 5.6 list operating system requirements and additional software requirements
for installation of Reporting Services on 32- and 64-bit platforms.
TABLE 5.4 Operating Systems That Can Run 32-Bit Versions of Report Server
NOTE
Systems that are not explicitly listed in Table 5.4 are not supported by Reporting Services. For
example, Reporting Services 32-bit is not supported on Windows 2003 64-bit Itanium.
For situations with heavy memory or I/O requirements, such as heavy graphics and PDF
rendering, customers can benefit from deploying SSRS on a 64-bit platform. Table 5.5 outlines
SSRS support on a 64-bit platform.
Express
Enterprise x64 Standard x64 Workgroup x64 Web x64
x64
Windows XP Pro x64 No Yes Yes Yes No
Windows Server 2003 Standard x64 Yes Yes Yes Yes Yes
Windows Server 2003 Data Center
Yes Yes Yes Yes Yes
x64
Windows Server 2003 Enterprise x64 Yes Yes Yes Yes Yes
Windows Vista x64 Ultimate No Yes Yes Yes Yes
Windows Vista x64 Home Premium No No Yes No Yes
Windows Vista x64 Home Basic No No Yes No Yes
Windows Vista x64 Enterprise No Yes Yes Yes Yes
Windows Vista x64 Business No Yes Yes Yes Yes
Windows Server 2008 Standard x64 Yes Yes Yes Yes Yes
Windows Server 2008 Data Center
Yes Yes Yes Yes Yes
x64
Windows Server 2008 Enterprise x64 Yes Yes Yes Yes Yes
The following operating systems are supported by SQL Server Enterprise/Developer Edition
IA64:
Note that with any 64-bit operating system, management tools may be supported in WOW64.
WOW64 allows native 32-bit code to execute natively on non-32-bit systems.
NOTE
Development tools such as Business Intelligence Development Studio (BIDS) are neither
installed nor supported on the IA64 platform. For IA64 deployments, use development tools
installed on a separate 32-bit or x64 workstation.
Table 5.6 outlines additional software requirements for both 32- and 64-bit platforms and
optional software that can be installed to benefit Reporting Services.
.NET Framework Windows 2003 IA63 requires .NET Framework 2.0 SP1.
Microsoft Data Access Components (MDAC) All versions require MDAC 2.8 SP1 or higher.
3. Setup Support Rules opens. Click on "show details to ensure that all the tests passed
succesfully
Then click on OK
6. The SQL Server 2008 Setup opens with a first "product key" tab
As we use a specific free version of SQL Serveur, no activation key is needed.
Simply click "next"
10. On the "features selection" tab choose "Data Engine Services" and "Management tools" (this
is the Management Studio Express)
check the features directory (no need to change normally) click "next"
11. On the "instance Configuration" check that the parameters are like the screenshot on the left
(nothing to change normally)
Click "Next"
19. Complete:
Once installed, click on "Close"
20. To ensure SQL Express is running correctly, run "SQL Server Configuration Manager"
On the left column click on "SQL Server Services
On the right column, ensure that SQL Server (SQLEXPRESS) is running correctly (otherwhise
right-click on the device to start it)
21. Browse the new directory "Microsoft SQL Server 2008" and open the SQL Server
Management Studio to ensure it has been correctly installed
22. If you used to work with SQL Server 2000 our SQL Server 2005 before, you will probably
obtain this message
"Do you want to import your customized user settings...". Simply click Yes (or no as you prefer
it doesn't matters concerning Octopus)
* You can find the name of your computer on the control panel>System
Does it opens ? -> Congratulations, you can now go to the next step: Install Octopus
NOTE: Be careful before using this operation because by deleting an existing database would
result in loss of complete information stored in the database.
Make sure you have admin privilege before dropping any database. Once a database is dropped,
you can check it in the list of databases as follows:
MySQL> SHOW DATABASES; Or Ms SQL> select * from sys.DATABASES
+--------------------+
CREATE TABLE is the keyword telling the database system what you want to do. In this case,
you want to create a new table. The unique name or identifier for the table follows the CREATE
TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data type it is.
The syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.
Example: Following is an example, which creates a CUSTOMERS table with ID as primary key
and NOT NULL are the constraints showing that these fields can not be NULL while creating
records in this table:
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
You can verify if your table has been created successfully by looking at the message displayed
by the SQL server, otherwise you can use DESC command as follows:
Syntax: The basic syntax for creating a table from another table is as follows:
CREATE TABLE NEW_TABLE_NAME AS
SELECT [ column1, column2...columnN ]
FROM EXISTING_TABLE_NAME
[ WHERE ]
Here, column1, column2...are the fields of existing table and same would be used to create fields
of new table.
Example: Following is an example, which would create a table SALARY using CUSTOMERS
table and having fields customer ID and customer SALARY:
SQL> CREATE TABLE SALARY AS
SELECT ID, SALARY
FROM CUSTOMERS;
This would create new table SALARY, which would have the following records:
+----+----------+
| ID | SALARY |
+----+----------+
| 1 | 2000.00 |
| 2 | 1500.00 |
| 3 | 2000.00 |
| 4 | 6500.00 |
| 5 | 8500.00 |
| 6 | 4500.00 |
| 7 | 10000.00 |
+----+----------+
Drop Table
The SQL DROP TABLE statement is used to remove a table definition and all data, indexes,
triggers, constraints, and permission specifications for that table.
NOTE: You have to be careful while using this command because once a table is deleted then
all the information available in the table would also be lost forever.
Example: Let us first verify CUSTOMERS table and then we would delete it from the database:
SQL> DESC CUSTOMERS; or Sp_help CUSTOMERS; in Ms SQL
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
This means CUSTOMERS table is available in the database, so let us drop it as follows:
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
Now, if you would try DESC command, then you would get error as follows:
SQL> DESC CUSTOMERS; or Sp_help CUSTOMERS; in Ms SQL
ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist
Here, TEST is database name which we are using for our examples.
Alter Table
The SQL ALTER TABLE command is used to add, delete or modify columns in an existing
table. You would also use ALTER TABLE command to add and drop various constraints on an
existing table.
Syntax: The basic syntax of ALTER TABLE to add a new column in an existing table is as
follows:
ALTER TABLE table_name ADD column_name datatype;
The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows:
ALTER TABLE table_name DROP COLUMN column_name;
The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as
follows:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as
follows:
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows:
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as
follows:
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
The basic syntax of ALTER TABLE to DROP CONSTRAINT from a table is as follows:
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;
The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as
follows:
ALTER TABLE table_name
DROP CONSTRAINT MyPrimaryKey;
Now, CUSTOMERS table is changed and following would be output from SELECT statement:
+----+---------+-----+-----------+----------+------+
| ID | NAME | AGE | ADDRESS | SALARY | SEX |
+----+---------+-----+-----------+----------+------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL |
| 2 | Ramesh | 25 | Delhi | 1500.00 | NULL |
| 3 | kaushik | 23 | Kota | 2000.00 | NULL |
| 4 | kaushik | 25 | Mumbai | 6500.00 | NULL |
| 5 | Hardik | 27 | Bhopal | 8500.00 | NULL |
| 6 | Komal | 22 | MP | 4500.00 | NULL |
| 7 | Muffy | 24 | Indore | 10000.00 | NULL |
+----+---------+-----+-----------+----------+------+
Following is the example to DROP sex column from existing table:
ALTER TABLE CUSTOMERS DROP SEX;
Now, CUSTOMERS table is changed and following would be output from SELECT statement:
+----+---------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+---------+-----+-----------+----------+
1.3.2 Inserting Records
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax: There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into which you
want to insert data.
You may not need to specify the column(s) name in the SQL query if you are adding values for
all the columns of the table. But make sure the order of the values is in the same order as the
columns in the table. The SQL INSERT INTO syntax would be as follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
You can create a record in CUSTOMERS table using second syntax as follows:
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in CUSTOMERS table:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Populate one table using another table:
You can populate data into a table through select statement over another table provided another
table has a set of fields, which are required to populate first table. Here is the syntax:
INSERT INTO first_table_name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];
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;
Following is an example, which would fetch ID, Name and Salary fields of the customers
available in CUSTOMERS table:
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
If you want to fetch all the fields of CUSTOMERS table, then use the following query:
SQL> SELECT * FROM CUSTOMERS;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Note: Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute
accuracy.
Character Strings Data Types:
DATA FROM TO
TYPE
char char Maximum length of 8,000 characters.( Fixed length non-
Unicode characters)
varchar varchar Maximum of 8,000 characters.(Variable-length non-Unicode
data).
varchar(max varchar(max) Maximum length of 231characters, Variable-length non-
) Unicode data (SQL Server 2005 only).
text text Variable-length non-Unicode data with a maximum length of
2,147,483,647 characters.
1.3.3.2 Expressions
An expression is a combination of one or more values, operators, and SQL functions that
evaluate to a value.
SQL EXPRESSIONs are like formulas and they are written in query language. You can also use
them to query the database for specific set of data.
Syntax:
Consider the basic syntax of the SELECT statement as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE [CONDITION|EXPRESSION];
There are different types of SQL expressions, which are mentioned below:
Syntax
SELECT [column_name | * | expression] <comparison operator>
[column_name | * | expression ]
FROM <table_name>
WHERE <expression> [ comparison operator] <expression>;
Operator Description
ALL The ALL operator is used to compare a value to all values in another value set.
AND The AND operator allows the existence of multiple conditions in an SQL
statement's WHERE clause.
ANY The ANY operator is used to compare a value to any applicable value in the list
according to the condition.
BETWEE The BETWEEN operator is used to search for values that are within a set of
N values, given the minimum value and the maximum value.
EXISTS The EXISTS operator is used to search for the presence of a row in a specified
table that meets certain criteria.
IN The IN operator is used to compare a value to a list of literal values that have
been specified.
LIKE The LIKE operator is used to compare a value to similar values using wildcard
operators.
NOT The NOT operator reverses the meaning of the logical operator with which it is
used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.
OR The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause.
IS NULL The NULL operator is used to compare a value with a NULL value.
UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness
(no duplicates).
Syntax
SELECT [column_name | * | expression] [logical operator]
[column_name | * | expression .....]
FROM <table_name>
WHERE <expressions> [ logical operator |
arithmetic operator | ...] <expressions>;
For example: if you want to find the names of students who are studying either Maths or Science,
the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject = 'Maths' OR subject = 'Science'
For Example: To find the names of the students between the age 10 to 15 years, the query would
be like:
SELECT first_name, last_name, age
FROM student_details
WHERE age >= 10 AND age <= 15;
Mathematical operators are provided for many PostgreSQL types. For types without common
mathematical conventions for all possible permutations (e.g., date/time types) we describe the
actual behavior in subsequent sections.
Table 9-3 shows the available mathematical functions. In the table, dp indicates double precision.
Many of these functions are provided in multiple forms with different argument types. Except
where noted, any given form of a function returns the same data type as its argument. The
functions working with double precision data are mostly implemented on top of the host system's
C library; accuracy and behavior in boundary cases may therefore vary depending on the host
system.
Finally, Table 9-4 shows the available trigonometric functions. All trigonometric functions take
arguments and return values of type double precision.
1.3.3.3FROM Clause
SQL FROM Syntax
SQL FROM clause allows us to specify table name (or view) that we want to use to retrieve
certain fields. The most basic syntax is below:
SELECT * FROM TableName
The FROM clause specifies the target table(s) for SELECT, UPDATE, and DELETE statements.
Example Syntax:
FROM table [[AS] alias]
FROM table1 [INNER|LEFT OUTER|RIGHT OUTER|FULL OUTER] JOIN table2 ON
join-criteria
FROM table1 CROSS JOIN table2
FROM (subquery) [AS] alias
FROM TABLE(subquery) [AS] alias
The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE,
DELETE statement, etc.
Syntax: The basic syntax of SELECT statement with WHERE clause is as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc.
Below examples would make this concept clear.
Following is an example which would fetch ID, Name and Salary fields from the CUSTOMERS
table where salary is greater than 2000:
SQL> SELECT ID, NAME, SALARY
SQL TOP:-
The SQL TOP clause is used to fetch a TOP N number or X percent records from a table.
Note: All the databases do not support TOP clause. For example MySQL supports LIMIT
clause to fetch limited number of records and Oracle uses ROWNUM to fetch limited number of
records.
Syntax:
The basic syntax of TOP clause with SELECT statement would be as follows:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE [condition]
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example on SQL server, which would fetch top 3 records from CUSTOMERS
table:
BY:- Ermias Israel
Page 26
Using Basic Structured Query Language
SQL> SELECT TOP 3 * FROM CUSTOMERS;
This would produce the following result:
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
If you are using MySQL server, then here is an equivalent example:
SQL> SELECT * FROM CUSTOMERS
LIMIT 3;
This would produce the following result:
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
If you are using Oracle server, then here is an equivalent example:
SQL> SELECT * FROM CUSTOMERS
WHERE ROWNUM <= 3;
Syntax: The basic syntax of DELETE query with WHERE clause is as follows:
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example: Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200
WHERE SALARY LIKE Finds any values that have 200 in any position
'%200%'
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with a 3
WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and end with 3
Let us take a real example, consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would display all the records from CUSTOMERS table where
SALARY starts with 200:
SQL> SELECT * FROM CUSTOMERS
WHERE SALARY LIKE '200%';
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y helados Constitución 2222 D.F.
3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico
Taquería Moreno D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
IN Operator Example: The following SQL statement selects all customers with a City of
"Paris" or "London":
SELECT * FROM Customers
WHERE City IN ('Paris','London');
NOT BETWEEN Operator Example: to display the products outside the range of the
previous example, use NOT BETWEEN:
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN Operator with IN Example: The following SQL statement selects all products
with a price BETWEEN 10 and 20, but products with a CategoryID of 1,2, or 3 should not be
displayed:
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
BETWEEN Operator with Text Value Example: - The following SQL statement selects
all products with a ProductName beginning with any of the letter BETWEEN 'C' and 'M':
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';
NOT BETWEEN Operator with Text Value Example:-The following SQL statement
selects all products with a ProductName beginning with any of the letter NOT BETWEEN 'C'
and 'M':
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
Sample Table: Below is a selection from the "Orders" table:
OrderI CustomerID EmployeeID OrderDate ShipperID
D
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
BETWEEN Operator with Date Value Example: - The following SQL statement selects
all orders with an OrderDate BETWEEN '04-July-1996' and '09-July-1996':
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
SQL Constraints
Constraints are the rules enforced on data columns on table. These are used to limit the type of
data that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints could be column level or table level. Column level constraints are applied only to
one column, whereas table level constraints are applied to the whole table.
Following are commonly used constraints available in SQL.
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.
Constraints can be specified when a table is created with the CREATE TABLE statement or you
can use ALTER TABLE statement to create constraints even after the table is created.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns, three of which, ID and NAME and AGE, specify not to accept NULLs:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to
SALARY column in Oracle and MySQL, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL;
DEFAULT Constraint
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO
statement does not provide a value for this column, then by default this column would be set to
5000.00.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID));
If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY
column, you would write a statement similar to the following:
UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the CUSTOMERS table, for example, you might want to prevent two or more people
from having identical age.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with
same age:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);
DROP a UNIQUE Constraint:
To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myUniqueConstraint;
If you are using MySQL, then you can use the following syntax:
ALTER TABLE CUSTOMERS
DROP INDEX myUniqueConstraint;
PRIMARY Key
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Note: You would use these concepts while creating database tables.
Example: Here is the syntax to define ID attribute as a primary key in a CUSTOMERS table.
To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already
exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table was first
created).
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME));
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
Delete Primary Key:
You can clear the primary key constraints from the table, Use Syntax:
ALTER TABLE CUSTOMERS DROP PRIMARY KEY ;
FOREIGN Key
A foreign key is a key used to link two tables together. This is sometimes called a referencing
key. Foreign Key is a column or a combination of columns whose values match a Primary Key in
a different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a
Foreign Key in the second table.
If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Example: Consider the structure of the two tables as follows: CUSTOMERS table:
CREATE TABLE CUSTOMERS(
If ORDERS table has already been created, and the foreign key has not yet been set, use the
syntax for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn't entered into the table.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, we add a CHECK with AGE column, so that you can not have any
CUSTOMER below 18 years:
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
BY:- Ermias Israel
Page 36
Using Basic Structured Query Language
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);
DROP a CHECK Constraint:
To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myCheckConstraint;
INDEX
The INDEX is used to create and retrieve data from the database very quickly. Index can be
created by using single or group of columns in a table. When index is created, it is assigned a
ROWID for each row before it sorts out the data.
Proper indexes are good for performance in large databases, but you need to be careful while
creating index. Selection of fields depends on what you are using in your SQL queries.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
Now, you can create index on single or multiple columns using the following syntax:
CREATE INDEX index_name
ON table_name ( column1, column2.....);
To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL syntax:
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
DROP an INDEX Constraint:
To drop an INDEX constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
BY:- Ermias Israel
Page 37
Using Basic Structured Query Language
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
1. INNER JOIN
The most frequently used and important of the joins is the INNER JOIN. They are also referred
to as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate. The query compares each row of table1 with each row
of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a result
row.
Syntax: The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
2. LEFT JOIN
BY:- Ermias Israel
Page 39
Using Basic Structured Query Language
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if the ON clause matches 0 (zero) records in right table, the join will
still return a row in the result, but with NULL in each column from right table.
This means that a left join returns all the values from the left table, plus matched values from the
right table or NULL in case of no matching join predicate.
3. RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the
left table. This means that if the ON clause matches 0 (zero) records in left table, the join will
still return a row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from
the left table or NULL in case of no matching join predicate.
5. SELF JOIN
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us join this table using SELF JOIN as follows:
SQL> SELECT a.ID, b.NAME, a.SALARY
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;
This would produce the following result:
+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |
----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
Example: Consider the following two tables; (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+------+----------+--------+---------------------+
The UNION ALL Clause:
The UNION ALL operator is used to combine the results of two SELECT statements including
duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator.
Now, let us join these two tables in our SELECT statement as follows:
3. EXCEPT: the SQL EXCEPT clause/operator is used to combine two SELECT statements
and returns rows from the first SELECT statement that are not returned by the second SELECT
statement. This means EXCEPT returns only rows, which are not available in second SELECT
statement. Just as with the UNION operator, the same rules apply when using the EXCEPT
operator. MySQL does not support EXCEPT operator.
Example: Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Alias Name
You can rename a table or a column temporarily by giving another name known as alias.
The use of table aliases means to rename a table in a particular SQL statement. The renaming is a
temporary change and the actual table name does not change in the database. The column aliases
are used to rename a table's columns for the purpose of a particular SQL query.
Syntax: The basic syntax of table alias is as follows:
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
The basic syntax of column alias is as follows:
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Example: Consider the following two tables; (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
Following is an example, which would sort the result in ascending order by NAME and
SALARY:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;
Following is an example, which would sort the result in descending order by NAME:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;
SQL GROUP BY
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. The GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.
Syntax: The basic syntax of GROUP BY clause is given below.
The GROUP BY clause must follow the conditions in the WHERE clause and must precede the
ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Example: Consider the CUSTOMERS table is having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to know the total amount of salary on each customer, then GROUP BY query would
be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
This would produce the following result:
+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
| kaushik | 2000.00 |
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 2000.00 |
+----------+-------------+
Now, let us have following table where CUSTOMERS table has the following records with
duplicate names:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
First, let us see how the following SELECT query returns duplicate salary records:
SQL> SELECT SALARY FROM CUSTOMERS
ORDER BY SALARY;
This would produce the following result where salary 2000 is coming twice which is a duplicate
record from the original table.
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
Now, let us use DISTINCT keyword with the above SELECT query and see the result:
SQL> SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY;
This would produce the following result where we do not have any duplicate entry:
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
2.2 Introduction to Functions
2.2.1 Date Functions
Date and Time Functions in SQL Server 2008
GETDATE()
The GETDATE() function returns the current date and time from the SQL Server.
Syntax: select GETDATE()
Note: The time part above goes all the way to milliseconds.
Example: - The following SQL creates an "Orders" table with a datetime column (OrderDate):
CREATE TABLE Orders
( OrderId int NOT NULL PRIMARY KEY,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE())
Notice that the OrderDate column specifies GETDATE() as the default value. As a result, when
you insert a row into the table, the current date and time are automatically inserted into the
column.
Now we want to insert a record into the "Orders" table:
INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese')
SYSDATETIME()
This function works the same as GETDATE(); it returns date and time. The difference in both
functions is that SYSDATETIME returns a higher level of precision and also returns the
newer datetime2 data type.
select SYSDATETIME()
DAY()
This function returns an integer representing the day part of the specified date.
select DAY(<date>)
MONTH()
This function returns an integer representing the month part of the specified date.
select MONTH(<date>)
YEAR()
This function returns an integer representing the year part of the specified date.
select YEAR(<date>)
DATEADD()
The DATEADD() function adds or subtracts a specified time interval from a date.
Syntax: - Select DATEADD(datepart,number,date)
Where date is a valid date expression and number is the number of interval you want to add. The
number can either be positive, for dates in the future, or negative, for dates in the past.
datepart can be one of the following:
OrderId OrderPayDate
1 2008-12-26 13:23:44.657
DATEDIFF()
This function returns the difference between two specified dates in a specified unit of time.
DATEDIFF(<datepart>, <startdate>, <enddate>)
Syntax:- select DATEDIFF(datepart,startdate,enddate)
Where startdate and enddate are valid date expressions and datepart can be one of the following:
Example: - Now we want to get the number of days between two dates.
We use the following SELECT statement:
SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate
Result:
DiffDate
61
Example:-Now we want to get the number of days between two dates (notice that the second
date is "earlier" than the first date, and will result in a negative number).
DATENAME()
This function returns a string representing the name of the specified datepart of the specified
date.
select DATENAME(<datepart>, <date>)
DATEPART()
The DATEPART() function is used to return a single part of a date/time, such as year, month,
day, hour, minute, etc.
Syntax: - select DATEPART(datepart,date)
Where date is a valid date expression and datepart can be one of the following:
datepart Abbreviation week wk, ww
year yy, yyyy weekday dw, w
quarter qq, q hour hh
month mm, m minute mi, n
dayofyear dy, y second ss, s
day dd, d millisecond ms
BY:- Ermias Israel
Page 57
Using Basic Structured Query Language
CONVERT()
The CONVERT() function is a general function that converts an expression of one data type to
another. The CONVERT() function can be used to display date/time data in different formats.
Syntax:- CONVERT(data_type(length),expression,style)
Value Description
data_type(length) Specifies the target data type (with an optional length)
expression Specifies the value to be converted
style Specifies the output format for the date/time
The table below represent the style values for datetime or smalldatetime conversion to character
data:
Value Value Input/Output Standard
(century yy) (century yyyy)
- 0 or 100 mon dd yyyy hh:miAM (or PM) Default
1 101 mm/dd/yy USA
2 102 yy.mm.dd ANSI
3 103 dd/mm/yy British/French
4 104 dd.mm.yy German
5 105 dd-mm-yy Italian
6 106 dd mon yy
7 107 Mon dd, yy
8 108 hh:mm:ss
- 9 or 109 mon dd yyyy hh:mi:ss:mmmAM (or PM) Default+millisec
10 110 mm-dd-yy USA
Example:- The following script uses the CONVERT() function to display different formats. We
will use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
Now suppose based on the above table you want to fetch maximum value of daily_typing_pages,
then you can do so simply using the following command:
+------+------+-------------------------+
| id | name | MAX(daily_typing_pages) |
+------+------+-------------------------+
| 3 | Jack | 170 |
| 4 | Jill | 220 |
| 1 | John | 250 |
| 2 | Ram | 220 |
| 5 | Zara | 350 |
+------+------+-------------------------+
5 rows in set (0.00 sec)
You can use MIN Function along with MAX function to find out minimum value as well. Try
out the following example:
+-------+------+
| least | max |
+-------+------+
| 100 | 350 |
+-------+------+
1 row in set (0.01 sec)
Now suppose based on the above table you want to calculate average of all the
dialy_typing_pages, then you can do so by using the following command:
SQL> SELECT AVG(daily_typing_pages)
-> FROM employee_tbl;
+-------------------------+
| AVG(daily_typing_pages) |
+-------------------------+
| 230.0000 |
+-------------------------+
1 row in set (0.03 sec)
You can take average of various records set using GROUP BY clause. Following example will
take average all the records related to a single person and you will have average typed pages by
every person.
+------+-------------------------+
| name | AVG(daily_typing_pages) |
+------+-------------------------+
| Jack | 135.0000 |
| Jill | 220.0000 |
| John | 250.0000 |
| Ram | 220.0000 |
| Zara | 325.0000 |
+------+-------------------------+
5 rows in set (0.20 sec)
Now suppose based on the above table you want to calculate total of all the dialy_typing_pages,
then you can do so by using the following command:
SQL> SELECT SUM(daily_typing_pages)
-> FROM employee_tbl;
+-------------------------+
| SUM(daily_typing_pages) |
+-------------------------+
| 1610 |
+-------------------------+
1 row in set (0.00 sec)
You can take sum of various records set using GROUP BY clause. Following example will sum
up all the records related to a single person and you will have total typed pages by every person.
SQL> SELECT name, SUM(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;
BY:- Ermias Israel
Page 63
Using Basic Structured Query Language
+------+-------------------------+
| name | SUM(daily_typing_pages) |
+------+-------------------------+
| Jack | 270 |
| Jill | 220 |
| John | 250 |
| Ram | 220 |
| Zara | 650 |
+------+-------------------------+
5 rows in set (0.17 sec)
6. SQL CONCAT Function
SQL CONCAT function is used to concatenate two strings to form a single string.
To understand CONCAT function in more detail, consider an employee_tbl table, which is
having the following records:
Now suppose based on the above table you want to concatenate all the names employee ID and
work_date, then you can do it using the following command:
Syntax: The basic syntax of ORDER BY clause which would be used to sort result in
ascending or descending order is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you
are using to sort, that column should be in column-list.
Example: Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would sort the result in ascending order by NAME and
SALARY:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;
The HAVING clause must follow the GROUP BY clause in a query and must also precede the
ORDER BY clause if used. The following is the syntax of the SELECT statement, including the
HAVING clause:
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
A subquery can be used any place where an expression is allowed providing it returns a single
value. This means that a subquery that returns a single value can also be listed as an object in a
FROM clause listing. This is termed an inline view because when a subquery is used as part of a
FROM clause, it is treated like a virtual table or view. Subquery can be placed either in FROM
clause, WHERE clause or HAVING clause of the main query.
Oracle allows a maximum nesting of 255 subquery levels in a WHERE clause. There is no limit
for nesting subqueries expressed in a FROM clause.In practice, the limit of 255 levels is not
really a limit at all because it is rare to encounter subqueries nested beyond three or four levels.
A subquery SELECT statement is very similar to the SELECT statement used to begin a regular
or outer query.The complete syntax of a subquery is:
Types of Subqueries
Single Row Sub Query: Sub query which returns single row output. They mark the usage of
single row comparison operators, when used in WHERE conditions.
Multiple row sub query: Sub query returning multiple row output. They make use of multiple
row comparison operators like IN, ANY, ALL. There can be sub queries returning multiple
columns also.
Correlated Sub Query: Correlated subqueries depend on data provided by the outer query.This
type of subquery also includes subqueries that use the EXISTS operator to test the existence of
data rows satisfying specified criteria.
In the below SELECT query, inner SQL returns only one row i.e. the minimum salary for the
company. It in turn uses this value to compare salary of all the employees and displays only
those, whose salary is equal to minimum salary.
A HAVING clause is used when the group results of a query need to be restricted based on some
condition. If a subquery's result must be compared with a group function, you must nest the inner
query in the outer query's HAVING clause.
Below query shows the error when single row sub query returns multiple rows.
[< ALL] Less than the lowest value returned by the subquery
[< ANY] Less than the highest value returned by the subquery
[> ANY] More than the lowest value returned by the subquery
Note in the above query, IN matches department ids returned from the sub query,compares it
with that in the main query and returns employee's name who satisfy the condition. A join would
be better solution for above query, but for purpose of illustration, sub query has been used in it.
Correlated subqueries can produce result tables that answer complex management questions.
Consider the below SELECT query. Unlike the subqueries previously considered, the subquery
in this SELECT statement cannot be resolved independently of the main query. Notice that the
outer query specifies that rows are selected from the employee table with an alias name of e1.
The inner query compares the employee department number column (DepartmentNumber) of the
employee table with alias e2 to the same column for the alias table name e1.
When a multiple-column subquery is used in the outer query's FROM clause, it creates a
temporary table that can be referenced by other clauses of the outer query. This temporary table
is more formally called an inline view. The subquery's results are treated like any other table in
the FROM clause. If the temporary table contains grouped data, the grouped subsets are treated
as separate rows of data in a table. Consider the FROM clause in the below query. The inline
view formed by the subquery is the data source for the main query.
SELECT *
FROM (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000);
4.2 Views
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from
one or many tables which depend on the written SQL query to create a view.
Views, which are kind of virtual tables, allow users to do the following:
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data such that a user can see and (sometimes) modify exactly what
they need and no more.
Summarize data from various tables which can be used to generate reports.
Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table.
Following is the example:
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result:
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
Updating a View:
A view can be updated under certain conditions:
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY clause.
The FROM clause may not contain multiple tables.
The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or HAVING.
Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in order for
the INSERT query to function.
So if a view satisfies all the above-mentioned rules then you can update a view. Following is an
example to update the age of Ramesh:
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name='Ramesh';
This would ultimately update the base table CUSTOMERS and same would reflect in the view
itself. Now, try to query base table, and SELECT statement would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
This would ultimately delete a row from the base table CUSTOMERS and same would reflect in
the view itself. Now, try to query base table, and SELECT statement would produce the
following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Dropping Views:
Obviously, where you have a view, you need a way to drop the view if it is no longer needed.
The syntax is very simple as given below:
DROP VIEW view_name;
Following is an example to drop CUSTOMERS_VIEW from CUSTOMERS table:
DROP VIEW CUSTOMERS_VIEW;