0% found this document useful (0 votes)
29 views

Basic SQL

SQL is a programming language used to store, manipulate, and retrieve data in relational database management systems (RDBMS). It defines several languages for different data operations - DDL for data definition, DML for data manipulation, DCL for data control, and DQL for data queries. Common SQL commands include CREATE to create tables, INSERT to insert data into tables, UPDATE to modify data in tables, DELETE to remove data from tables, and SELECT to retrieve data from tables. Transactions can be committed to permanently save changes to the database or rolled back to undo changes.

Uploaded by

an navi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Basic SQL

SQL is a programming language used to store, manipulate, and retrieve data in relational database management systems (RDBMS). It defines several languages for different data operations - DDL for data definition, DML for data manipulation, DCL for data control, and DQL for data queries. Common SQL commands include CREATE to create tables, INSERT to insert data into tables, UPDATE to modify data in tables, DELETE to remove data from tables, and SELECT to retrieve data from tables. Transactions can be committed to permanently save changes to the database or rolled back to undo changes.

Uploaded by

an navi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Introduction to SQL

Structure Query Language(SQL) is a programming language used for storing and managing data
in RDBMS. SQL was the first commercial language introduced for E.F Codd's Relational
model. Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) uses SQL as the
standard database language. SQL is used to perform all type of data operations in RDBMS.

SQL Command

SQL defines following data languages to manipulate data of RDBMS.

DDL : Data Definition Language

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

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

TCL : Transaction Control Language

Compiled By: Eng. Kibwika Nasurudin Bashir


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

DCL : Data Control Language

Data control language provides command to grant and take back authority.

Command Description
grant grant permission of right
revoke take back permission.

DQL : Data Query Language

Command Description
select retrieve records from one or more table

create command
create is a DDL command used to create a table or a database.

Creating a Database

To create a database in RDBMS, create command is uses. Following is the Syntax,

create database database-name;

Example for Creating Database

create database Test;

Compiled By: Eng. Kibwika Nasurudin Bashir


The above command will create a database named Test.

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 table-name


{
column-name1 datatype1,
column-name2 datatype2,
column-name3 datatype3,
column-name4 datatype4
};

create table command will tell the database system to create a new table with given table name
and column information.

Example for creating Table

create table Student(id int, name varchar, age int);

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,

 to add a column to existing table


 to rename any existing column
 to change datatype of any column or to modify its size.
 alter is also used to drop a column.

To Add Column to existing Table

Compiled By: Eng. Kibwika Nasurudin Bashir


Using alter command we can add a column to an existing table. Following is the Syntax,

alter table table-name add(column-name datatype);

Here is an Example for this,

alter table Student add(address char);

The above command will add a new column address to the Student table

To Add Multiple Column to existing Table

Using alter command we can even add multiple columns to an existing table. Following is the
Syntax,

alter table table-name add(column-name1 datatype1, column-name2 datatype2,


column-name3 datatype3);

Here is an Example for this,

alter table Student add(father-name varchar(60), mother-name varchar(60), dob


date);

The above command will add three new columns to the Student table

To Add column with Default Value

alter command can add a new column to an existing table with default values. Following is the
Syntax,

alter table table-name add(column-name1 datatype1 default data);

Here is an Example for this,

alter table Student add(dob date default '1-Jan-99');

The above command will add a new column with default value to the Student table

To Modify an existing Column

alter command is used to modify data type of an existing column . Following is the Syntax,

Compiled By: Eng. Kibwika Nasurudin Bashir


alter table table-name modify(column-name datatype);

Here is an Example for this,

alter table Student modify(address varchar(30));

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,

alter table table-name rename old-column-name to column-name;

Here is an Example for this,

alter table Student rename address to Location;

The above command will rename address column to Location.

To Drop a Column

alter command is also used to drop columns also. Following is the Syntax,

alter table table-name drop(column-name);

Here is an Example for this,

alter table Student drop(address);

The above command will drop address column from the Student table

SQL queries to Truncate, Drop or Rename a Table


truncate command

Compiled By: Eng. Kibwika Nasurudin Bashir


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,

truncate table table-name

Here is an Example explaining it.

truncate table Student;

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,

drop table table-name

Here is an Example explaining it.

drop table Student;

The above query will delete the Student table completely. It can also be used on Databases. For
Example, to drop a database,

drop database Test;

The above query will drop a database named Test from the system.

Compiled By: Eng. Kibwika Nasurudin Bashir


rename query

rename command is used to rename a table. Following is its Syntax,

rename table old-table-name to new-table-name

Here is an Example explaining it.

rename table Student to Student-record;

The above query will rename Student table to Student-record.

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,

INSERT into table-name values(data1,data2,..)

Lets see an example,

Consider a table Student with following fields.

S_id S_Name age


INSERT into Student values(101,'Adam',15);

The above command will insert a record into Student table.

S_id S_Name age


101 Adam 15

Example to Insert NULL value to a column

Compiled By: Eng. Kibwika Nasurudin Bashir


Both the statements below will insert NULL value into age column of the Student table.

INSERT into Student(id,name) values(102,'Alex');

Or,

INSERT into Student values(102,'Alex',null);

The above command will insert only two column value other column is set to null.

S_id S_Name age


101 Adam 15
102 Alex

Example to Insert Default value to a column

INSERT into Student values(103,'Chris',default)


S_id S_Name age
101 Adam 15
102 Alex
103 chris 14

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.

INSERT into Student values(103,'Chris')

2) UPDATE command

Update command is used to update a row of a table. Following is its general syntax,

UPDATE table-name set column-name = value where condition;

Lets see an example,

update Student set age=18 where s_id=102;


S_id S_Name age
101 Adam 15
102 Alex 18
103 chris 14

Compiled By: Eng. Kibwika Nasurudin Bashir


Example to Update multiple columns

UPDATE Student set s_name='Abhi',age=17 where s_id=103;

The above command will update two columns of a record.

S_id S_Name age


101 Adam 15
102 Alex 18
103 Abhi 17

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,

DELETE from table-name;

Example to Delete all Records from a Table

DELETE from Student;


The above command will delete all the records from Student table.

Example to Delete a particular Record from a Table

Consider the following Student table

S_id S_Name age


101 Adam 15
102 Alex 18
103 Abhi 17
DELETE from Student where s_id=103;

The above command will delete the record where s_id is 103 from Student table.

S_id S_Name age


101 Adam 15
102 Alex 18

Compiled By: Eng. Kibwika Nasurudin Bashir


TCL command

Transaction Control Language(TCL) commands are used to manage transactions in


database.These are used to manage the changes made by DML statements. It also allows
statements to be grouped together into logical transactions.

Commit command

Commit command is used to permanently save any transaaction into database.


Following is Commit command's syntax,
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.

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 necessary.

Following is savepoint command's syntax,

savepoint savepoint-name;

Example of Savepoint and Rollback

Following is the class table,

ID NAME
1 abhi
2 adam
4 alex

Compiled By: Eng. Kibwika Nasurudin Bashir


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;

The resultant table will look like,

ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris
7 bravo

Now rollback to savepoint B

rollback to B;
SELECT * from class;

The resultant table will look like

ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris

Now rollback to savepoint A

rollback to A;
SELECT * from class;

The result table will look like

ID NAME

Compiled By: Eng. Kibwika Nasurudin Bashir


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.

DCL defines two commands,

 Grant : Gives user access privileges to database.


 Revoke : Take back permissions from user.

To Allow a User to create Session

grant create session to username;

To Allow a User to create Table

grant create table to username;

To provide User with some Space on Tablespace to store Table

alter user username quota unlimited on system;

To Grant all privilege to a User

Compiled By: Eng. Kibwika Nasurudin Bashir


grant sysdba to username

To Grant permission to Create any Table

grant create any table to username

To Grant permission to Drop any Table

grant drop any table to username

To take back Permissions

revoke create table from username

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.

Syntax for WHERE clause

SELECT column-name1,
column-name2,
column-name3,
column-nameN
from table-name WHERE [condition];

Example using WHERE clause

Consider a Student table,

s_id s_Name age address


101 Adam 15 Noida
102 Alex 18 Delhi

Compiled By: Eng. Kibwika Nasurudin Bashir


103 Abhi 17 Rohtak
104 Ankit 22 Panipat

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
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.

Syntax of SELECT Query

SELECT column-name1, column-name2, column-name3, column-nameN from table-


name;

Example for SELECT Query

Conside the following Student table,

S_id S_Name age address


101 Adam 15 Noida
102 Alex 18 Delhi
103 Abhi 17 Rohtak
104 Ankit 22 Panipat
SELECT s_id, s_name, age from Student.

The above query will fetch information of s_id, s_name and age column from Student table

S_id S_Name age

Compiled By: Eng. Kibwika Nasurudin Bashir


101 Adam 15
102 Alex 18
103 Abhi 17
104 Ankit 22

Example to Select all Records from 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.

SELECT * from student;

The above query will show all the records of Student table, that means it will show complete
Student table as result.

S_id S_Name age address


101 Adam 15 Noida
102 Alex 18 Delhi
103 Abhi 17 Rohtak
104 Ankit 22 Panipat

Example to Select particular Record based on Condition

SELECT * from Student WHERE s_name = 'Abhi';


103 Abhi 17 Rohtak

Example to Perform Simple Calculations using Select Query

Conside the following Employee table.

eid Name age salary


101 Adam 26 5000
102 Ricky 42 8000
103 Abhi 22 10000
104 Rohan 35 5000
SELECT eid, name, salary+3000 from Employee;

The above command will display a new column in the result, showing 3000 added into existing
salaries of the employees.

Compiled By: Eng. Kibwika Nasurudin Bashir


eid Name salary+3000
101 Adam 8000
102 Ricky 11000
103 Abhi 13000
104 Rohan 8000

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.

Wildcard operators

There are two wildcard operators that are used in like clause.

 Percent sign % : represents zero, one or more than one character.


 Underscore sign _ : represents only one character.

Example of LIKE clause

Consider the following Student table.

s_id s_Name age


101 Adam 15
102 Alex 18
103 Abhi 17
SELECT * from Student where s_name like 'A%';

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

Compiled By: Eng. Kibwika Nasurudin Bashir


Example

SELECT * from Student where s_name like '_d%';

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

Example

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

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

SELECT column-list|* from table-name order by asc|desc;

Example using Order by

Consider the following Emp table,

Compiled By: Eng. Kibwika Nasurudin Bashir


eid name age salary
401 Anu 22 9000
402 Shane 29 8000
403 Rohan 34 6000
404 Scott 44 10000
405 Tiger 35 8000
SELECT * from Emp order by salary;

The above query will return result 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

Example of Order by DESC

Consider the Emp table described above,

SELECT * from Emp order by salary DESC;

The above query will return result 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

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.

Compiled By: Eng. Kibwika Nasurudin Bashir


Syntax for using Group by in a statement.

SELECT column_name, function(column_name)


FROM table_name
WHERE condition
GROUP BY column_name

Example of Group by in a Statement

Consider the following Emp table.

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 9000

405 Tiger 35 8000

Here we want to find name and age of employees grouped by their salaries

SQL query for the above requirement will be,

SELECT name, age


from Emp group by salary

Result will be,

name age

Rohan 34

shane 29

anu 22

Example of Group by in a Statement with WHERE clause

Consider the following Emp table

eid name age salary

Compiled By: Eng. Kibwika Nasurudin Bashir


401 Anu 22 9000
402 Shane 29 8000
403 Rohan 34 6000
404 Scott 44 9000
405 Tiger 35 8000

SQL query will be,

select name, salary


from Emp
where age > 25
group by salary

Result will be.

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.

Syntax for having will be,

select column_name, function(column_name)


FROM table_name
WHERE column_name condition
GROUP BY column_name
HAVING function(column_name) condition

Example of HAVING Statement

Consider the following Sale table.

Compiled By: Eng. Kibwika Nasurudin Bashir


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

Suppose we want to find the customer whose previous_balance sum is more than 3000.

We will use the below SQL query,

SELECT *
from sale group customer
having sum(previous_balance) > 3000

Result will be,

oid order_name previous_balance customer


11 ord1 2000 Alex

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.

Syntax for DISTINCT Keyword

SELECT distinct column-name from table-name;

Example

Consider the following Emp table.

eid name age salary

Compiled By: Eng. Kibwika Nasurudin Bashir


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 & OR operator


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

AND operator is used to set multiple conditions with Where clause.

Example of AND

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 AND age > 25

Compiled By: Eng. Kibwika Nasurudin Bashir


The above query will return records where salary is less than 10000 and age greater than 25.

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 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

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 greater than
25.

402 Shane 29 8000


403 Rohan 34 12000
404 Scott 44 10000
405 Tiger 35 9000

Compiled By: Eng. Kibwika Nasurudin Bashir

You might also like