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

Structured Query Language

Uploaded by

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

Structured Query Language

Uploaded by

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

SQL Lab Manual PICE

DATABASE LAB REPORT

Compiled by: Melsew D

Compiled By: - Melsew d Page 1


SQL Lab Manual PICE

Structured Query Language (SQL)


SQL is a database computer language designed for the retrieval and management of data in
relational database. SQL stands for Structured Query Language.

SQL: A database programming language that uses to create and manipulate databases using the
tools/packages. In other word, SQL is a Query language for most commercial relational database
management systems (DBMS). There are many different versions of the SQL language, but to be
in compliance with the ANSI standard, they must support the same major keywords in a similar
manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and others). Most of the
SQL database programs also have their own proprietary extensions in addition to the SQL
standard such as TSQL (Transact-SQL) for Microsoft SQL Server and PLSQL and SQL plus for
Oracle.

Any DBMS should have a language for defining the structures in the database – this is called the
DDL (Data Definition Language). This is used by the database designer/administrator to build
the database.
It should also have a language for manipulating the data in the database – this is called the DML
(Data Manipulation Language). This language is used by users of the database to insert, retrieve,
modify and delete data in the database.

Generally, SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in relational database.

SQL is the standard language for Relation Database System. All relational database management
systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL
as standard database language.
Why SQL?
 Allows users to access data in relational database management systems.
 Allows users to describe the data.
 Allows users to define the data in database and manipulate that data.

Compiled By: - Melsew d Page 2


SQL Lab Manual PICE

 Allows to embed within other languages using SQL modules, libraries &
pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a database.
 Allows users to set permissions on tables, procedures and views.

SQL Process:
When you are executing an SQL command for any RDBMS, the system determines the best way to
carry out your request and SQL engine figures out how to interpret the task.

There are various components included in the process. These components are Query Dispatcher,
Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine
handles all non-SQL queries, but SQL query engine won't handle logical files.

Following is a simple diagram showing SQL Architecture:

Compiled By: - Melsew d Page 3


SQL Lab Manual PICE

SQL Commands
Unfortunately, as we discussed previously there are many different versions of the SQL
language, but to be in compliance with the ANSI standard, they must support the same major
keywords or commands in a similar manner (such as SELECT, UPDATE, DELETE, INSERT,
WHERE, and others).

The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These SQL commands are grouped or classified into
four major categories depending on their functionality or nature:

DDL -Data Definition Language:


These SQL commands are used for creating, modifying, and dropping the structure of database
objects including the database itself. The commands are CREATE, ALTER, DROP, RENAME,
and TRUNCATE.
SQL Commands /statements Description
CREATE Creates a new table, a view of a table, or other object in
database
ALTER Modifies an existing database object, such as a table.
DROP Deletes an entire table, a view of a table or other object in
the database.

DML -Data Manipulation Language:


These SQL commands are used for storing, modifying, and deleting data on database tables. These
commands are INSERT, UPDATE, and DELETE.
SQL Commands /statements Description
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records

DCL -Data Control Language:


These SQL commands are used for providing security to database objects. These commands are
GRANT and REVOKE.

Compiled By: - Melsew d Page 4


SQL Lab Manual PICE

SQL Commands /statements Description


GRANT Gives a privilege to user
REVOKE Takes back privileges granted from user

DQL -Data Query Language:


These SQL commands are used for retrieving data from database tables. The command that used to
retrieve data is SELECT command.
SQL Commands /statements Description
SELECT Retrieves certain records from one or more tables

TCL - Transaction Control Language:


These SQL commands are used for managing changes affecting the data. These commands are
COMMIT, ROLLBACK, and SAVEPOINT.

SQL Commands /statements Description


COMMIT
ROLLBACK
SAVEPOINT

SQL Data Types


SQL data type is an attribute that specifies type of data of any object. Each column, variable
and expression has related data type in SQL.

You would use these data types while creating your tables. You would choose a particular data
type for a table column based on your requirement.

SQL Server offers six categories of data types for your use:

Compiled By: - Melsew d Page 5


SQL Lab Manual PICE

Exact Numeric Data Types:

Approximate Numeric Data Types:

Compiled By: - Melsew d Page 6


SQL Lab Manual PICE

Date and Time Data Types:

Character Strings Data Types:

Compiled By: - Melsew d Page 7


SQL Lab Manual PICE

Unicode Character Strings Data Types:

Binary Data Types:

Compiled By: - Melsew d Page 8


SQL Lab Manual PICE

Misc Data Types:

SQL Operators
What is an Operator in SQL?
An operator is a reserved word or a character used primarily in an SQL statement's WHERE
clause to perform operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement. The available types of operators in SQL are the following:
Arithmetic operators
Comparison operators
Logical operators

Compiled By: - Melsew d Page 9


SQL Lab Manual PICE

SQL Arithmetic Operators:

Assume variable a holds 10 and variable b holds 20, then:

SQL Comparison Operators:


Assume variable a holds 10 and variable b holds 20, then:

\\

Compiled By: - Melsew d Page 10


SQL Lab Manual PICE

SQL Logical Operators:

Here is a list of all the logical operators available in SQL.

NOTE: Examples for each operator will be discuss in SELECT statement.

An expression is a combination of one or more values, operators, and SQL functions that
evaluate to a value.

SQL EXPRESSIONs are like formulas and they are written in query language. You can also use
them to query the database for specific set of data. We will discuss about the syntax and examples in
select statement.

Compiled By: - Melsew d Page 11


SQL Lab Manual PICE

SQL is followed by unique set of rules and guidelines called Syntax. This tutorial gives you
a quick start with SQL by listing all the basic SQL Syntax:

All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE,
DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a
semicolon (;).

Important point to be noted is that SQL is case insensitive, which means SELECT and
select have same meaning in SQL statements, but MySQL makes difference in table names.
So if you are working with MySQL, then you need to give table names as they exist in the
database.

DDL -Data Definition Language:


 CREATE DATABASE statement: is used to create new SQL database.
Syntax:

CREATE DATABASE Database_Name;

Example:
If you want to create new database called testDB, then CREATE DATABASE statement would be
as follows:
MYSQL> CREATE DATABASE testDB;
Once a database is created, you can check it in the list of databases using SHOW statement as
follows:

+ +
| Database |
+ +
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+ +
7 rows in set (0.00 sec)

Compiled By: - Melsew D Page 12


SQL Lab Manual PICE

When you have multiple databases in your SQL Schema, then before starting your operation, you
would need to select a database where all the operations would be performed.

 USE statement: is the SQL statement that used to select any existing database in SQL
schema.
Syntax:
USE Database_name;
Example: if you want to work with testDB database, then you can execute the following SQL
command and start working with testDB database.
MYSQL> USE testDB;
 DROP DATABASE statement: is used to drop or delete an existing database in SQL
schema.
Syntax:

DROP DATABASE Database-name;

Example:
If you want to delete an existing database <testDB>, then DROP DATABASE statement would
be as follows:

MYSQL> DROP DATABASE testDB;

NOTE: Be careful before using this operation because by deleting an existing database would
result in loss of complete information stored in the database.

SQL CREATE Table

Creating a basic table involves naming the table, defining its columns, fixing each column's data
type and defining constraints.
o CREATE TABLE statement: is used to create a new table object of database.

Compiled By: - Melsew D Page 13


SQL Lab Manual PICE

Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY (one or more columns)
);

 Table_name - is the name of the table.


 Column_name1, column_name2.... - is the name of the columns
 Datatype - is the datatype for the column like char, date, number etc.
Example:
Creates a CUSTOMERS table with ID, Name, Age, Address, and Salary as likes follows: MYSQL>
CREATE TABLE customers (
Id int not null, Name
varchar (20), Age int
,
Address char (25) ,
Salary decimal (18, 2),
Primary key (id)
);

SQL Constraints:
Here as we discussed theoretically there are constraints that are the rules enforced on data columns
on table. These are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database. Constraints could be column level or table level.
Column level constraints are applied only to one column, whereas table level constraints are
applied to the whole table.

So, in this lab we will see the following commonly used constraints available in SQL:
 NOT NULL Constraint: Ensures that a column cannot have NULL value.
 DEFAULT Constraint: Provides a default value for a column when none is specified.

Compiled By: - Melsew D Page 14


SQL Lab Manual PICE

 UNIQUE Constraint: Ensures that all values in a column are different.


 PRIMARY Key Constraint: Uniquely identified each rows/records in a database table.
 FOREIGN Key Constraint: Uniquely identified a rows/records in any another
database table.
 CHECK Constraint: The CHECK constraint ensures that all values in a column
satisfy certain conditions.
 INDEX: Use to create and retrieve data from the database very quickly.
NOT NULL Constraint
By default, a column can hold NULL values. If you do not want a column to have a NULL value,
then you need to define such constraint on this column specifying that NULL is now not allowed
for that column. A NULL is not the same as no data, rather, it represents unknown data.

Example:
Creates a CUSTOMERS table with ID as primary key and NOT NULL are the constraints
showing that these fields cannot be NULL while creating records in this table:
MYSQL> CREATE TABLE customers ( Id
int not null,
Name varchar (20) not null, Age
int not null,
Address char (25),
Salary decimal (18, 2),
Primary key (id)
);

If customers table has already been created, then to add a NOT NULL constraint to SALARY
column in Oracle and MySQL, you would write a statement similar to the following:
ALTER TABLE customers
Modify salary decimal (18, 2) not null;
DEFAULT Constraint
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.

Compiled By: - Melsew D Page 15


SQL Lab Manual PICE

Example:
For example, the following SQL creates a new table called customers and adds five columns.
Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO statement does
not provide a value for this column. Then by default this column would be set to 5000.00.
CREATE TABLE customers (
Id int not null,
Name varchar (20) not null, Age
int not null,
Address char (25),
Salary decimal (18, 2) default 5000.00, Primary
key (id)
);

If customers table has already been created, then to add a DFAULT constraint to SALARY
column, you would write a statement similar to the following:
ALTER TABLE customers
MODIFY SALARY DECIMAL (18, 2) default 5000.00;

To drop a DEFAULT constraint, use the following SQL: ALTER


TABLE CUSTOMERS
ALTER COLUMN SALARY DROP DEFAULT;

UNIQUE Constraint
The UNIQUE Constraint prevents two records from having identical values in a particular column.
In the CUSTOMERS table, for example, you might want to prevent two or more people from
having identical age.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, AGE column is set to UNIQUE, so that you can not have two records with same
age:
CREATE TABLE customers (
Id int not null,
Name varchar (20) not null, Age
int not null unique, Address char
(25),
Salary decimal (18, 2),
Primary key (id)
);

Compiled By: - Melsew D Page 16


SQL Lab Manual PICE

If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;

You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myUniqueConstraint UNIQUE (AGE, SALARY); To
drop a UNIQUE constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myUniqueConstraint;
If you are using MySQL, then you can use the following syntax:
ALTER TABLE CUSTOMERS
DROP INDEX myUniqueConstraint;
PRIMARY Key Constraint
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values. A
table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key. If a table has a primary
key defined on any field(s), then you cannot have two records having the same value of that
field(s).

Note: You would use these concepts while creating database tables.

Here is the syntax to define ID attribute as a primary key in a CUSTOMERS table.


CREATE TABLE customers (
Id int not null,
Name varchar (20) not null,
Age int not null,
Address char (25) ,
Salary decimal (18, 2),
Primary key (id)
);

Compiled By: - Melsew D Page 17


SQL Lab Manual PICE

To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already
exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table was first
created).

For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME)
);
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
You can clear or delete the primary key constraints from the table, Use Syntax: ALTER
TABLE CUSTOMERS DROP PRIMARY KEY;

FOREIGN Key Constraint


A foreign key is a key used to link two tables together. This is sometimes called a referencing
key. Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table. The relationship between two tables matches the Primary Key in one of the tables
with a Foreign Key in the second table. If a table has a primary key defined on any field(s), then
you cannot have two records having the same value of that field(s).
Example: Consider the structure of the two tables as follows:
CUSTOMERS table:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,

Compiled By: - Melsew D Page 18


SQL Lab Manual PICE

NAME VARCHAR (20) NOT NULL,


AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
ORDERS table:
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS (ID),
AMOUNT double,
PRIMARY KEY (ID)
);

If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax
for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS
DROP FOREIGN KEY;

CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn’t entered into the table.

Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, we add a CHECK with AGE column, so that you can not have any CUSTOMER
below 18 years:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Compiled By: - Melsew D Page 19


SQL Lab Manual PICE

If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you
would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL CHECK (AGE >= 18);

You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myCheckConstraint CHECK (AGE >= 18);

To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myCheckConstraint;

INDEX Constraint
The INDEX is used to create and retrieve data from the database very quickly. Index can be created
by using single or group of columns in a table. When index is created, it is assigned a ROWID for
each row before it sorts out the data. Proper indexes are good for performance in large databases,
but you need to be careful while creating index. Selection of fields depends on what you are using in
your SQL queries.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, you can create index on single or multiple columns using the following syntax: CREATE
INDEX index_name
ON table_name (column1, column2. ......... );

To create an INDEX on AGE column, to optimize the search on customers for a particular

Compiled By: - Melsew D Page 20


SQL Lab Manual PICE

age, following is the SQL syntax:


CREATE INDEX idx_age
ON CUSTOMERS (AGE);
To drop an INDEX constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;

o SHOW TABLES statement: is used to show the existing tables in the database.
Syntax:
SHOW tables;

o DESCRIBE TABLE statement: is used to give information about the fields in a


table. You can verify if your table has been created successfully by this command.
Syntax:
DESCRIBE table_name;
Example:
MYSQL> Describe CUSTOMERS;

o DROP TABLE statement: is used to remove a table definition and all data, indexes,
triggers, constraints, and permission specifications for that table. The SQL DROP
command is used to remove an object from the database. If you drop a table, all the rows in
the table are deleted and the table structure is removed from the database. Once a table is
dropped we cannot get it back, so be careful while using DROP command. When a table
is dropped all the references to the table will not be valid.

NOTE: You have to be careful while using this command because once a table is deleted then all
the information available in the table would also be lost forever.
Syntax:
DROP TABLE table_name;

Example:
To drop CUSTOMERS table from database
MYSQL> DROP TABLE CUSTOMERS;
o ALTER TABLE statement: is used to add, drop or modify table columns. The SQL

Compiled By: - Melsew D Page 21


SQL Lab Manual PICE

ALTER TABLE command is used to modify the definition (structure) of a table by


modifying the definition of its columns. The ALTER command is used to perform the
following functions.
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints
Syntax:

ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};

Let’s write the syntax for each operation


Syntax for ADD
ALTER TABLE table_name ADD column_name datatype;

Syntax for DROP


ALTER TABLE table_name DROP column_name;

Syntax for MODIFY


ALTER TABLE table_name MODIFY column_name datatype;

Example:
o RENAME TABLE statement: is used to change the name of the table or a database
object.
Syntax:

RENAME old_table_name To new_table_name;

With RENAME statement you can rename a table. Some of the relational database management
system (RDBMS) does not support this command, because this is not standardizing statement.
So use the following syntax:
RENAME TABLE {oldtable_name} TO {newtable_name};
Where {oldtable_name} table that exists in the current database, and {newtable_name} is new
table name.
Example:
To change the name of the table employee to my_employee, the query would be like
RENAME table employee TO my_emloyee;
Compiled By: - Melsew D Page 22
SQL Lab Manual PICE

DML -Data Manipulation Language:


INSERT INTO table statement: is used to add new records/rows of data into a database
table. We can insert data to a table in two ways.
Syntax:
INSERT INTO table_name [(col1, col2, col3...colN)]
VALUES (value1, value2, value3...valueN);
Or
INSERT INTO table_name VALUES (value1, value2, value3...valueN);

N.B: You may not need to specify the column(s) name in the SQL query if you are adding values
for all the columns of the table. But make sure the order of the values is in the same order as the
columns in the table.

Example:

If you want to insert a row to the employee table, the query would be like,
INSERT INTO employee (id, name, dept, age, salary location) VALUES (105, 'Srinath',
'Aeronautics', 27, 33000);

NOTE: When adding a row, only the characters or date values should be enclosed with single
quotes.

If you are inserting data to all the columns, the column names can be omitted. The above insert
statement can also be written as:
INSERT INTO employee
VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);

Assume we have created the following tables in the database: Student table and Teacher table. These
database tables are used here for better explanation of SQL DML commands/statements. And
starting from this we are going to manipulate data on this tables.

Compiled By: - Melsew D Page 23


SQL Lab Manual PICE

Create Database Tables

CREATE TABLE student (


Sid int not null,
Fname varchar (20) not null,
Lname varchar (15) not null,
Sex char (2),
Age int not null,
Department varchar (15) not null,
Primary key (Sid)
);

CREATE TABLE Teacher (


Tid int not null,
Fname varchar (20) not null,
Lname varchar (15) not null,
Sex char (2),
Age int not null,
Department varchar (15) not null,
Primary key (Tid)
);

Insert records/data into database tables

INSERT INTO student


VALUES (100, 'Haile', 'Abebe', ‘M’, 27, ‘IT’);

Based on this insert the following records into student table.

INSERT INTO teacher


VALUES (20, 'Daniel', 'Dagne', ‘M’, 47, ‘Electrical’);

Compiled By: - Melsew D Page 24


SQL Lab Manual PICE

Based on this insert the following records/data into teacher table.

UPDATE Statement: is used to change the value in an existing record. A Statement is used
to modify the existing rows in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2. ...columnN=valueN
[WHERE CONDITION];

 Table_name - the table name which has to be updated.


 Column_name1, column_name2.. - The columns that gets changed.
 Value1, value2... - are the new values.

NOTE: In the Update statement, WHERE clause identifies the rows that get affected. If you do
not include the WHERE clause, column values for all the rows get affected.
Example: To update the department of betelehem from student table by Maths

UPDATE student
SET Department= ‘Maths’
WHERE Sid=102;

DELETE Statement: is used to delete rows from a table.


Syntax:
DELETE FROM table_name

Compiled By: - Melsew D Page 25


SQL Lab Manual PICE

 Table_name -- the table name which has to be updated.

NOTE: The WHERE clause in the SQL delete command is optional and it identifies the rows in
the column that gets deleted. If you do not include the WHERE clause all the rows in the table is
deleted, so be careful while writing a DELETE query without WHERE clause.

Example: To delete a student with Sid 100 from the student table, the SQL delete query would be
like,
DELETE FROM student WHERE Sid = 100;
To delete all the rows from the student table, the query would be like, DELETE
FROM student;

DQL -Data Query Language:


SELECT statement: The most commonly used SQL command/statement is SELECT
statement. The SQL SELECT statement is used to query or retrieve data from a table in the
database. A query may retrieve information from specified columns or from all of the
columns in the table. To create a simple SQL SELECT Statement, you must specify the
column(s) name and the table name. The whole query is called SQL SELECT Statement.
Syntax:
SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY Clause]
[HAVING Clause]
[ORDER BY Clause];

 Column_list includes one or more columns from which data is retrieved.


 Table-name is the name of the table from which the information is retrieved.
 The codes within the brackets are optional.

NOTE: In a SQL SELECT statement only SELECT and FROM statements are mandatory. Other
clauses like WHERE, ORDER BY, GROUP BY, HAVING are optional.

Compiled By: - Melsew D Page 26


SQL Lab Manual PICE

Simple SQL Query examples:


To retrieve or extract all data/attributes of rows/records in the student table

SELECT *from Student;


To retrieve Fname and Lname of Student SELECT

Fname, Lname from Student;

To retrieve specific data/records based on criteria from database tables you can use SQL clauses
and operators.

The operators are evaluated in a specific order of precedence, when more than one arithmetic
operator is used in an expression. The order of evaluation is: parentheses, division, multiplication,
addition, and subtraction. The evaluation is performed from the left to the right of the expression.

For example: If we want to display the first and last name of student combined together, the
SQL Select Statement would be like:
SELECT Fname, Lname FROM student;

SQL Clauses

SQL clauses are used to manipulate data on database. In this manual we will see some clauses,
operators and expressions in SQL with example in different SQL commands/statements.

Compiled By: - Melsew D Page 27


SQL Lab Manual PICE

SQL WHERE Clause


The WHERE Clause is used when you want to retrieve specific information from a table
excluding other irrelevant data. Retrieving information about all the data would increase the
processing time for the query. So, SQL offers a feature called WHERE clause, which we can use
to restrict the data that is retrieved. The condition you provide in the WHERE clause filters the
rows retrieved from the table and gives you only those rows which you expected to see. WHERE
clause can be used along with SELECT, DELETE, and UPDATE statements.

Syntax of SQL WHERE Clause:


WHERE {column or expression} comparison-operator value
 column or expression - Is the column of a table or a expression
 Comparison-operator - operators like = < > etc.
 Value - Any user value or a column name for comparison
Syntax for a WHERE clause with Select statement is:
SELECT column_list
FROM table-name
WHERE condition;

For Example: To find or retrieve the Fname and Lname of a student with id 100, the query would
be like:
SELECT Fname, Lname FROM student
WHERE id = 100;
N.B: Comparison Operators and Logical Operators are used in WHERE Clause.

For Example: To find the name of a student with age above 20, the query would be like: SELECT
Fname, Lname FROM student
WHERE Age>20;

SELECT Fname, Lname, age FROM


student
WHERE age > 20 AND department=’Civil’;

Compiled By: - Melsew D Page 28


SQL Lab Manual PICE

SELECT Fname, Lname, age FROM


student
WHERE age > 20 or department=’Civil’;

NOTE: Aliases defined for the columns in the SELECT statement cannot be used in the
WHERE clause to set conditions. Only aliases created for tables can be used to reference the columns
in the table.

How to use expressions in the WHERE Clause?


Expressions can also be used in the WHERE clause of the SELECT statement.

NOTE: Aliases defined in the SELECT Statement can be used in WHERE Clause.

SQL ORDER BY Clause


The ORDER BY clause is used in a SELECT statement to sort results either in ascending or
descending order. Oracle sorts query results in ascending order by default.
Syntax for using SQL ORDER BY clause to sort data is:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1 [, column2... columnN] [DESC|ASCE]];

Examples see the output of the following query:

SELECT * from student


ORDER BY Fname;

You can also use more than one column in the ORDER BY clause.

SELECT * from student


ORDER BY Fname, age;

NOTE: The columns specified in ORDER BY clause should be one of the columns selected in the
SELECT column list.

Compiled By: - Melsew D Page 29


SQL Lab Manual PICE

You can represent the columns in the ORDER BY clause by specifying the position of a column in
the SELECT list, instead of writing the column name.

Example we can write as follows,

SELECT Fname, Lname FROM student ORDER BY 2, 3;

By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the data in
descending order, you must explicitly specify it as shown below.

SELECT Fname, Lname


FROM student
ORDER BY Fname, Lname DESC;

The above query sorts only the column 'Lname' in descending order and the column 'Fname' by
ascending order.

If you want to select both Fname and Lname in descending order, the query would be as given
below.

SELECT Fname, Lname


FROM student
ORDER BY Fname DESC, Lname DESC;

How to use expressions in the ORDER BY Clause?


Expressions in the ORDER BY clause of a SELECT statement.

NOTE: Aliases defined in the SELECT Statement can be used in ORDER BY Clause.

SQL GROUP BY Clause

The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups.

The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.

Compiled By: - Melsew D Page 30


SQL Lab Manual PICE

GROUP BY operates on the rows from the FROM clause as filtered by the WHERE clause. It
collects the rows into groups based on common values in the grouping columns. Except nulls,
rows with the same set of values for the grouping columns are placed in the same group. If any
grouping column for a row contains a null, the row is given its own group.

Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [conditions]
GROUP BY column1, column2
ORDER BY column1, column2

Example
SELECT Fname, Department
FROM student
GROUP BY Department;
The output would be like:

But as you can see from the table one Fname value is left that is Endalew Kassa because you did
not include all select columns in the GROUP BY clause.

NOTE: The GROUP BY clause should contain all the columns in the select list expect those
used along with the group functions. Group functions can appear with select statement as
follows:

Compiled By: - Melsew D Page 31


SQL Lab Manual PICE

SELECT Fname, department, SUM (attribute)


FROM student
GROUP BY Fname, department;
Example in our case
SELECT Fname, department, SUM (salary) FROM
student
GROUP BY Fname, department; The

output would be like:

The SQL GROUP BY Clause is also used along with the group functions (built-in functions) to
retrieve data grouped according to one or more columns. In Grouping Queries, the select list can
only contain grouping columns, plus literals, outer references and expression involving these
elements. Non-grouping columns from the underlying FROM tables cannot be referenced
directly. However, non-grouping columns can be used in the select list as arguments to Set
Functions. Set Functions summarize columns from the underlying rows of a group.

SQL HAVING Clause


Having clause is used to filter data based on the group functions. This is similar to WHERE
condition but is used with group functions. Group functions cannot be used in WHERE Clause
but can be used in HAVING clause.

Compiled By: - Melsew D Page 32


SQL Lab Manual PICE

The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause.

SQL HAVING Clause syntax:


SELECT column1, column2, function FROM table1, table2
WHERE [conditions]
GROUP BY column1, column2
HAVING < [conditions (i.e. group function)]> <operator> value
ORDER BY column1, column2;

The HAVING clause must follow the GROUP BY clause in a query and must also precedes the
ORDER BY clause if used. The following is the syntax of the SELECT statement, including the
HAVING clause:

SQL HAVING Clause Example


The Following is the example, which would display record for which similar age count would be
more than or equal to 2:
SELECT * FROM student
GROUP BY age
HAVING COUNT (age) >= 2;

The output would be like:

As we discussed in the select statement WHERE, GROUP BY and HAVING clauses are used
together in a SELECT statement. And when this clauses are used together in a SELECT
statement, the WHERE clause is processed first, then the rows that are returned after the WHERE
clause is executed are grouped based on the GROUP BY clause.

Compiled By: - Melsew D Page 33


SQL Lab Manual PICE

Finally, any conditions on the group functions in the HAVING clauses are applied to the grouped rows
before the final output is displayed.

SQL LIKE Clause


The SQL LIKE clause is used to compare a value to similar values using wildcard operators.
There are two wildcards used in conjunction with the LIKE operator:
The percent sign (%)
The underscore (_)

The percent sign represents zero, one, or multiple characters. The underscore represents a single
number or character. The symbols can be used in combinations

Syntax:
The basic syntax of „%‟ and „_‟ is as follows:
SELECT FROM table_name
WHERE column LIKE 'XXXX%'
or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
or

Compiled By: - Melsew D Page 34


SQL Lab Manual PICE

SELECT FROM table_name


WHERE column LIKE '_XXXX_'

Note: You can combine N number of conditions using AND or OR operators. Here, XXXX
could be any numeric or string value.

Example:
Here are number of examples showing WHERE part having different LIKE clause with '%' and
'_' operators:

The following is an example, which would display all the records from student table where
Fname starts with B:

SELECT * FROM student


WHERE Fname LIKE 'B%';

The output would be like:

Compiled By: - Melsew D Page 35


SQL Lab Manual PICE

SQL Joins/Table Relationships


Types of relationships include one-to-one, one-to-many and many-to-many.
One to one
Create table Husband (Hid int, Hname varchar (10), Hsex char, Hage int, Primary key (Hid));

Create table Wife (Wid int, Wname varchar (10), Wsex char, Wage int, Primary key (Wid));

So will first create a table for Husband, insert some data, then create a separate table for Wife
using the field Wid within the Wife table to insert the primary Wid and form the relationship
between the two tables:

To select or retrieve data jointly from two or more tables we will use join conditions.
The Syntax for joining two tables is:
SELECT col1, col2, col3...
FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;
So, to get a list of Husbands along with their corresponding Wife you'll need to perform a table
join on Husband. Hid = Wife.Wid for the two tables using a one-to-one relationship like so:

Compiled By: - Melsew D Page 36


SQL Lab Manual PICE

SELECT *
FROM husband, wife
WHERE husband.hid = Wife.wid
ORDER BY husband. hname ASC;

One To Many
In this type of relationship you identify the table representing the many side of the relationship
and add the primary key of the one side table to it.

Example for this cardinality is department to employee. So in this instance many employees belong
to one department therefore we add the field department id to the employee table and perform a
table join on employee.eid = department. did to retrieve employees and their corresponding
department.

So let’s create the department table, insert some records, and create employee table and insert
some records.

Create table department (Did int, Dname varchar (10), Dlocation int, Primary key (Hid));

Create table employee (Eid int, Did int, Ename varchar (10), Esex int, Eage int, Primary key
(Eid));

And finally to get/retrieve a list of employees and their department we perform a table join on
department. did = employee.eid for the two tables using a one-to-many relationship like so:

SELECT *
FROM department, employee
WHERE department. did = employee.eid

Many To Many
A relationship that is multi-valued in both directions is a many-to-many relationship. An
example for this cardinality of relationship is student to course. A student can take more than

Compiled By: - Melsew D Page 37


SQL Lab Manual PICE

one course, and a course can be taken by more than one student. So, this type of relationship is
helped by the use of a linking table student_course (the third table).

So first let's create a table for student and course and then insert some records, then create a
linking table called student_course which will help us join relationships between the two
tables student and course, then insert existing primary id's of both student and their course so we
can make the relationship work:

Create table student (Sid int, Sname varchar (10), Ssex int, Sage char, Primary key (Sid)); Create

table course (Cid int, Ccode int, Cname varchar (10), Ccredit int, Primary key (Cid)); Create table

student_course (Sid int, Cid int);

Finally, to obtain or select a list of departments and what type/number of employees they employed we
perform a table joins Student_Student.Sid = student. Sid
AND Student_Student.Cid = Course.Cid for the three tables using a many-to-many relationship like
so:

SELECT *
FROM student, course, student_course
WHERE student_course.sid = student.sid
AND student_course.cid = course.cid
ORDER BY student. Sname ASC;

SQL Joins are used to relate information in different tables. A Join condition is a part of the SQL
query that retrieves rows from two or more tables. The SQL Joins clause is used to combine
records from two or more tables in a database. A JOIN is a means for combining fields from two
tables by using values common to each. A SQL Join condition is used in the SQL WHERE
Clause of SELECT, UPDATE, DELETE statements.

Compiled By: - Melsew D Page 38


SQL Lab Manual PICE

If a SQL join condition is omitted or if it is invalid the join operation will result in a Cartesian
product. The Cartesian product returns a number of rows equal to the product of all rows in all
the tables being joined. For example, if the first table has 20 rows and the second table has 10
rows, the result will be 20 * 10 or 200 rows. This query takes a long time to execute.

Note: Here, it is noticeable that the join is performed in the WHERE clause. Several operators
can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can
all be used to join tables. However, the most common operator is the equal symbol.

Note: we have used one of the type of joint condition that is inner join. But there are a number of
joint conditions.

Inner Join:
All the rows returned by the SQL query satisfy the SQL join condition specified. Returns rows
when there is a match in both tables. The most frequently used and important of the joins is the
INNER JOIN.

The INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate. The query compares each row of table1 with each row
of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a result
row.

Syntax:
The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;

NB: You can leave INNER JOIN word in the above Syntax. Because this condition is implicit in
the where clause as previous one.

Compiled By: - Melsew D Page 39


SQL Lab Manual PICE

LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if the ON clause matches 0 (zero) records in right table, the join will
still return a row in the result, but with NULL in each column from right table.

This means that a left join returns all the values from the left table, plus matched values from the
right table or NULL in case of no matching join predicate.

Syntax:

The basic syntax of LEFT JOIN is as follows:

SELECT table1.column1, table2.column2...


FROM table1
LEFT JOIN table2
ON table1.common_filed = table2.common_field;

RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the
left table. This means that if the ON clause matches 0 (zero) records in left table, the join will
still return a row in the result, but with NULL in each column from left table.

This means that a right join returns all the values from the right table, plus matched values from
the left table or NULL in case of no matching join predicate.

Syntax:
The basic syntax of RIGHT JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_filed = table2.common_field;

FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.

Compiled By: - Melsew D Page 40


SQL Lab Manual PICE

The joined table will contain all records from both tables, and fill in NULLs for missing matches
on either side.

Syntax:
The basic syntax of FULL JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;

CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records
from the two or more joined tables. Thus, it equates to an inner join where the join-condition
always evaluates to True or where the join-condition is absent from the statement.
Syntax:
The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]

Compiled By: - Melsew D Page 41


SQL Lab Manual PICE

SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or more tables
can be seen. Views do not contain data of their own. They are used to restrict access to the
database or to hide data complexity. A view is stored as a SELECT statement in the database.
DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original
table upon which the view is based.
The Syntax to create a SQL view is
CREATE VIEW view_name
AS
SELECT column_list
FROM table_name [WHERE condition];
 View_name is the name of the VIEW.
 The SELECT statement is used to define the columns and rows that you want to display
in the view.

Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.

For Example: to create a view on the product table the SQL query would be like
CREATE VIEW view_product
AS
SELECT product_id, product_name
FROM product;

We can query the view above as follows:

SELECT * FROM VIEW_PRODUCT


SQL Updating a View
You can update a view by using the following syntax:
SQL CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Compiled By: - Melsew D Page 42


SQL Lab Manual PICE

Now we want to add the "Category" column to the "Current Product List" view. We will update
the view with the following SQL:

CREATE VIEW [Current Product List] AS


SELECT Product_id, Product_Name, Category
FROM Products;
SQL Dropping a View
You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax

DROP VIEW view_name

Nested Queries
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. A Subquery is usually added in
the WHERE Clause of the SQL statement. Most of the time, a Subquery is used when you know
how to search for a value using a SELECT statement, but do not know the exact value.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following SQL statements along with the comparisons operators
like =, <, >, >=, <=, IN, BETWEEN etc.
 SELECT

 INSERT
 UPDATE
 DELETE
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 cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY 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.

Compiled By: - Melsew D Page 43


SQL Lab Manual PICE

 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.
Subqueries with the SELECT Statement:
Subqueries are most frequently used with the SELECT statement. T he basic syntax is as
follows:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

Example: Consider the CUST OMERS table having the following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now, let us check following subquery with SELECT statement:
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500);

This would produce the following result:

Compiled By: - Melsew D Page 44


SQL Lab Manual PICE

Subqueries with the INSERT Statement:

Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.

The basic syntax is as follows:


INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

Example: Consider a table CUST OMERS_BKP with similar structure as CUST OMERS table.
Now to copy complete CUST OMERS table into CUST OMERS_BKP, following is the syntax:
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS);

Subqueries with the UPDATE Statement:


The subquery can be used in conjunction with the UPDATE statement. Either sing le or multiple
columns in a table can be updated when using a subquery with the UPDAT E statement.
The basic syntax is as follows:
UPDATE table
SET column_name = new_value
[WHERE OPERATOR [VALUE]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[WHERE)]

Compiled By: - Melsew D Page 45


SQL Lab Manual PICE

Example: Assuming, we have CUST OMERS_BKP table available which is backup of CUST
OMERS table.
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27:
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27);

This would impact two rows and finally CUST OMERS table would have the following records:

Subqueries with the DELETE Statement:


The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows:
DELETE FROM TABLE_NAME
[WHERE OPERATOR [VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[WHERE)]

Example: Assuming, we have CUST OMERS_BKP table available which is backup of CUST
OMERS table.
Following example deletes records from CUST OMERS table for all the customers whose AGE
is greater than or equal to 27:
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP

Compiled By: - Melsew D Page 46


SQL Lab Manual PICE

WHERE AGE > 27);

This would impact two rows and finally CUST OMERS table would have the following records:

NOTE:
1) You can nest as many queries you want but it is recommended not to nest more than 16
Subqueries in oracle.
2) If a subquery is not dependent on the outer query it is called a non-correlated subquery.

SQL Index

Index in SQL is created on existing tables to retrieve the rows quickly. When there are thousands
of records in a table, retrieving information will take a long time. Therefore indexes are created
on columns which are accessed frequently, so that the information can be retrieved quickly.
Indexes can be created on a single column or a group of columns. When a index is created, it
first sorts the data and then it assigns a ROWID for each row.
Syntax to create Index:
CREATE INDEX index_name
ON table_name (column_name1,column_name2...);

Syntax to create SQL unique Index:


CREATE UNIQUE INDEX index_name
ON table_name (column_name1,column_name2...);
 Index_name is the name of the INDEX.
 table_name is the name of the table to which the indexed column belongs.

Compiled By: - Melsew D Page 47


SQL Lab Manual PICE

 column_name1, column_name2.. is the list of columns which make up the INDEX.

In Oracle there are two types of SQL index namely, implicit and explicit.

Implicit Indexes:
They are created when a column is explicit defined with PRIMARY KEY, UNIQUE KEY
Constraint.
Explicit Indexes:
They are created using the "create index.. " syntax.

NOTE:
1) Even though sql indexes are created to access the rows in the table quickly, they slow down
DML operations like INSERT, UPDATE, DELETE on the table, because the indexes and tables
both are updated along when a DML operation is performed. So use indexes only on columns
which are used to search the table frequently.
2) Is not required to create indexes on table which have less data.
3) In oracle database you can define up to sixteen (16) columns in an INDEX.

SQL Useful built-in Functions


Functions are built-in SQL functions that operate on groups of rows and return one value for the
entire group. SQL has many built-in functions for performing processing on string or numeric
data. Following is the list of all useful SQL built-in functions:

SQL COUNT Function - The SQL COUNT aggregate function is used to count the number
of rows in a database table. This function returns the number of rows in the table that satisfies
the condition specified in the WHERE condition. If the WHERE condition is not specified,
then the query returns the total number of rows in the table.

For Example: If you want the number of employees in a particular department, the query
would be:
SELECT COUNT (*) FROM employee
WHERE department = „Computer Science‟;
If you want the total number of employees in all the department, the query would take the
form:

Compiled By: - Melsew D Page 48


SQL Lab Manual PICE

SELECT COUNT (*) FROM employee;


SQL DISTINCT Function: This function is used to select the distinct rows.
For Example: If you want to select all distinct department names from employee table, the
query would be:
SELECT DISTINCT department FROM employee;
To get the count of employees with unique name, the query would be:
SELECT COUNT (DISTINCT name) FROM employee;
SQL MAX Function - The SQL MAX aggregate function allows us to select the highest
(maximum) value for a certain column. This function is used to get the maximum value from
a column.
For Example: To get the maximum salary drawn by an employee, the query would be:
SELECT MAX (salary) FROM employee;
SQL MIN Function - The SQL MIN aggregate function allows us to select the lowest
(minimum) value for a certain column. This function is used to get the minimum value from
a column.
For Example: To get the minimum salary drawn by an employee, the query would be:
SELECT MIN (salary) FROM employee;
SQL AVG Function - The SQL AVG aggregate function selects the average value for certain
table column. This function is used to get the average value of a numeric column.
For Example: To get the average salary, the query would be
SELECT AVG (salary) FROM employee;
SQL SUM Function - The SQL SUM aggregate function allows selecting the total for a
numeric column. This function is used to get the sum of a numeric column.
For Example: To get the total salary given out to the employees,
SELECT SUM (salary) FROM employee;
SQL SQRT Functions - This is used to generate a square root of a given number.
SQL RAND Function - This is used to generate a random number using SQL command.
SQL CONCAT Function - This is used to concatenate any string inside any SQL command.
SQL Numeric Functions - Complete list of SQL functions required to manipulate numbers in
SQL.

Compiled By: - Melsew D Page 49


SQL Lab Manual PICE

SQL String Functions - Complete list of SQL functions required to manipulate strings in
SQL.

Adding or Creating user (User account)


In the Previous MySQL tutorial, we did all of the editing or operations in MySQL as the root
user, with full access to all of the databases. However, in the cases where more restrictions may
be required, there are ways to create users with custom permissions.

You can create MySQL accounts or users in two ways:


1. Using CREATE USER Command and
2. Using GRANT Command.

The basic Syntax for creating user using CREATE USER Command is:
Create user “user_name” identified by “Password”

Example: To create a user „abebe‟ identified by „123‟ password:


Create user 'abebe'@'localhost' identified by '123';

If you are running the code/site accessing MySQL on the same machine, hostname would be
localhost.

NOTE: At this point newuser abebe has no permissions to do anything with the databases. In
fact, if newuser even tries to login (with the password, password), they will not be able to reach
the MySQL shell.

We can also use the SQL command GRANT to both create a new user and to set the needed
privileges at the same time, this is done in the following way:

The basic Syntax for creating user using GRANT Command is:
GRANT usage (Privilege) ON *.* TO „User@hostname‟ IDENTIFIED BY 'password';

The asterisks in this command refer to the database and table (respectively) that they can
access—this specific command allows to the user to perform usages (the tasks) across all the
databases and tables.

Compiled By: - Melsew D Page 50


SQL Lab Manual PICE

To test out your new user, log out by typing


Quit
And log back in with this command in terminal:
Mysql -u [username]-p

Once you have finalized the permissions that you want to set up for your new users, always be
sure to reload all the privileges.
FLUSH PRIVILEGES;
Your changes will now be in effect.

To see the users you have or are created use the following syntax:
SELECT user FROM mysql.user;

To see current user you are in:


SELECT USER (), CURRENT_USER ();

To Changing users Account Passwords


SET PASSWORD FOR 'user'@'localhost' = PASSWORD ('NewPass');

To delete the user created


Drop user „Username‟;

DCL-Data Control Language:


SQL GRANT Command
DCL commands are used to enforce database security in a multiple user database environment.
Two types of DCL commands are GRANT and REVOKE. Only Database Administrator's or
owner's of the database object can provide/remove privileges on a database object.

SQL GRANT is a command:


SQL GRANT is a command used to provide access or privileges on the database objects to the
users. This command also used to create users and grant rights to databases, tables, etc.

Compiled By: - Melsew D Page 51


SQL Lab Manual PICE

The Syntax for the GRANT command is:


GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
 Privilege_name is the access right or privilege granted to the user. Some of the access
rights are the following (i.e. List of common possible permissions or privileges that users
can enjoy).

o ALL PRIVILEGES- as we saw previously, this would allow a MySQL user all access
to a designated database (or if no database is selected, across the system)
o CREATE- allows them to create new tables or databases
o DROP- allows them to them to delete tables or databases
o DELETE- allows them to delete rows from tables
o INSERT- allows them to insert rows into tables
o SELECT- allows them to use the Select command to read through databases
o UPDATE- allow them to update table rows
o GRANT OPTION- allows them to grant or remove other users' privileges
 Object_name is the name of a database object like TABLE, VIEW, STORED PROC and
SEQUENCE.
 User_name is the name of the user to whom an access right is being granted.
 PUBLIC is used to grant access rights to all users.
 ROLES are a set of privileges grouped together.
 WITH GRANT OPTION - allows a user to grant access rights to other users.

To provide a specific user with permission, you can use this framework:
GRANT [type of permission] ON [database name].[table name] TO „[username]‟@'localhost‟;

If you want to give them access to any database or to any table, make sure to put an asterisk (*)
in the place of the database name or table name. Each time you update or change a permission
be sure to use the FLUSH PRIVILEGES command.

Example: To create user abebe and to provide all privileges on all database and tables:

Compiled By: - Melsew D Page 52


SQL Lab Manual PICE

CREATE USER „abebe@localhost‟ IDENTIFIED BY '123';


Grant all privileges on *.* to „abebe‟@‟localhost‟ with grant option;

If you have the user abebe you can simply provide privilege as follows:
Grant all privileges on *.* to „Abebe‟@‟localhost‟ identified by '123' with grant option;

To create a user abebe and to provide all privilege on all tables of PICE database:

Create user 'abebe‟@‟localhost' identified by '123';


Grant all on PICE.* to 'abebe'@'localhost' identified by '123';

To create a user abebe and assign select privilege on course table of dbstudent database:
Create user 'abebe'@'localhost' identified by '123';
Grant select on dbstudent.course to 'abebe'@'localhost' identified by '123';

To create a user abebe and assign select, insert, delete privileges on course table of dbstudent
database:

Create user 'abebe'@'localhost' identified by '123';


Grant select, insert, delete on dbstudent.course to 'abebe'@'localhost' identified by '123';

To check the privileges for an account or user we can use SHOW GRANTS command:
SHOW GRANTS FOR 'User'@'hostname';

SQL REVOKE Command:

The REVOKE command removes user access rights or privileges to the database objects.

The Syntax for the REVOKE command is:


REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}

If you need to revoke a permission, the structure is almost identical to granting it:
REVOKE [type of permission] ON [database name]. [Table name] FROM
„[username]‟@„localhost‟;

Compiled By: - Melsew D Page 53


SQL Lab Manual PICE

Example: To remove all privileges on all databases and all tables from user abebe:
REVOKE ALL PRIVILEGES ON *.*
FROM „abebe‟@‟localhost‟;

To remove select privilege on all tables of PICE database from user abebe:
REVOKE SELECT ON PICE.*
FROM „abebe‟@‟localhost‟;

REVOKE SELECT ON PICE FROM user abebe; this command will REVOKE a SELECT
privilege on all tables of PICE database from user abebe. When you REVOKE SELECT
privilege on a database from a user, the user will not be able to SELECT data from that database
tables anymore. However, if the user has received SELECT privileges on that database tables
from more than one user, he/she can SELECT from that database tables until everyone who
granted the permission revokes it. You cannot REVOKE privileges if they were not initially
granted by you.

Privileges and Roles:


Privileges: Privileges defines the access rights provided to a user on a database object. There are
two types of privileges.
1) System privileges - This allows the user to CREATE, ALTER, or DROP database
objects.
2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or
DELETE data from database objects to which the privileges apply.
Few CREATE system privileges are listed below:

System Privileges Description

CREATE object Allows users to create the specified object in their own schema.

CREATE ANY object Allows users to create the specified object in any schema.

The above rules also apply for ALTER and DROP system privileges.

Compiled By: - Melsew D Page 54


SQL Lab Manual PICE

Few of the object privileges are listed below:

Object Privileges Description


INSERT Allows users to insert rows into a table.
SELECT Allows users to select data from a database object.
UPDATE Allows user to update data in a table.
EXECUTE Allows user to execute a stored procedure or a function.

Roles: Roles are a collection of privileges or access rights. When there are many users in a
database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles,
you can grant or revoke privileges to users, thereby automatically granting or revoking
privileges. You can either create Roles or use the system roles pre-defined by oracle.

Some of the privileges granted to the system roles are as given below:

System Role Privileges Granted to the Role


CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE
CONNECT
SEQUENCE, CREATE SESSION etc.

CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE,


RESOURCE CREATE TRIGGER etc. The primary usage of the RESOURCE role is to
restrict access to database objects.

DBA ALL SYSTEM PRIVILEGES

Creating Roles:

The Syntax to create a role is:

CREATE ROLE role_name


[IDENTIFIED BY password];

For Example: To create a role called "testing" with password as "pwd", the code will be as
follows:

CREATE ROLE testing


[IDENTIFIED BY pwd];

Compiled By: - Melsew D Page 55


SQL Lab Manual PICE

It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a
privilege directly to every user. If a role is identified by a password, then, when you GRANT or
REVOKE privileges to the role, you definitely have to identify it with the password.

We can GRANT or REVOKE privilege to a role as below.

For example: To grant CREATE TABLE privilege to a user by creating a testing role:

First, create a testing Role

CREATE ROLE testing


Second, grant a CREATE TABLE privilege to the ROLE testing. You can add more privileges to
the ROLE.
GRANT CREATE TABLE TO testing;

Third, grant the role to a user.

GRANT testing TO user1;

To revoke a CREATE TABLE privilege from testing ROLE, you can write:

REVOKE CREATE TABLE FROM testing;

The Syntax to drop a role from the database is as below:


DROP ROLE role_name;

For example: To drop a role called testing, you can write:


DROP ROLE testing;

Compiled By: - Melsew D Page 56

You might also like