Using Basic Structured Query Language: What Is SQL?
Using Basic Structured Query Language: What Is SQL?
Using Basic Structured Query Language: What Is SQL?
What is SQL?
SQL (Structured Query Language) is a database computer language designed for managing data
in relational database management systems (RDBMS).
Most Relational Database Management Systems like MS SQL Server, Microsoft Access, Oracle,
MySQL, DB2, Sybase, PostgreSQL and Informix use SQL as a database querying language.
Even though SQL is defined by both ISO and ANSI there are many SQL implementation, which
do not fully comply with those definitions.
SQL, is a standardized computer language that was originally developed by IBM for querying,
altering and defining relational databases, using declarative statements. SQL is relatively simple
language, but it’s also very powerful.
SQL is pronounced SEQUEL. SQL was developed during the early 70’s at IBM.
Even if SQL is a standard, many of the database systems that exist today implement their own
version of the SQL language.
1|Page
Using Basic Structured Query Language
Database Applications:
Database management systems were developed to handle the following difficulties of typical
file-processing systems supported by conventional operating systems:
There are lots of different database systems, or DBMS- Database Management Systems, such as:
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:
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|Page
Using Basic Structured Query Language
2. Oracle
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.
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.
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 can be used free of charge (open source license), MySQL is an open source relational
database management system released under GNU General Public License. The Swedish
company called MySQL AB develops MySQL. This is partly because it is completely free but
also very powerful.
MySQL is most commonly used for Web applications and for embedded applications and has
3|Page
Using Basic Structured Query Language
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.
SQL Command
All DDL commands are auto-committed. That means it saves all the changes permanently in the
database.
Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table
4|Page
Using Basic Structured Query Language
DML : Data Manipulation Language
DML commands are not auto-committed. It means changes are not permanent to database, they
can be rolled back.
Command Description
insert to insert a new row
update to update existing row
delete to delete a row
merge merging two rows or two tables
These commands are to keep a check on other commands and their affect on the database. These
commands can annul changes made by other commands by rolling back to original state. It can
also make changes permanent.
Command Description
commit to permanently save
rollback to undo change
savepoint to save temporarily
Data control language provides command to grant and take back authority.
Command Description
grant grant permission of right
revoke take back permission.
Command Description
select retrieve records from one or more table
Create command
5|Page
Using Basic Structured Query Language
Creating a Database
Creating a Table
create command is also used to create a table. We can specify names and datatypes of various
columns along.Following is the Syntax,
create table command will tell the database system to create a new table with given table name
and column information.
The above command will create a new table Student in database system with 3 columns, namely
id, name and age.
alter command
alter command is used for alteration of table structures. There are various uses of alter
command, such as,
6|Page
Using Basic Structured Query Language
alter is also used to drop a column.
Using alter command we can add a column to an existing table. Following is the Syntax,
The above command will add a new column address to the Student table
Using alter command we can even add multiple columns to an existing table. Following is the
Syntax,
The above command will add three new columns to the Student table
alter command can add a new column to an existing table with default values. Following is the
Syntax,
The above command will add a new column with default value to the Student table
7|Page
Using Basic Structured Query Language
alter command is used to modify data type of an existing column . Following is the Syntax,
The above command will modify address column of the Student table
To Rename a column
Using alter command you can rename an existing column. Following is the Syntax,
To Drop a Column
alter command is also used to drop columns also. Following is the Syntax,
The above command will drop address column from the Student table
8|Page
Using Basic Structured Query Language
truncate command
truncate command removes all records from a table. But this command will not destroy the
table's structure. When we apply truncate command on a table its Primary key is initialized.
Following is its Syntax,
The above query will delete all the records of Student table.
truncate command is different from delete command. delete command will delete all the rows
from a table whereas truncate command re-initializes a table(like a newly created table).
For eg. If you have a table with 10 rows and an auto_increment primary key, if you use delete
command to delete all the rows, it will delete all the rows, but will not initialize the primary key,
hence if you will insert any row after using delete command, the auto_increment primary key
will start from 11. But in case of truncate command, primary key is re-initialized.
drop command
drop query completely removes a table from database. This command will also destroy the table
structure. Following is its Syntax,
The above query will delete the Student table completely. It can also be used on Databases. For
Example, to drop a database,
The above query will drop a database named Test from the system.
9|Page
Using Basic Structured Query Language
rename query
DML command
Data Manipulation Language (DML) statements are used for managing data in database. DML
commands are not auto-committed. It means changes made by DML command are not
permanent to database, it can be rolled back.
1) INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
Both the statements below will insert NULL value into age column of the Student table.
10 | P a g e
Using Basic Structured Query Language
Or,
The above command will insert only two column value other column is set to null.
Suppose the age column of student table has default value of 14.
Also, if you run the below query, it will insert default value into the age column, whatever the
default value may be.
2) UPDATE command
Update command is used to update a row of a table. Following is its general syntax,
11 | P a g e
Using Basic Structured Query Language
The above command will update two columns of a record.
3) Delete command
Delete command is used to delete data from a table. Delete command can also be used with
condition to delete a particular row. Following is its general syntax,
The above command will delete all the records from Student table.
The above command will delete the record where s_id is 103 from Student table.
12 | P a g e
Using Basic Structured Query Language
TCL command
Commit command
commit;
Rollback command
This command restores the database to last commited state. It is also use with savepoint
command to jump to a savepoint in a transaction.
rollback to savepoint-name;
Savepoint command
savepoint command is used to temporarily save a transaction so that you can rollback to that
point whenever necessary.
savepoint savepoint-name;
13 | P a g e
Using Basic Structured Query Language
ID NAME
1 abhi
2 adam
4 alex
Lets use some SQL queries on the above table and see the results.
ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris
7 bravo
rollback to B;
SELECT * from class;
ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris
rollback to A;
SELECT * from class;
14 | P a g e
Using Basic Structured Query Language
ID NAME
1 abhi
2 adam
4 alex
5 abhijit
DCL command
Data Control Language(DCL) is used to control privilege in Database. To perform any operation
in the database, such as for creating tables, sequences or views we need privileges. Privileges are
of two types,
System : creating session, table etc are all types of system privilege.
Object : any command or query to work on tables comes under object privilege.
15 | P a g e
Using Basic Structured Query Language
WHERE clause
Where clause is used to specify condition while retriving data from table. Where clause is used
mostly with Select, Update and Delete query. If condititon specified by where clause is true then
only the result from table is returned.
SELECT column-name1,
column-name2,
column-name3,
column-nameN
from table-name WHERE [condition];
Now we will use a SELECT statement to display data of the table, based on a condition, which
we will add to the SELECT query using WHERE clause.
SELECT s_id,
s_name,
age,
address
16 | P a g e
Using Basic Structured Query Language
from Student WHERE s_id=101;
s_id s_Name age address
101 Adam 15 Noida
SELECT Query
Select query is used to retrieve data from a tables. It is the most used SQL query. We can retrieve
complete tables, or partial by mentioning conditions using WHERE clause.
The above query will fetch information of s_id, s_name and age column from Student table
A special character asterisk * is used to address all the data(belonging to all columns) in a query.
SELECT statement uses * character to retrieve all records from a table.
17 | P a g e
Using Basic Structured Query Language
The above query will show all the records of Student table, that means it will show complete
Student table as result.
The above command will display a new column in the result, showing 3000 added into existing
salaries of the employees.
Like clause
Like clause is used as condition in SQL query. Like clause compares data with an expression
using wildcard operators. It is used to find similar data from the table.
18 | P a g e
Using Basic Structured Query Language
Wildcard operators
There are two wildcard operators that are used in like clause.
The above query will return all records where s_name starts with character 'A'.
Example
The above query will return all records from Student table where s_name contain 'd' as second
character.
Example
The above query will return all records from Student table where s_name contain 'x' as last
character.
19 | P a g e
Using Basic Structured Query Language
102 Alex 18
Order By Clause
Order by clause is used with Select statement for arranging retrieved data in sorted order. The
Order by clause by default sort data in ascending order. To sort data in descending order DESC
keyword is used with Order by clause.
Syntax of Order By
The above query will return result in ascending order of the salary.
20 | P a g e
Using Basic Structured Query Language
Consider the Emp table described above,
The above query will return result in descending order of the salary.
Group By Clause
Group by clause is used to group the results of a SELECT query based on one or more columns.
It is also used with SQL functions to group the result from one or more tables.
Here we want to find name and age of employees grouped by their salaries
21 | P a g e
Using Basic Structured Query Language
from Emp group by salary
name age
Rohan 34
shane 29
anu 22
name salary
Rohan 6000
Shane 8000
Scott 9000
You must remember that Group By clause will always come at the end, just like the Order by
clause
HAVING Clause
having clause is used with SQL Queries to give more precise condition for a statement. It is used
to mention condition in Group based SQL functions, just like WHERE clause.
22 | P a g e
Using Basic Structured Query Language
WHERE column_name condition
GROUP BY column_name
HAVING function(column_name) condition
Suppose we want to find the customer whose previous_balance sum is more than 3000.
SELECT *
from sale group customer
having sum(previous_balance) > 3000
Distinct keyword
The distinct keyword is used with Select statement to retrieve unique values from the table.
Distinct removes all the duplicate records while retrieving from database.
Example
23 | P a g e
Using Basic Structured Query Language
Consider the following Emp table.
The above query will return only the unique salary from Emp table
salary
5000
8000
10000
AND and OR operators are used with Where clause to make more precise conditions for
fetching data from database by combining more than one condition together.
AND operator
Example of AND
The above query will return records where salary is less than 10000 and age greater than 25.
OR operator
OR operator is also used to combine multiple conditions with Where clause. The only difference
between AND and OR is their behaviour. When we use AND to combine two or more than two
conditions, records satisfying all the condition will be in the result. But in case of OR, atleast one
condition from the conditions specified must be satisfied by any record to be in the result.
Example of OR
The above query will return records where either salary is greater than 10000 or age greater than
25.
SQL Constraints
SQL Constraints are rules used to limit the type of data that can go into a table, to maintain the
accuracy and integrity of the data inside table.
Constraints are used to make sure that the integrity of data is maintained in the database.
Following are the most used constraints that can be applied to a table.
25 | P a g e
Using Basic Structured Query Language
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
NOT NULL constraint restricts a column from having a NULL value. Once NOT NULL
constraint is applied to a column, you cannot pass a null value to that column. It enforces a
column to contain a proper value. One important point to note about NOT NULL constraint is
that it cannot be defined at table level.
CREATE table Student(s_id int NOT NULL, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will not take NULL value.
UNIQUE Constraint
UNIQUE constraint ensures that a field or column will only have unique values. A UNIQUE
constraint field will not have duplicate data. UNIQUE constraint can be applied at column level
or table level.
CREATE table Student(s_id int NOT NULL UNIQUE, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will only have unique values
and wont take NULL value.
26 | P a g e
Using Basic Structured Query Language
ALTER table Student add UNIQUE(s_id);
The above query specifies that s_id field of Student table will only have unique value.
Primary key constraint uniquely identifies each record in a database. A Primary Key must
contain unique value and it must not contain null value. Usually Primary Key is used to index the
data inside the table.
CREATE table Student (s_id int PRIMARY KEY, Name varchar(60) NOT NULL, Age
int);
FOREIGN KEY is used to relate two tables. FOREIGN KEY constraint is also used to restrict
actions that would destroy links between tables. To understand FOREIGN KEY, let's see it using
two table.
Customer_Detail Table :
27 | P a g e
Using Basic Structured Query Language
102 Alex Delhi
103 Stuart Rohtak
Order_Detail Table :
In Customer_Detail table, c_id is the primary key which is set as foreign key in Order_Detail
table. The value that is entered in c_id which is set as foreign key in Order_Detail table must be
present in Customer_Detail table where it is set as primary key. This prevents invalid data to be
inserted into c_id column of Order_Detail table.
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference of c_id
column of Customer_Detail.
There are two ways to maintin the integrity of data in Child table, when a particular record is
deleted in main table. When two tables are connected with Foriegn key, and certain data in the
main table is deleted, for which record exit in child table too, then we must have some
mechanism to save the integrity of data in child table.
28 | P a g e
Using Basic Structured Query Language
On Delete Cascade : This will remove the record from child table, if that value of
foriegn key is deleted from the main table.
On Delete Null : This will set all the values in that record of child table as NULL, for
which the value of foriegn key is deleted from the main table.
If we don't use any of the above, then we cannot delete data from the main table for
which data in child table exists. We will get an error if we try to do so.
CHECK Constraint
CHECK constraint is used to restrict the value of a column between a range. It performs check
on the values, before storing them into the database. Its like condition checking before saving
data into a column.
The above query will restrict the s_id value to be greater than zero.
29 | P a g e
Using Basic Structured Query Language
SQL Functions
SQL provides many built-in functions to perform operations on data. These functions are useful
while performing mathematical calculations, string concatenations, sub-strings etc. SQL
functions are divided into two catagories,
Aggregrate Functions
Scalar Functions
Aggregrate Functions
These functions return a single value after calculating from a group of values.Following are
some frequently used Aggregrate functions.
1) AVG()
Average returns average value after calculating from values in a numeric column.
30 | P a g e
Using Basic Structured Query Language
Consider following Emp table
avg(salary)
8200
2) COUNT()
Count returns the number of rows present in the table either based on some condition or without
condition.
31 | P a g e
Using Basic Structured Query Language
SELECT COUNT(name) from Emp where salary = 8000;
count(name)
2
Example of COUNT(distinct)
count(distinct salary)
4
3) MAX()
MAX function returns maximum value from selected column of the table.
Example of MAX()
32 | P a g e
Using Basic Structured Query Language
405 Tiger 35 8000
MAX(salary)
10000
4) MIN()
MIN function returns minimum value from a selected column of the table.
Example of MIN()
MIN(salary)
6000
33 | P a g e
Using Basic Structured Query Language
5) SUM()
Example of SUM()
SUM(salary)
41000
Scalar Functions
Scalar functions return a single value from an input value. Following are soe frequently used
Scalar Functions.
34 | P a g e
Using Basic Structured Query Language
Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. SQL Join is used for combining column from two or more tables by using values common
to both tables. Join Keyword is used in SQL queries for joining two or more tables. Minimum
required condition for joining table, is (n-1) where n, is number of tables. A table can also join to
itself known as, Self Join.
Types of Join
The following are the types of JOIN that we can use in SQL.
Inner
Outer
Left
Right
This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a
table which consists of records which combines each row from the first table with each row of
the second table.
35 | P a g e
Using Basic Structured Query Language
SELECT column-name-list
from table-name1
CROSS JOIN
table-name2;
ID NAME
1 abhi
2 adam
4 alex
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
SELECT *
from class,
cross JOIN class_info;
ID NAME ID Address
1 abhi 1 DELHI
2 adam 1 DELHI
4 alex 1 DELHI
1 abhi 2 MUMBAI
2 adam 2 MUMBAI
4 alex 2 MUMBAI
1 abhi 3 CHENNAI
2 adam 3 CHENNAI
4 alex 3 CHENNAI
36 | P a g e
Using Basic Structured Query Language
This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.
SELECT column-name-list
from table-name1
INNER JOIN
table-name2
WHERE table-name1.column-name = table-name2.column-name;
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
37 | P a g e
Using Basic Structured Query Language
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.
SELECT *
from table-name1
NATURAL JOIN
table-name2;
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME Address
1 abhi DELHI
2 adam MUMBAI
3 alex CHENNAI
38 | P a g e
Using Basic Structured Query Language
In the above example, both the tables being joined have ID column(same name and same
datatype), hence the records for which value of ID matches in both the tables will be the result of
Natural Join of these two tables.
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
The left outer join returns a result table with the matched data of two tables then remaining
rows of the left table and null for the right table's column.
SELECT column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
select column-name-list
from table-name1,
table-name2
on table-name1.column-name = table-name2.column-name(+);
ID NAME
1 abhi
2 adam
3 alex
4 anu
39 | P a g e
Using Basic Structured Query Language
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
4 anu null null
5 ashish null null
The right outer join returns a result table with the matched data of two tables then remaining
rows of the right table and null for the left table's columns.
select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
select column-name-list
40 | P a g e
Using Basic Structured Query Language
from table-name1,
table-name2
on table-name1.column-name(+) = table-name2.column-name;
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
null null 7 NOIDA
null null 8 PANIPAT
The full outer join returns a result table with the matched data of two table then remaining rows
of both left table and then the right table.
41 | P a g e
Using Basic Structured Query Language
Full Outer Join Syntax is,
select column-name-list
from table-name1
FULL OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
4 anu null null
5 ashish null null
null null 7 NOIDA
null null 8 PANIPAT
42 | P a g e
Using Basic Structured Query Language
SQL supports few Set operations to be performed on table data. These are used to get meaningful
results from data, under different special conditions.
Union
UNION is used to combine the results of two or more Select statements. However it will
eliminate duplicate rows from its result set. In case of union, number of columns and datatype
must be same in both the tables.
Example of UNION
43 | P a g e
Using Basic Structured Query Language
The First table,
ID Name
1 abhi
2 adam
ID Name
2 adam
3 Chester
ID NAME
1 abhi
2 adam
3 Chester
Union All
This operation is similar to Union. But it also shows the duplicate rows.
44 | P a g e
Using Basic Structured Query Language
Example of Union All
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
ID NAME
1 abhi
2 adam
2 adam
3 Chester
Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of columns
and datatype must be same. MySQL does not support INTERSECT operator.
45 | P a g e
Using Basic Structured Query Language
Example of Intersect
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
ID NAME
2 adam
Minus
Minus operation combines result of two Select statements and return only those result which
belongs to first set of result. MySQL does not support INTERSECT operator.
46 | P a g e
Using Basic Structured Query Language
Example of Minus
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
ID NAME
1 abhi
SQL View
A view in SQL is a logical subset of data from one or more tables. View is used to restrict data
access.
47 | P a g e
Using Basic Structured Query Language
12 ord2 1000 Adam
13 ord3 2000 Abhi
14 ord4 1000 Adam
15 ord5 2000 Alex
The data fetched from select statement will be stored in another object called sale_view. We can
use create seperately and replace too but using both together works better.
Syntax of displaying a view is similar to fetching data from table using Select statement.
force keyword is used while creating a view. This keyword force to create View even if the table
does not exist. After creating a force View if we create the base table and enter values in it, the
view will be automatically updated.
Update a View
UPDATE view-name
set value
WHERE condition;
48 | P a g e
Using Basic Structured Query Language
If we update a view it also updates base table data automatically.
Read-Only View
We can create a view with read-only option to restrict access to the view.
The above syntax will create view for read-only purpose, we cannot Update or Insert data into
read-only view. It will throw an error.
Types of View
Simple View
Complex View
49 | P a g e