Professional Documents
Culture Documents
1
Grant permission to create any table ................................................................................................ 38
Grant permission to drop any table .................................................................................................. 38
To take back Permissions ................................................................................................................... 38
1. SELECT SQL Query ............................................................................................................................... 38
Syntax of SELECT query ............................................................................................................................... 38
Time for an Example .................................................................................................................................. 39
Select all records from a table ................................................................................................................... 39
Select a particular record based on a condition........................................................................................ 39
Performing Simple Calculations using SELECT Query................................................................................ 40
2. Using the WHERE SQL clause .............................................................................................................. 40
Syntax for WHERE clause ................................................................................................................... 40
Time for an Example........................................................................................................................... 40
Operators for WHERE clause condition .................................................................................................. 41
3. SQL LIKE clause ................................................................................................................................... 42
Wildcard operators ............................................................................................................................ 42
Example of LIKE clause ....................................................................................................................... 42
Using _ and % ..................................................................................................................................... 42
Using % only ....................................................................................................................................... 43
4. ORDER BY Clause ................................................................................................................................ 43
Syntax of Order By .................................................................................................................................. 43
Using default Order by ............................................................................................................................ 43
Using Order by DESC ............................................................................................................................... 44
5. Group By Clause.................................................................................................................................. 44
Example of Group by in a Statement ................................................................................................. 44
Example of Group by in a Statement with WHERE clause ................................................................ 45
6. HAVING Clause ................................................................................................................................... 45
Example of SQL Statement using HAVING......................................................................................... 46
7. DISTINCT keyword .............................................................................................................................. 46
Syntax for DISTINCT Keyword ............................................................................................................ 46
Example using DISTINCT Keyword ..................................................................................................... 46
8. AND & OR operator ............................................................................................................................ 47
AND operator .......................................................................................................................................... 47
Example of AND operator .................................................................................................................. 47
2
OR operator ............................................................................................................................................ 48
SQL Constraints .......................................................................................................................................... 49
NOT NULL Constraint .............................................................................................................................. 49
Example using NOT NULL constraint ................................................................................................. 49
UNIQUE Constraint ................................................................................................................................. 49
Using UNIQUE constraint when creating a Table (Table Level) ........................................................ 49
Using UNIQUE constraint after Table is created (Column Level)...................................................... 50
Primary Key Constraint ........................................................................................................................... 50
Using PRIMARY KEY constraint at Table Level .................................................................................. 50
Using PRIMARY KEY constraint at Column Level............................................................................... 50
Foreign Key Constraint ............................................................................................................................ 50
Using FOREIGN KEY constraint at Table Level ................................................................................... 51
Using FOREIGN KEY constraint at Column Level ............................................................................... 51
Behaviour of Foriegn Key Column on Delete .................................................................................... 51
CHECK Constraint .................................................................................................................................... 52
Using CHECK constraint at Table Level .............................................................................................. 52
Using CHECK constraint at Column Level........................................................................................... 52
What are SQL Functions? ........................................................................................................................... 53
AVG() Function ................................................................................................................................... 53
COUNT() Function............................................................................................................................... 53
FIRST() Function.................................................................................................................................. 54
LAST() Function ................................................................................................................................... 55
MAX() Function................................................................................................................................... 56
MIN() Function.................................................................................................................................... 56
SUM() Function ................................................................................................................................... 57
Scalar Functions ...................................................................................................................................... 57
UCASE() Function ................................................................................................................................ 57
LCASE() Function................................................................................................................................. 58
MID() Function.................................................................................................................................... 59
ROUND() Function .............................................................................................................................. 59
SQL JOIN...................................................................................................................................................... 61
Types of JOIN .......................................................................................................................................... 61
Cross JOIN or Cartesian Product ............................................................................................................. 61
3
INNER Join or EQUI Join .......................................................................................................................... 62
Natural JOIN ....................................................................................................................................... 63
OUTER JOIN ............................................................................................................................................. 64
LEFT Outer Join ................................................................................................................................... 64
RIGHT Outer Join ................................................................................................................................ 65
Full Outer Join..................................................................................................................................... 66
SET Operations in SQL ................................................................................................................................ 68
UNION Operation .................................................................................................................................... 68
UNION ALL............................................................................................................................................... 69
INTERSECT ............................................................................................................................................... 69
MINUS ..................................................................................................................................................... 70
What is an SQL Sequence? ......................................................................................................................... 72
Creating a Sequence ............................................................................................................................... 72
Using Sequence in SQL Query ................................................................................................................. 72
SQL VIEW .................................................................................................................................................... 74
Creating a VIEW ...................................................................................................................................... 74
Displaying a VIEW ................................................................................................................................... 74
Force VIEW Creation ............................................................................................................................... 75
Update a VIEW ........................................................................................................................................ 75
Read-Only VIEW ...................................................................................................................................... 75
Types of View .......................................................................................................................................... 75
4
Here is the complete sequence for sql server :
1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH CUBE or WITH ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10. ORDER BY
11. TOP
Types of Keys
1. Super Key
2. Minimal Super Key
3. Candidate Key
4. Primary Key
5. Unique Key
6. Alternate Key
7. Composite Key
8. Foreign Key
9. Natural Key
10. Surrogate Key
5
Now we take two tables for better understanding of the key. First table is “Branch Info” and
second table is “Student_Information”.
1. Candidate Key
A Candidate key is an attribute or set of attributes that uniquely identifies a record. Among the
set of candidate, one candidate key is chosen as Primary Key. So a table can have multiple
candidate key but each table can have maximum one primary key.
Example:
1. Branch_Id
2. Branch_Name
3. Branch_Code
1. Student_Id
2. College_Id
3. Rtu_Roll_No
6
2. Primary Key
A Primary key uniquely identifies each record in a table and must never be the same for the 2
records. Primary key is a set of one or more fields (columns) of a table that uniquely identify a
record in database table. A table can have only one primary key and one candidate key can
select as a primary key. The primary key should be chosen such that its attributes are never or
rarely changed, for example, we can’t select Student_Id field as a primary key because in some
case Student_Id of student may be changed.
Example:
1. Branch_Id
1. College_Id
3. Alternate Key:
Alternate keys are candidate keys that are not selected as primary key. Alternate key can also
work as a primary key. Alternate key is also called “Secondary Key”.
Example:
1. Branch_Name
2. Branch_Code
1. Student_Id
2. Rtu_Roll_No
4. Unique Key:
A unique key is a set of one or more attribute that can be used to uniquely identify the records
in table. Unique key is similar to primary key but unique key field can contain a “Null” value but
primary key doesn’t allow “Null” value. Other difference is that primary key field contain a
clustered index and unique field contain a non-clustered index.
7
Example:
1. Branch_Name
1. Rtu_Roll_No
5. Composite Key:
Composite key is a combination of more than one attributes that can be used to uniquely
identity each record. It is also known as “Compound” key. A composite key may be a candidate
or primary key.
Example:
1. { Branch_Name, Branch_Code}
2. { Student_Id, Student_Name }
6. Super Key
Super key is a set of one or more than one keys that can be used to uniquely identify the record
in table. A Super key for an entity is a set of one or more attributes whose combined value
uniquely identifies the entity in the entity set. A super key is a combine form of Primary Key,
Alternate key and Unique key and Primary Key, Unique Key and Alternate Key are subset of
super key. A Super Key is simply a non-minimal Candidate Key, that is to say one with additional
columns not strictly required to ensure uniqueness of the row. A super key can have a single
column.
Example:
1. Branch_Id
2. Branch_Name
3. Branch_Code
8
4. { Branch_Id, Branch_Code }
5. { Branch_Name , Branch_Code }
1. Student_Id
2. College_Id
3. Rtu_Roll_No
4. { Student_Id, Student_Name}
5. { College_Id, Branch_Id }
6. { Rtu_Roll_No, Session }
A minimal super key is a minimum set of columns that can be used to uniquely identify a row. In
other words, the minimum number of columns that can be combined to give a unique value for
every row in the table.
Example:
1. Branch_Id
2. Branch_Name
3. Branch_Code
1. Student_Id
2. College_Id
3. Rtu_Roll_No
8. Natural Keys:
A natural key is a key composed of columns that actually have a logical relationship to other
columns within a table. For example, if we use Student_Id, Student_Name and Father_Name
columns to form a key then it would be “Natural Key” because there is definitely a relationship
between these columns and other columns that exist in table. Natural keys are often called
“Business Key ” or “Domain Key”.
9. Surrogate Key:
Surrogate key is an artificial key that is used to uniquely identify the record in table. For
example, in SQL Server or Sybase database system contain an artificial key that is known as
9
“Identity”. Surrogate keys are just simple sequential number. Surrogate keys are only used to
act as a primary key.
Example:
Foreign key is used to generate the relationship between the tables. Foreign Key is a field in
database table that is Primary key in another table. A foreign key can accept null and duplicate
value.
Example:
10
SQL - Sub Queries
A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are
in the main query for the subquery to compare its selected columns.
An ORDER BY command cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP BY command can be used to perform the same function as
the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY,
CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Consider the following employees and departments tables from the sample database:
11
Suppose you have to find all employees who locate in the location with the id 1700. You might
come up with the following solution.
SELECT *
FROM
departments
WHERE
location_id = 1700;
Second, find all employees that belong to the location 1700 by using the department id list of
the previous query:
SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (1 , 3, 8, 10, 11)
ORDER BY first_name , last_name;
12
This solution has two problems. To start with, you have looked at the departments table to
check which department belongs to the location 1700. However, the original question was not
referring to any specific departments; it referred to the location 1700.
Because of the small data volume, you can get a list of department easily. However, in the real
system with high volume data, it might be problematic.
Another problem was that you have to revise the queries whenever you want to find
employees who locate in a different location.
A much better solution to this problem is to use a subquery. By definition, a subquery is a query
nested inside another query such as SELECT, INSERT, UPDATE, or DELETE statement. In this
tutorial, we are focusing on the subquery used with the SELECT statement.
In this example, you can rewrite combine the two queries above as follows:
SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (SELECT
department_id
FROM
departments
WHERE
location_id = 1700)
ORDER BY first_name , last_name;
The query placed within the parentheses is called a subquery. It is also known as an inner query
or inner select. The query that contains the subquery is called an outer query or an outer select.
To execute the query, first, the database system has to execute the subquery and substitute the
subquery between the parentheses with its result – a number of department id located at the
location 1700 – and then executes the outer query.
13
Normalization
Normalization is a database design technique which organizes tables in a manner that reduces
redundancy and dependency of data.
It divides larger tables to smaller tables and links them using relationships.
Assume a video library maintains a database of movies rented out. Without any normalization,
all information is stored in one table as shown below.
Table 1
1NF Example
14
Before we proceed let's understand a few things --
What is a KEY?
A KEY is a value used to identify a record in a table uniquely. A KEY could be a single column or
combination of multiple columns
Note: Columns in a table that are NOT used to identify a record uniquely are called non-key
columns.
A composite key is a primary key composed of multiple columns used to identify a record
uniquely
In our database, we have two people with the same name Robert Phil, but they live in different
places.
Hence, we require both Full Name and Address to identify a record uniquely. That is
a composite key.
15
Let's move into second normal form 2NF
Rule 1- Be in 1NF
Rule 2- Single Column Primary Key
It is clear that we can't move forward to make our simple database in 2 nd Normalization form
unless we partition the table above.
Table 1
Table 2
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id
Foreign Key references the primary key of another Table! It helps connect your Tables
A foreign key can have a different name from its primary key
It ensures rows in one table have corresponding rows in another
Unlike the Primary key, they do not have to be unique. Most often they aren't
Foreign keys can be null even though primary keys can not
16
Why do you need a foreign key?
You will only be able to insert values into your foreign key that exist in the unique key in the
parent table. This helps in referential integrity.
The above problem can be overcome by declaring membership id from Table2 as foreign key
of membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in the
parent table, an error will be shown!
17
What are transitive functional dependencies?
A transitive functional dependency is when changing a non-key column, might cause any of the
other non-key columns to change
Consider the table 1. Changing the non-key column Full Name may change Salutation.
Rule 1- Be in 2NF
Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
TABLE 1
Table 2
Table 3
18
We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF
In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in
Table 3
Now our little example is at a level that cannot further be decomposed to attain higher forms of
normalization. In fact, it is already in higher normalization forms. Separate efforts for moving into
next levels of normalizing data are normally needed in complex databases. However, we will be
discussing next levels of normalizations in brief in the following.
Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has
more than one Candidate Key.
If no database table instance contains two or more, independent and multivalued data
describing the relevant entity, then it is in 4th Normal Form.
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed into any number
of smaller tables without loss of data.
6th Normal Form is not standardized, yet however, it is being discussed by database experts for
some time. Hopefully, we would have a clear & standardized definition for 6 th Normal Form in
the near future...
19
Aggregation
Aggregation is a process in which a single entity alone is not able to make sense in a
relationship so the relationship of two entities acts as one entity.
In real world, we know that a manager not only manages the employee working under
them but he has to manage the project as well. In such scenario if entity “Manager” makes
a “manages” relationship with either “Employee” or “Project” entity alone then it will not
make any sense because he has to manage both. In these cases the relationship of two
entities acts as one entity. In our example, the relationship “Works-On” between
“Employee” & “Project” acts as one entity that has a relationship “Manages” with the
entity “Manager”.
20
Relationships
There are 3 types of relationships in relational database design. They are:
One-to-One
Many-to-Many
These are explained below.
One-to-One
A row in table A can have only one matching row in table B, and vice versa.
21
Example of one-to-many relationship.
One-to-Many relationships can also be viewed as Many-to-One relationships, depending
on which way you look at it.
In the above example, the Customer table is the “many” and the City table is the “one”.
Each customer can only be assigned one city, One city can be assigned to many customers.
Many-to-Many
In a many-to-many relationship, a row in table A can have many matching rows in table
B, and vice versa.
22
displayed
This is the Relationships tab that is when you create a relationship Microsoft Access. In
this case, a many-to-many relationship has just been created. The Orders table is a
junction table that cross-references the Customers table with the Products table.
So in order to create a many-to-many relationship between the Customers table and the
Products table, we created a new table called Orders.
Again, the relationship between the Customers and Orders table is one-to-many, but
consider the relationship between the Orders and Products table. An order can contain
multiple products, and a product could be linked to multiple orders: several customers
might submit an order that contains some of the same products. This kind of relationship
requires at minimum three tables.
23
DDL Commands
Create query
Alter query
Truncate, Drop and Rename query
Creating a Database
To create a database in RDBMS, create command is used. Following is the syntax,
CREATE DATABASE <DB_NAME>;
The above command will create a database named Test, which will be an empty schema
without any table.
To create tables in this newly created database, we can again use the create command.
Creating a Table
create command can also be used to create tables. Now when we create a table, we have to
specify the details of the columns of the tables too. We can specify the names and datatypes of
various columns in the create command itself.
Following is the syntax,
CREATE TABLE <TABLE_NAME>
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4 );
24
create table command will tell the database system to create a new table with the given table
name and column information.
student_id INT,
name VARCHAR(100),
age INT);
The above command will create a new table with name Student in the current database with 3
columns, namely student_id, name and age. Where the column student_id will only store
integer, name will hold upto 100 characters and age will again store only integer value.
If you are currently not logged into your database in which you want to create the table then
you can also add the database name along with table name, using a dot operator .
For example, if we have a database with name Test and we want to create a table Student in it,
then we can do so using the following query:
CREATE TABLE Test.Student(
student_id INT,
name VARCHAR(100),
age INT);
25
2. SQL: ALTER command
alter command is used for altering the table structure, such as,
column_name datatype);
address VARCHAR(200)
);
The above command will add a new column address to the table student, which will hold data
of type varchar which is nothing but string, of length 200.
column_name1 datatype1,
column-name2 datatype2,
column-name3 datatype3);
father_name VARCHAR(60),
mother_name VARCHAR(60),
dob DATE);
26
The above command will add three new columns to the student table
);
);
The above command will add a new column with a preset default value to the table student.
column_name datatype
);
address varchar(300));
Remember we added a new column address in the beginning? The above command will modify
the address column of the student table, to now hold upto 300 characters.
old_column_name TO new_column_name;
27
address TO location;
column_name);
address);
The above command will drop the address column from the table student
TRUNCATE command
TRUNCATE command removes all the records from a table. But this command will not destroy
the table's structure. When we use TRUNCATE command on a table its (auto-increment) primary
key is also initialized. Following is its syntax,
TRUNCATE TABLE table_name
The above query will delete all the records from the table student.
In DML commands, we will study about the DELETE command which is also more or less same as
the TRUNCATE command. We will also learn about the difference between the two in that
tutorial.
DROP command
DROP command completely removes a table from the database. This command will also destroy
the table structure and the data stored in it. Following is its syntax,
DROP TABLE table_name
28
The above query will delete the Student table completely. It can also be used on Databases, to
delete the complete database. For example, to drop a database,
DROP DATABASE Test;
The above query will drop the database with name Test from the system.
RENAME query
RENAME command is used to set a new name for any existing table. Following is the syntax,
RENAME TABLE old_table_name to new_table_name
29
DML Commands
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.
Talking about the Insert command, whenever we post a Tweet on Twitter, the text is stored in
some table, and as we post a new tweet, a new record gets inserted in that table.
INSERT command
UPDATE command
DELETE command
1. INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
INSERT INTO table_name VALUES(data1, data2, ...)
The above command will insert a new record into student table.
s_id name age
101 Adam 15
The above SQL query will only insert id and name values in the newly inserted record.
Or,
INSERT INTO Student VALUES(102,'Alex', null);
30
The above command will insert only two column values and the other column is set to null.
S_id S_Name age
101 Adam 15
102 Alex
2. UPDATE command
UPDATE command is used to update any record of data in a table. Following is its general
syntax,
UPDATE table_name SET column_name = new_value WHERE some_condition;
WHERE is used to add a condition to any SQL query, we will soon study about it in detail.
Lets take a sample table student,
student_id name age
101 Adam 15
102 Alex
103 chris 14
UPDATE student SET age=18 WHERE student_id=102;
31
UPDATE student SET name='Abhi', age=17 where s_id=103;
The above command will update two columns of the record which has s_id 103.
s_id name age
101 Adam 15
102 Alex 18
103 Abhi 17
UPDATE Command: Incrementing Integer Value
When we have to update any integer value in a table, then we can fetch and update the value
in the table in a single statement.
For example, if we have to update the age column of student table every year for every
student, then we can simply run the following UPDATE statement to perform the following
operation:
UPDATE student SET age = age+1;
As you can see, we have used age = age + 1 to increment the value of age by 1.
NOTE: This style only works for integer values.
3. DELETE command
DELETE command is used to delete data from a table.
Following is its general syntax,
DELETE FROM table_name;
Let's take a sample table student:
s_id name age
101 Adam 15
102 Alex 18
103 Abhi 17
32
The above command will delete the record where s_id is 103 from the table student.
S_id S_Name age
101 Adam 15
102 Alex 18
33
TCL COMMAND
Transaction Control Language(TCL) commands are used to manage transactions in the database.
These are used to manage the changes made to the data in a table by DML statements. It also
allows statements to be grouped together into logical transactions.
Commit
Rollback
SavePoint
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these
commands are not permanent, until the current session is closed, the changes made by these
commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and realise that
those changes were not required, then we can use the ROLLBACK command to rollback those
changes, if they were not commited using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
In short, using this command we can name the different states of our data in any table and then
rollback to that state using the ROLLBACK command whenever required.
34
Using Savepoint and Rollback
Following is the table class,
id name
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.
INSERT INTO class VALUES(5, 'Rahul');
COMMIT;
UPDATE class SET name = 'Abhijit' WHERE id = '5';
SAVEPOINT A;
INSERT INTO class VALUES(6, 'Chris');
SAVEPOINT B;
INSERT INTO class VALUES(7, 'Bravo');
SAVEPOINT C;
SELECT * FROM class;
NOTE: SELECT statement is used to show the data stored in the table.
The resultant table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Now let's use the ROLLBACK command to roll back the state of data to the savepoint B.
ROLLBACK TO B;
35
4 Alex
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of data to the savepoint A
ROLLBACK TO A;
36
DCL COMMAND
Data Control Language(DCL) is used to control privileges in Database. To perform any operation
in the database, such as for creating tables, sequences or views, a user needs privileges.
Privileges are of two types,
System: This includes permissions for creating session, table, etc and all types of other
system privileges.
Object: This includes permissions for any command or query to perform any operation
on the database tables.
GRANT: Used to provide any user access privileges or other priviliges for the database.
The above command will alter the user details and will provide it access to unlimited tablespace
on system.
NOTE: Generally unlimited quota is provided to Admin users.
37
Grant all privilege to a User
sysdba is a set of priviliges which has all the permissions in it. So if we want to provide all the
privileges to any user, we can simply grant them the sysdba permission.
GRANT sysdba TO username
column_name1,
column_name2,
column_name3,
column_nameN
FROM table_name;
38
Time for an Example
Consider the following student table,
s_id name age address
101 Adam 15 Chennai
102 Alex 18 Delhi
103 Abhi 17 Banglore
104 Ankit 22 Mumbai
SELECT s_id, name, age FROM student;
The above query will fetch information of s_id, name and age columns of the student table and
display them,
s_id name age
101 Adam 15
102 Alex 18
103 Abhi 17
104 Ankit 22
As you can see the data from address column is absent, because we did not specif it in
our SELECT query.
The above query will show all the records of student table, that means it will show complete
dataset of the table.
s_id name age address
101 Adam 15 Chennai
102 Alex 18 Delhi
103 Abhi 17 Banglore
104 Ankit 22 Mumbai
39
Performing Simple Calculations using SELECT Query
Consider the following employee table.
eid name age salary
101 Adam 26 5000
102 Ricky 42 8000
103 Abhi 25 10000
104 Rohan 22 5000
Here is our SELECT query,
SELECT eid, name, salary+3000 FROM employee;
The above command will display a new column in the result, with 3000 added into existing
salaries of the employees.
eid name salary+3000
101 Adam 8000
102 Ricky 11000
103 Abhi 13000
104 Rohan 8000
So you can also perform simple mathematical operations on the data too using
the SELECT query to fetch data from table.
The WHERE clause is used at the end of any SQL query, to specify a condition for execution.
40
s_id name age address
101 Adam 15 Chennai
102 Alex 18 Delhi
103 Abhi 17 Banglore
104 Ankit 22 Mumbai
Now we will use the SELECT statement to display data of the table, based on a condition, which
we will add to our SELECT query using WHERE clause.
Let's write a simple SQL query to display the record for student with s_id as 101.
SELECT s_id,
name,
age,
address
name,
age,
address
41
Operator Description
= Equal to
!= Not Equal to
< Less than
> Greater than
<= Less than or Equal to
>= Greate than or Equal to
BETWEEN Between a specified range of values
LIKE This is used to search for a pattern in value.
IN In a given set of values
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'.
s_id s_Name age
101 Adam 15
102 Alex 18
103 Abhi 17
Using _ and %
SELECT * FROM Student WHERE s_name LIKE '_d%';
42
The above query will return all records from Student table where s_name contain 'd' as second
character.
s_id s_Name age
101 Adam 15
Using % only
SELECT * FROM Student WHERE s_name LIKE '%x';
The above query will return all records from Student table where s_name contain 'x' as last
character.
s_id s_Name age
102 Alex 18
4. ORDER BY Clause
Order by clause is used with SELECT statement for arranging retrieved data in sorted order.
The Order by clause by default sorts the retrieved data in ascending order. To sort the data in
descending order DESC keyword is used with Order by clause.
Syntax of Order By
SELECT column-list|* FROM table-name ORDER BY ASC | DESC
The above query will return the resultant data in ascending order of the salary.
eid name age salary
403 Rohan 34 6000
402 Shane 29 8000
405 Tiger 35 8000
401 Anu 22 9000
404 Scott 44 10000
43
Using Order by DESC
Consider the Emp table described above,
SELECT * FROM Emp ORDER BY salary DESC;
The above query will return the resultant data in descending order of the salary.
eid name age salary
404 Scott 44 10000
401 Anu 22 9000
405 Tiger 35 8000
402 Shane 29 8000
403 Rohan 34 6000
5. 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.
Syntax for using Group by in a statement.
SELECT column_name, function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
44
SELECT name, age
FROM Emp GROUP BY salary
Result will be,
name age
Rohan 34
Shane 29
Anu 22
FROM Emp
GROUP BY salary
name salary
Rohan 6000
Shane 8000
Scott 9000
You must remember that Group By clause will always come at the end of the SQL query, just like
the Order by clause.
6. 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 by based SQL queries, just like WHERE clause is used
with SELECT query.
Syntax for HAVING clause is,
SELECT column_name, function(column_name)
FROM table_name
45
WHERE column_name condition
GROUP BY column_name
7. 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 records from any table in the
database.
46
In the table below, multiple employees have the same salary, so we will be
using DISTINCT keyword to list down distinct salary amount, that is currently being paid to the
employees.
eid name age salary
401 Anu 22 5000
402 Shane 29 8000
403 Rohan 34 10000
404 Scott 44 10000
405 Tiger 35 8000
SELECT DISTINCT salary FROM Emp;
The above query will return only the unique salary from Emp table.
salary
5000
8000
10000
AND operator
AND operator is used to set multiple conditions with the WHERE clause,
alongside, SELECT, UPDATE or DELETE SQL queries.
The above query will return records where salary is less than 10000 and age greater than 25.
Hope you get the concept here. We have used the AND operator to specify two conditions
with WHERE clause.
47
eid name age salary
402 Shane 29 8000
405 Tiger 35 9000
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
specified conditions will be there in the result.
But in case of OR operator, atleast one condition from the conditions specified must be satisfied
by any record to be in the resultset.
Example of OR operator
Consider the following Emp table
eid name age salary
401 Anu 22 5000
402 Shane 29 8000
403 Rohan 34 12000
404 Scott 44 10000
405 Tiger 35 9000
SELECT * FROM Emp WHERE salary > 10000 OR age > 25
The above query will return records where either salary is greater than 10000 or age is greater
than 25.
402 Shane 29 8000
403 Rohan 34 12000
404 Scott 44 10000
405 Tiger 35 9000
48
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 can be divided into the following two types,
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.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
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. This constraint can be applied at column
level or table level.
49
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.
The above query specifies that s_id field of Student table will only have unique value.
50
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.
If you try to insert any incorrect data, DBMS will return error and will not allow you to insert the
data.
);
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference
of c_id column in Customer_Detail table.
51
1. On Delete Cascade : This will remove the record from child table, if that value of foriegn key is
deleted from the main table.
2. 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.
3. 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.
Age int
);
The above query will restrict the s_id value to be greater than zero.
52
What are 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 categories,
1. Aggregate Functions
2. Scalar Functions
Aggregate Functions
These functions return a single value after performing calculations on a group of values.
Following are some of the frequently used Aggregrate functions.
AVG() Function
Average returns average value after calculating it from values in a numeric column.
Its general syntax is,
SELECT AVG(column_name) FROM table_name
COUNT() Function
Count returns the number of rows present in the table either based on some condition or
without condition.
53
Its general syntax is,
SELECT COUNT(column_name) FROM table-name
FIRST() Function
First function returns first value of a selected column
Syntax for FIRST function is,
SELECT FIRST(column_name) FROM table-name;
54
Using FIRST() function
Consider the following Emp table
eid name age salary
401 Anu 22 9000
402 Shane 29 8000
403 Rohan 34 6000
404 Scott 44 10000
405 Tiger 35 8000
SQL query will be,
SELECT FIRST(salary) FROM Emp;
LAST() Function
LAST function returns the return last value of the selected column.
Syntax of LAST function is,
SELECT LAST(column_name) FROM table-name;
55
MAX() Function
MAX function returns maximum value from selected column of the table.
Syntax of MAX function is,
SELECT MAX(column_name) from table-name;
MIN() Function
MIN function returns minimum value from a selected column of the table.
Syntax for MIN function is,
SELECT MIN(column_name) from table-name;
56
SQL query to find minimum salary is,
SELECT MIN(salary) FROM emp;
SUM() Function
SUM function returns total sum of a selected columns numeric values.
Syntax for SUM is,
SELECT SUM(column_name) from table-name;
Scalar Functions
Scalar functions return a single value from an input value. Following are some frequently used
Scalar Functions in SQL.
UCASE() Function
UCASE function is used to convert value of string column to Uppercase characters.
Syntax of UCASE,
SELECT UCASE(column_name) from table-name;
57
Using UCASE() function
Consider the following Emp table
eid name age salary
401 anu 22 9000
402 shane 29 8000
403 rohan 34 6000
404 scott 44 10000
405 Tiger 35 8000
SQL query for using UCASE is,
SELECT UCASE(name) FROM emp;
Result is,
UCASE(name)
ANU
SHANE
ROHAN
SCOTT
TIGER
LCASE() Function
LCASE function is used to convert value of string columns to Lowecase characters.
Syntax for LCASE is,
SELECT LCASE(column_name) FROM table-name;
58
Result will be,
LCASE(name)
anu
shane
rohan
scott
tiger
MID() Function
MID function is used to extract substrings from column values of string type in a table.
Syntax for MID function is,
SELECT MID(column_name, start, length) from table-name;
ROUND() Function
ROUND function is used to round a numeric field to number of nearest integer. It is used on
Decimal point values.
Syntax of Round function is,
SELECT ROUND(column_name, decimals) from table-name;
59
Using ROUND() function
Consider the following Emp table
eid name age salary
401 anu 22 9000.67
402 shane 29 8000.98
403 rohan 34 6000.45
404 scott 44 10000
405 Tiger 35 8000.01
SQL query is,
SELECT ROUND(salary) from emp;
60
SQL JOIN
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. It 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,
which is known as, Self Join.
Types of JOIN
Following are the types of JOIN that we can use in SQL:
Inner
Outer
Left
Right
61
SELECT * FROM
class CROSS JOIN class_info;
The resultset table will look like,
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
As you can see, this join returns the cross product of all the records present in both the tables.
62
The resultset table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
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.
The syntax for Natural Join is,
SELECT * FROM
63
OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
64
The resultset table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
4 anu null null
5 ashish null null
ON table-name1.column-name = table-name2.column-name;
table-name1, table-name2
ON table-name1.column-name(+) = table-name2.column-name;
65
Right Outer Join query will be,
SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id = class_info.id);
66
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
67
SET Operations in SQL
SQL supports few Set operations which can be performed on the table data. These are used to
get meaningful results from data stored in the table, under different special conditions.
In this tutorial, we will cover 4 different types of SET operations, along with example:
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
UNION Operation
UNION is used to combine the results of two or more SELECT statements. However it will
eliminate duplicate rows from its resultset. In case of union, number of columns and datatype
must be same in both the tables, on which UNION operation is being applied.
Example of UNION
The First table,
ID Name
1 abhi
2 adam
The Second table,
ID Name
2 adam
3 Chester
Union SQL query will be,
SELECT * FROM First
UNION
SELECT * FROM Second;
68
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
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.
NOTE: MySQL does not support INTERSECT operator.
69
Example of Intersect
The First table,
ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
Intersect query will be,
SELECT * FROM First
INTERSECT
SELECT * FROM Second;
MINUS
The Minus operation combines results of two SELECT statements and return only those in the
final result, which belongs to the first set of the result.
Example of Minus
The First table,
ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
Minus query will be,
70
SELECT * FROM First
MINUS
SELECT * FROM Second;
71
What is an SQL Sequence?
Sequence is a feature supported by some database systems to produce unique values on
demand. Some DBMS like MySQL supports AUTO_INCREMENT in place of Sequence.
AUTO_INCREMENT is applied on columns, it automatically increments the column value
by 1 each time a new record is inserted into the table.
Sequence is also some what similar to AUTO_INCREMENT but it has some additional features
too.
Creating a Sequence
Syntax to create a sequence is,
CREATE SEQUENCE sequence-name
START WITH initial-value
INCREMENT BY increment-value
MAXVALUE maximum-value
CYCLE | NOCYCLE;
72
Now let's use the sequence that we just created above.
Below we have a class table,
ID NAME
1 abhi
2 adam
4 alex
The SQL query will be,
INSERT INTO class VALUE(seq_1.nextval, 'anu');
73
SQL VIEW
A VIEW in SQL is a logical subset of data from one or more tables. View is used to restrict data
access.
Syntax for creating a View,
CREATE or REPLACE VIEW view_name
AS
SELECT column_name(s)
FROM table_name
WHERE condition
As you may have understood by seeing the above SQL query, a view is created using data
fetched from some other table(s). It's more like a temporary table created with data.
Creating a VIEW
Consider following Sale table,
oid order_name previous_balance customer
11 ord1 2000 Alex
12 ord2 1000 Adam
13 ord3 2000 Abhi
14 ord4 1000 Adam
15 ord5 2000 Alex
SQL Query to Create a View from the above table will be,
CREATE or REPLACE VIEW sale_view
AS
SELECT * FROM Sale WHERE customer = 'Alex';
The data fetched from SELECT statement will be stored in another object called sale_view. We
can use CREATE and REPLACE seperately too, but using both together works better, as if any view
with the specified name exists, this query will replace it with fresh data.
Displaying a VIEW
The syntax for displaying the data in a view is similar to fetching data from a table using
a SELECT statement.
SELECT * FROM sale_view;
74
Force VIEW Creation
FORCE keyword is used while creating a view, forcefully. This keyword is used to create a 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.
Syntax for forced View is,
CREATE or REPLACE FORCE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;
Update a VIEW
UPDATE command for view is same as for tables.
Read-Only VIEW
We can create a view with read-only option to restrict access to the view.
Syntax to create a view with Read-Only Access
CREATE or REPLACE FORCE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition WITH read-only;
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
There are two types of view,
Simple View
Complex View
75
Simple View Complex View
Created from one table Created from one or more table
Does not contain functions Contain functions
Does not contain groups of data Contains groups of data
76