SQL For Trainee Programmers
SQL For Trainee Programmers
SQL Commands:
SQL commands are instructions used to communicate with the database to perform specific task that work with data. SQL
commands can be used not only for searching the database but also to perform various other functions like, for example,
you can create tables, add data to tables, or modify data, drop the table, set permissions for users. SQL commands are
grouped into four major categories depending on their functionality:
• Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and dropping the
structure of database objects. The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
• Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving, modifying, and
deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.
• Transaction Control Language (TCL) - These SQL commands are used for managing changes affecting the
data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.
• Data Control Language (DCL) - These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.
SQL SELECT Statement
The most commonly used SQL command 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.
NOTE: These database tables are used here for better explanation of SQL commands. In reality, the tables can have
different columns and different data.
For example, consider the table student_details. To select the first name of all the students the query would be like:
SELECT first_name FROM student_details;
NOTE: The commands are not case sensitive. The above SELECT statement can also be written as "select first_name
from students_details;"
You can also retrieve data from more than one column. For example, to select first name and last name of all the students.
SELECT first_name, last_name FROM student_details;
Expressions combine many arithmetic operators, they can be used in SELECT, WHERE and ORDER BY Clauses of the
SQL SELECT Statement.
Here we will explain how to use expressions in the SQL SELECT Statement. About using expressions in WHERE and
ORDER BY clause, they will be explained in their respective sections.
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 an employee combined together, the SQL Select Statement
would be like
SELECT first_name || ' ' || last_name FROM employee;
Output:
first_name || ' ' || last_name
---------------------------------
Sai Manoj
Subba Rao
Sateesh Kumar
Raman Kumar
Pavan Kumar
You can also provide aliases as below.
SELECT first_name || ' ' || last_name AS emp_name FROM employee;
Output:
emp_name
-------------
Sai Manoj
Subba Rao
Sateesh Kumar
Raman Kumar
Pavan Kumar
SQL Alias
SQL Aliases are defined for columns and tables. Basically aliases is created to make the column selected more readable.
For Example: To select the first name of all the students, the query would be like:
Aliases for columns:
NOTE: Aliases defined in the SELECT Statement can be used in WHERE Clause.
SQL Operators
There are two type of Operators, namely Comparison Operators and Logical Operators. These operators are used mainly
in the WHERE clause, HAVING clause to filter the data to be selected.
Comparison Operators:
Comparison operators are used to compare the column data with specific values in a condition.
Comparison Operators are also used along with the SELECT statement to filter data based on specific conditions.
The below table describes each comparison operator.
Comparison
Description
Operators
= equal to
Logical Operators:
If you want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR.
For example: if you want to find the names of students who are studying either Maths or Science, the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject = 'Maths' OR subject = 'Science'
The output would be something like,
SQL Material For Trainee Programmers Tuesday, June 14, 2011
first_name last_name subject
------------- ------------- ----------
Subba Rao Maths
Raman Kumar Maths
Sai Manoj Science
Sateesh Kumar Science
The following table describes how logical "OR" operator selects a row.
Column1 Satisfied? Column2 Satisfied? Row Selected
YES NO YES
NO YES YES
NO NO NO
If you want to select rows that must satisfy all the given conditions, you can use the logical operator, AND.
For Example: To find the names of the students between the age 10 to 15 years, the query would be like:
SELECT first_name, last_name, age
FROM student_details
WHERE age >= 10 AND age <= 15;
The following table describes how logical "AND" operator selects a row.
Column1 Satisfied? Column2 Satisfied? Row Selected
YES NO NO
NO YES NO
NO NO NO
If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results in the reverse
of a condition. That is, if a condition is satisfied, then the row is not returned.
The following table describes how logical "NOT" operator selects a row.
NOT Column1
Column1 Satisfied? Row Selected
Satisfied?
YES NO NO
NO YES YES
--------
------------- ------------- --------
----
Cricke
Sai Manoj 10
t
Pavan Kumar 15 Chess
Comparison
Description
Operators
The LIKE operator is used to list all rows in a table whose column values match a specified pattern. It is useful when you
want to search rows to match a specific pattern, or when you do not know the entire value. For this purpose we use a
wildcard character '%'.
For example: To select all the students whose name begins with 'S'
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE 'S%';
The output would be similar to:
first_name last_name
------------- -------------
Sateesh Kumar
Raman Kumar
The above select statement searches for all the rows where the first letter of the column first_name is 'S' and rest of the
letters in the name can be any character.
There is another wildcard character you can use with LIKE operator. It is the underscore character, ' _ ' . In a search string,
the underscore signifies a single character.
For example: to display all the names with 'a' second character,
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE '_a%';
NOTE:Each underscore act as a placeholder for only one character. So you can use more than one underscore. Eg: ' __i%
'-this has two underscores towards the left, 'S__j%' - this has two underscores between character 'S' and 'i'.
SQL BETWEEN ... AND Operator
The operator BETWEEN and AND, are used to compare data for a range of values.
For Example: to find the names of the students between age 10 to 15 years, the query would be like,
SELECT first_name, last_name, age
FROM student_details
WHERE age BETWEEN 10 AND 15;
The output would be similar to:
first_name last_name age
Sai Manoj 10
Subba Rao 12
Raman Kumar 15
SQL IN Operator:
The IN operator is used when you want to compare a column with more than one value. It is similar to an OR condition.
For example: If you want to find the names of students who are studying either Maths or Science, the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject IN ('Maths', 'Science');
The output would be similar to:
first_name last_name subject
------------- ------------- ----------
Subba Rao Maths
Raman Kumar Maths
Sai Manoj Science
Sateesh Kumar Science
A column value is NULL if it does not exist. The IS NULL operator is used to display all the rows for columns that do not
have a value.
For Example: If you want to find the names of students who do not participate in any games, the query would be as given
below
SELECT first_name, last_name
FROM student_details
WHERE games IS NULL
There would be no output as we have every student participate in a game in the table student_details, else the names of the
students who do not participate in any games would be displayed.
SQL ORDER BY
SQL Material For Trainee Programmers Tuesday, June 14, 2011
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]];
database table "employee";
id name dept age salary location
For Example: If you want to sort the employee table by salary of the employee, the sql query would be.
SELECT name, salary FROM employee ORDER BY salary;
The query first sorts the result according to name and then displays it.
You can also use more than one column in the ORDER BY clause.
If you want to sort the employee table by the name and salary, the query would be like,
SELECT name, salary FROM employee ORDER BY name, salary;
The output would be like:
name salary
------------- -------------
Jyothsna 20000
Chandu 25000
Pavan 30000
Sahithi 35000
Srivani 35000
NOTE:The columns specified in ORDER BY clause should be one of the columns selected in the SELECT column list.
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.
The above query can also be written as given below,
SELECT name, salary FROM employee ORDER BY 1, 2;
Group functions are built-in SQL functions that operate on groups of rows and return one value for the entire group. These
functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT
SQL COUNT ( ): 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 dept = 'Electronics';
If you want the total number of employees in all the department, the query would take the form:
SQL MAX( ): This function is used to get the maximum value from a column.
To get the maximum salary drawn by an employee, the query would be:
SQL MIN( ): This function is used to get the minimum value from a column.
SQL AVG( ): This function is used to get the average value of a numeric column.
SQL SUM( ): This function is used to get the sum of a numeric column
The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped according to one or more
columns.
For Example: If you want to know the total amount of salary spent on each department, the query would be:
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept;
NOTE: The group by clause should contain all the columns in the select list expect those used along with the group
functions.
SELECT location, dept, SUM (salary)
FROM employee
GROUP BY location, dept;
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.
For Example: If you want to select the department that has total salary paid for its employees more than 25000, the sql
query would be like;
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000
When WHERE, GROUP BY and HAVING 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. Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the
final output is displayed.
SQL INSERT Statement
The INSERT Statement is used to add new rows of data to a table.
We can insert data to a table in two ways,
1) Inserting the data directly to a table.
Syntax for SQL INSERT is:
UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[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.
For Example: To update the location of an employee, the sql update query would be like,
UPDATE employee
SET location ='Mysore'
WHERE id = 101;
To change the salaries of all the employees, the query would be,
UPDATE employee
SET salary = salary + (salary * 0.2);
SQL Delete Statement
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. A SQL Join condition is used in the SQL WHERE Clause of select, update, delete statements.
Lets use the below two tables to explain the sql join conditions.
SQL Joins can be classified into Equi join and Non Equi join.
It is a simple sql join condition which uses the equal sign as the comparison operator. Two types of equi joins are SQL
Outer join and SQL Inner join.
For example: You can get the information about a customer who purchased a product and the quantity of product.
2) SQL Non equi joins
It is a sql join condition which makes use of some comparison operator other than the equal sign like >, <, >=, <=
1) SQL Equi Joins:
All the rows returned by the sql query satisfy the sql join condition specified.
For example: If you want to display the product information for each order the query will be as given below. Since you
are retrieving the data from two tables, you need to identify the common column between these two tables, which is
theproduct_id.
The query for this type of sql joins would be like,
SELECT order_id, product_name, unit_price, supplier_name, total_units
FROM product, order_items
WHERE order_items.product_id = product.product_id;
The columns must be referenced by the table name in the join condition, because product_id is a column in both the tables
and needs a way to be identified. This avoids ambiguity in using the columns in the SQL SELECT statement.
The number of join conditions is (n-1), if there are more than two tables joined in a query where 'n' is the number of tables
involved. The rule must be true to avoid Cartesian product.
We can also use aliases to reference the column name, then the above query would be like,
SQL Material For Trainee Programmers Tuesday, June 14, 2011
SELECT o.order_id, p.product_name, p.unit_price, p.supplier_name, o.total_units
FROM product p, order_items o
WHERE o.product_id = p.product_id;
b) SQL Outer Join:
This sql join condition returns all rows from both tables which satisfy the join condition along with rows which do not
satisfy the join condition from one of the tables. The sql outer join operator in Oracle is ( + ) and is used on one side of the
join condition only.
The syntax differs for different RDBMS implementation. Few of them represent the join conditions as "sql left outer join",
"sql right outer join".
If you want to display all the product data along with order items data, with null values displayed for order items if a
product has no order item, the sql query for outer join would be as shown below:
SELECT p.product_id, p.product_name, o.order_id, o.total_units
FROM order_items o, product p
WHERE o.product_id (+) = p.product_id;
The output would be like,
product_id product_name order_id total_units
NOTE:If the (+) operator is used in the left side of the join condition it is equivalent to left outer join. If used on the right
side of the join condition it is equivalent to right outer join.
SQL Self Join:
A Self Join is a type of sql join which is used to join a table to itself, particularly when the table has a FOREIGN KEY
that references its own PRIMARY KEY. It is necessary to ensure that the join statement defines an alias for both copies of
the table to avoid column ambiguity.
The below query is an example of a self join,
SELECT a.sales_person_id, a.name, a.manager_id, b.sales_person_id, b.name
FROM sales_person a, sales_person b
WHERE a.manager_id = b.sales_person_id;
2) SQL Non Equi Join:
A Non Equi Join is a SQL Join whose condition is established using all comparison operators except the equal (=)
operator. Like >=, <=, <, >
For example: If you want to find the names of students who are not studying either Economics, the sql query would be
like, (lets use student_details table defined earlier.)
SELECT first_name, last_name, subject
FROM student_details
WHERE subject != 'Economics'
The output would be something like,
first_name last_name subject
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.
For Example:
1) Usually, a subquery should return only one record, but sometimes it can also return multiple records when used with
operators like IN, NOT IN in the where clause. The query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE games NOT IN ('Cricket', 'Football');
The output would be similar to:
first_name last_name subject
2) Lets consider the student_details table which we have used earlier. If you know the name of the students who are
studying science subject, you can get their id's by using this query below,
SQL Material For Trainee Programmers Tuesday, June 14, 2011
SELECT id, first_name
FROM student_details
WHERE first_name IN ('Sai', 'Sateesh');
but, if you do not know their names, then to get their id's you need to write the query in this manner,
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Output:
id first_name
-------- -------------
100 Sai
102 Sateesh
In the above sql statement, first the inner query is processed first and then the outer query is processed.
3) Subquery can be used with INSERT statement to add rows of data from one or more tables to another table. Lets try to
group all the students who study Maths in a table 'maths_group'.
INSERT INTO maths_group(id, name)
SELECT id, first_name || ' ' || last_name
FROM student_details WHERE subject= 'Maths'
4) A subquery can be used in the SELECT statement as follows. Lets use the product and order_items table defined in the
sql_joins section.
select p.product_name, p.supplier_name, (select order_id from order_items where product_id = 101) as
order_id from product p where p.product_id = 101
supplier_name order_id
product_name
------------------ ------------------ ----------
Television Onida 5103
Correlated Subquery
A query is called correlated subquery when both the inner query and the outer query are interdependent. For every row
processed by the inner query, the outer query is processed as well. The inner query depends on the outer query before it
can be processed.
SELECT p.product_name FROM product p
WHERE p.product_id = (SELECT o.product_id FROM order_items o
WHERE o.product_id = p.product_id);
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
• table_name is the name of the table to which the indexed column belongs.
In Oracle there are two types of SQL index namely, implicit and explicit.
Implicit Indexes:
They are created when a column is explicity defined with PRIMARY KEY, UNIQUE KEY Constraint.
Explicit Indexes:
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}
For Eample: REVOKE SELECT ON employee FROM user1;This commmand will REVOKE a SELECT privilege on
employee table from user1.When you REVOKE SELECT privilege on a table from a user, the user will not be able to
SELECT data from that table anymore. However, if the user has received SELECT privileges on that table from more
than one users, he/she can SELECT from that table 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
The above rules also apply for ALTER and DROP system privileges.
Few of the object privileges are listed below:
Object Privileges Description
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:
Creating Roles:
Numeric functions are used to perform operations on numbers. They accept numeric values as input and return numeric
values as output. Few of the Numeric functions are:
Function Name Return Value
CEIL (x) Integer value that is Greater than or equal to the number 'x'
FLOOR (x) Integer value that is Less than or equal to the number 'x'
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places
The following examples explains the usage of the above numeric functions
Function Name Examples Return Value
ABS (1) 1
ABS (x)
ABS (-1) -1
CEIL (2.83) 3
CEIL (x) CEIL (2.49) 3
CEIL (-1.6) -1
FLOOR (2.83) 2
FLOOR (x) FLOOR (2.49) 2
FLOOR (-1.6) -2
Character or text functions are used to manipulate text strings. They accept strings or characters as input and can return
both character and number values as output.
LTRIM (string_value,
All occurrences of 'trim_text' is removed from the left of 'string_value'.
trim_text)
RTRIM (string_value,
All occurrences of 'trim_text' is removed from the right of'string_value' .
trim_text)
TRIM (trim_text FROM All occurrences of 'trim_text' from the left and right of 'string_value' ,'trim_text' can also be
string_value) only one character long .
SUBSTR (string_value, m, n) Returns 'n' number of characters from'string_value' starting from the 'm'position.
LPAD (string_value, n, Returns 'string_value' left-padded with'pad_value' . The length of the whole string will be
pad_value) of 'n' characters.
RPAD (string_value, n, Returns 'string_value' right-padded with 'pad_value' . The length of the whole string will be
pad_value) of 'n' characters.
For Example, we can use the above UPPER() text function with the column value as follows.
SELECT UPPER (product_name) FROM product;
The following examples explains the usage of the above character or text functions
Function Name Examples Return Value
TRIM (trim_text FROM string_value) TRIM ('o' FROM 'Good Morning') Gd Mrning
3) Date Functions:
These are functions that take values that are of datatype DATE as input and return values of datatypes DATE, except for
the MONTHS_BETWEEN function, which returns a number as output.
Few date functions are as given below.
Function Name Return Value
ADD_MONTHS (date, n) Returns a date value after adding 'n'months to the date 'x'.
MONTHS_BETWEEN (x1,
Returns the number of months between dates x1 and x2.
x2)
Returns the date 'x' rounded off to the nearest century, year, month, date, hour, minute, or
ROUND (x, date_format)
second as specified by the 'date_format'.
Returns the date 'x' lesser than or equal to the nearest century, year, month, date, hour, minute,
TRUNC (x, date_format)
or second as specified by the 'date_format'.
NEXT_DAY (x, week_day) Returns the next date of the 'week_day'on or after the date 'x' occurs.
LAST_DAY (x) It is used to determine the number of days remaining in a month from the date 'x' specified.
The below table provides the examples for the above functions
Function Name Examples Return Value
These are functions that help us to convert a value in one form to another form. For Ex: a null value into an actual value,
or a value from one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE.
Few of the conversion functions available in oracle are:
Function Name Return Value
Converts Numeric and Date values to a character string value. It cannot be used for
TO_CHAR (x [,y])
calculations since it is a string value.
Converts a valid Numeric and Character values to a Date value. Date is formatted to the
TO_DATE (x [, date_format])
format specified by 'date_format'.
NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y'must be of the same datatype.
DECODE (a, b, c, d, e, Checks the value of 'a', if a = b, then returns'c'. If a = d, then returns 'e'. Else,
default_value) returnsdefault_value.
The below table provides the examples for the above functions
Function Name Examples Return Value
1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.
For Example: Write the query as
SELECT id, first_name, last_name, age, subject FROM student_details;
Instead of:
SELECT * FROM student_details;
2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING
clause for any other purposes.
For Example: Write the query as
SELECT subject, count(subject)
FROM student_details
WHERE subject != 'Science'
AND subject != 'Maths'
GROUP BY subject;
Instead of:
SELECT subject, count(subject)
FROM student_details
SQL Material For Trainee Programmers Tuesday, June 14, 2011
GROUP BY subject
HAVING subject!= 'Vancouver' AND subject!= 'Toronto';
3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block
in your query.
For Example: Write the query as
SELECT name
FROM employee
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = 'Electronics';
Instead of:
SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';
4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.
For Example: Write the query as
Select * from product p
where EXISTS (select * from order_items o
where o.product_id = p.product_id)
Instead of:
Select * from product p
where product_id IN
(select product_id from order_items
5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as
SELECT d.dept_id, d.dept
FROM dept d
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);
Instead of:
SELECT DISTINCT d.dept_id, d.dept
FROM dept d,employee e
WHERE e.dept = e.dept;
6) Try to use UNION ALL in place of UNION.
For Example: Write the query as
SELECT id, first_name
FROM student_details_class10
UNION ALL
SELECT id, first_name
FROM sports_team;
Instead of: