SQL Command
SQL Command
SQL Command
Creating a Database
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 data types of various columns in the create command itself.
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
);
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:
student_id INT,
name VARCHAR(100),
age INT);
Here we have listed some of the most commonly used data types used for
columns in tables.
Data
Use
type
CHAR used for columns which will store char values(single character).
used for columns which will store text which is generally long in
length. For example, if you create a table for storing profile
TEXT
information of a social networking website, then for about
me section you can have a column of type TEXT.
Using ALTER command we can add a column to any existing table. Following is
the syntax,
column_name datatype);
example:
address VARCHAR(200)
);
Using ALTER command we can even add multiple new columns to any existing
table. Following is the syntax,
column_name1 datatype1,
column-name2 datatype2,
column-name3 datatype3);
father_name VARCHAR(60),
mother_name VARCHAR(60),
dob DATE);
ALTER Command: Add Column with default value
ALTER command can add a new column to an existing table with a default
value too. The default value is used when no value is inserted in the column.
Following is the syntax,
);
);
ALTER command can also be used to modify data type of any existing column.
Following is the syntax,
address varchar(300));
address TO location;
address);
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.
TRUNCATE TABLE student;
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.
RENAME query
RENAME command is used to set a new name for any existing 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.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
By default, a column can hold NULL values. If you do not want a column to
have a NULL value, use the NOT NULL constraint.
One important point to note about this constraint is that it cannot be defined
at table level.
Example using NOT NULL constraint:
name varchar(60),
age int
);
The above query will declare that the s_id field of Student table will not take
NULL value.
If you wish to alter the table after it has been created, then we can use the
ALTER command for it:
ALTER TABLE Student
UNIQUE Constraint
It ensures that a column will only have unique values. A UNIQUE constraint
field cannot have any duplicate data.
Here we have a simple CREATE query to create a table, which will have a
column s_id with unique values.
name varchar(60),
The above query will declare that the s_id field of Student table will only have
unique values and wont take NULL value.
If you wish to alter the table after it has been created, then we can use the
ALTER command for it:
Age int);
Foreign Key is used to relate two tables. The relationship between the two
tables matches the Primary Key in one of the tables with a Foreign Key in the
second table.
To understand FOREIGN KEY, let's see its use, with help of the below tables:
Customer_Detail Table
Order_Detail Table
10 Order1 101
11 Order2 103
12 Order3 102
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.
);
There are two ways to maintin the integrity of data in Child table, when a
particular record is deleted in the main table. When two tables are connected
with Foriegn key, and certain data in the main table is deleted, for which a
record exits in the child table, then we must have some mechanism to save the
integrity of data in the child table.
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
Age int
);
DML Commands
Using INSERT SQL 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.
Both the statements below will insert NULL value into age column of
the student table.
OR
101 Adam 15
Alex
102
Also, if you run the below query, it will insert default value into the age
column, whatever the default value may be.
Example:
101 Adam 15
102 Alex 18
103 chris 14
In the above statement, if we do not use the WHERE clause, then our update
query will update age for all the columns of the table to 18.
101 Adam 15
102 Alex 18
103 Abhi 17
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.
101 Adam 15
102 Alex 18
For eg: If you have a table with 10 rows and an auto_increment primary key,
and if you use DELETE command to delete all the rows, it will delete all the
rows, but will not re-initialize the primary key, hence if you will insert any row
after using the DELETE command, the auto_increment primary key will start
from 11. But in case of TRUNCATE command, primary key is re-initialized, and it
will again start from 1.
TCL Commands
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 command
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.
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.
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.
id name
1 Abhi
2 Adam
4 Alex
COMMIT;
SAVEPOINT B;
SAVEPOINT C;
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
ROLLBACK TO B;
id name
1 Abhi
2 Adam
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;
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
System: This includes permissions for creating session, table, etc and all
types of other system privileges.
GRANT: Used to provide any user access privileges or other priviliges for
the database.
When we create a user in SQL, it is not even allowed to login and create a
session until and unless proper permissions/priviliges are granted to the 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.
Sometimes user is restricted from creating come tables with names which are
reserved for system tables. But we can grant privileges to a user to create any
table using the below command,
As the title suggests, if you want to allow user to drop any table from the
database, then grant this privilege to the user,
And, if you want to take back the privileges from any user, use
the REVOKE command.
SELECT query is used to retieve records from a table. We can specify the
names of the columns which we want in the resultset.
The above query will fetch information of s_id, name and age columns of
the student table and display them,
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.
So you can also perform simple mathematical operations on the data too
using the SELECT query to fetch data from table.
When we specify a condition using the WHERE clause then the query executes
only for those records for which the condition specified by the WHERE clause is
true.
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
SELECT s_id,
name,
age,
address
Operator Description
= Equal to
!= Not Equal to
There are two wildcard operators that are used in LIKE clause.
101 Adam 15
102 Alex 18
103 Abhi 17
The above query will return all records where s_name starts with character 'A'.
102 Alex 18
103 Abhi 17
Using _ and %
The above query will return all records from Student table
where s_name contain 'd' as second character.
101 Adam 15
Using % only
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
Syntax of Order By
The above query will return the resultant data in ascending order of the salary.
The above query will return the resultant data in descending order of
the salary.
Consider the following Emp table. As you can see in the table below, there is
employee name, along with employee salary and age.
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.
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.
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
The above query will return records where either salary is greater than
10000 or age is greater than 25.
1. Aggregate Functions
2. Scalar Functions
Aggregate Functions
AVG() Function
avg(salary)
8200
COUNT() Function
Count returns the number of rows present in the table either based on some
condition or without condition.
Using COUNT() function
Consider the following Emp table
count(name)
Example of COUNT(distinct)
Consider the following Emp table
count(distinct salary)
MAX() Function
MAX function returns maximum value from selected column of the table.
Using MAX() function
Consider the following Emp table
MAX(salary)
10000
MIN() Function
MIN function returns minimum value from a selected column of the table.
Using MIN() function
Consider the following Emp table,
MIN(salary)
6000
SUM() Function
result:
SUM(salary)
41000
Scalar Functions
Scalar functions return a single value from an input value. Following are some
frequently used Scalar Functions in SQL.
UCASE() Function
Result is,
UCASE(name)
ANU
SHANE
ROHAN
SCOTT
TIGER
LCASE() Function
LCASE(name)
anu
shane
rohan
scott
tiger
MID() Function
MID(name,2,2)
nu
ha
oh
co
ig
ROUND() Function
ROUND(salary)
9001
8001
6000
10000
8000
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
Inner
Outer
Left
Right
ID NAME
1 abhi
2 adam
4 alex
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
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.
This is a simple JOIN in which the result is based on matched data as per the
equality condition specified in the SQL query.
Example of INNER JOIN
Consider a class table,
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
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.
Example of Natural JOIN
Here is the class table,
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
1 abhi DELHI
2 adam MUMBAI
3 alex CHENNAI
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 resultset table with the matched data from the
two tables and then the remaining rows of the left table and null from
the right table's columns.
Example of Left Outer Join
Here is the class table,
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
The right outer join returns a resultset table with the matched data from the
two tables being joined, then the remaining rows of the right table and null
for the remaining left table's columns.
Example of Right Outer Join
Once again the class table,
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
The full outer join returns a resultset table with the matched data of two table
then remaining rows of both left table and then the right table.
Example of Full outer join is,
The class table,
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
and the class_info table,
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
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
Example of UNION
The First table,
ID Name
1 abhi
2 adam
ID Name
2 adam
3 Chester
UNION
ID NAME
1 abhi
2 adam
3 Chester
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
Example of Union All
The First table,
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
ID NAME
1 abhi
2 adam
2 adam
3 Chester
INTERSECT
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
ID NAME
2 adam
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
ID NAME
2 adam
3 Chester
MINUS
ID NAME
1 abhi
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.
Creating a Sequence
syntax:
INCREMENT BY increment-value
MAXVALUE maximum-value
CYCLE | NOCYCLE;
The keyword CYCLE specifies that if the maximum value exceeds the set
limit, sequence will restart its cycle from the begining.
And, NO CYCLE specifies that if sequence exceeds MAXVALUE value, an
error will be thrown.
Let's start by creating a sequence, which will start from 1, increment by 1 with a
maximum value of 999.
START WITH 1
INCREMENT BY 1
MAXVALUE 999
CYCLE;
ID NAME
1 abhi
2 adam
4 alex
ID NAME
1 abhi
2 adam
4 alex
1 anu
Once you use nextval the sequence will increment even if you don't Insert any
record into the table.
SQL VIEW
A VIEW in SQL is a logical subset of data from one or more tables. View is used
to restrict data access.
Creating a VIEW
SQL Query to Create a View from the above table will be,
AS
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.
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.
SELECT column_name(s)
FROM table_name
WHERE condition;
Update a VIEW
WHERE condition;
Copy
NOTE: 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.
SELECT column_name(s)
FROM table_name
Copy
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
BETWEEN operator
The SQL BETWEEN condition allows you to easily test if an expression is within a range of
values (inclusive). The values can be text, date, or numbers. It can be used in a SELECT,
INSERT, UPDATE, or DELETE statement. The SQL BETWEEN Condition will return the
records where expression is within the range of value1 and value2.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Examples:
Consider the following Employee Table,
Queries
IN
IN operator allows you to easily test if the expression matches any value in the list of values.
It is used to remove the need of multiple OR condition in SELECT, INSERT, UPDATE or
DELETE. You can also use NOT IN to exclude the rows in your list. We should note that any
kind of duplicate entry will be retained.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (list_of_values);
Queries
Find the Fname, Lname of the Employees who have Salary equal to 30000, 40000 or
25000.