You are on page 1of 60

SQL Introduction SQL stands for Structured Query Language and can be pronounced as SQL or sequel (Structured English

h Query Language). It is a query language used for accessing and modifying information in the database. IBM first developed SQL in 1970s. Also it is an ANSI/ISO standard. It has become a Standard Universal Language used by most of the relational database management systems (RDBMS). Some of the RDBMS systems are: Oracle, Microsoft SQL server, Sybase etc. Most of these have provided their own implementation thus enhancing it's feature and making it a powerful tool. Few of the sql commands used in sql programming are SELECT Statement, UPDATE Statement, INSERT INTO Statement, DELETE Statement, WHERE Clause, ORDER BY Clause, GROUP BY Clause, ORDER Clause, Joins, Views, GROUP Functions, Indexes etc. In a simple manner, SQL is a non-procedural, English-like language that processes data in groups of records rather than one record at a time. Few functions of SQL are:
y y y y y y y

store data modify data retrieve data modify data delete data create tables and other database objects delete data SQL > SQL Syntax

Select Statement SELECT "column_name" FROM "table_name" Distinct SELECT DISTINCT "column_name" FROM "table_name" Where SELECT "column_name" FROM "table_name" WHERE "condition" And/Or SELECT "column_name"

Page 1

Page

FROM "table_name" WHERE "simple condition" {[AND|OR] "simple condition"}+ In SELECT "column_name" FROM "table_name" WHERE "column_name" IN ('value1', 'value2', ...) Between SELECT "column_name" FROM "table_name" WHERE "column_name" BETWEEN 'value1' AND 'value2' Like SELECT "column_name" FROM "table_name" WHERE "column_name" LIKE {PATTERN} Order By SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC, DESC] Count SELECT COUNT("column_name") FROM "table_name" Group By SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1" Having SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1" HAVING (arithematic function condition)

Page 2

Page

Create Table Statement CREATE TABLE "table_name" ("column 1" "data_type_for_column_1",

"column 2" "data_type_for_column_2",.. ) Drop Table Statement DROP TABLE "table_name" Truncate Table Statement TRUNCATE TABLE "table_name" Insert Into Statement INSERT INTO "table_name" ("column1", "column2", ...) VALUES ("value1", "value2", ...) Update Statement UPDATE "table_name" SET "column_1" = [new value] WHERE {condition} Delete From Statement DELETE FROM "table_name" WHERE {condition}

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

Page 3

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.

Creating Tables The create table statement is used to create a new table. Here is the format of a simple create table statement: create table "tablename"("column1" "data type", "column2" "data type", "column3" "data type"); Format of create table if you were to use optional constraints: create table "tablename"("column1" "data type" [constraint], "column2" "data type" [constraint], "column3" "data type" [constraint]); [ ] = optional Note: You may have as many columns as you'd like, and the constraints are optional. Example: create table employee(first varchar(15),last varchar(20), age number(3),address varchar(30),city varchar(20), state varchar(20)); To create a new table, enter the keywords create table followed by the table name, followed by an open parenthesis, followed by the first column name, followed by the data type for that column, followed by any optional constraints, and followed by a closing parenthesis. It is important to make sure you use an open parenthesis before the beginning table, and a closing parenthesis after the end of the last column definition. Make sure you seperate each column definition with a comma. All SQL statements should end with a ";". The table and column names must start with a letter and can be followed by letters, numbers, or underscores - not to exceed a total of 30 characters in length. Do not use any SQL reserved keywords as names for tables or column names (such as "select", "create", "insert", etc).

Page 4

Page

Data types specify what the type of data can be for that particular column. If a column called "Last_Name", is to be used to hold names, then that particular column should have a "varchar" (variable-length character) data type. Here are the most common Data types: char(size) varchar(size) number(size) Date Fixed-length character string. Size is specified in parenthesis. Max 255 bytes. Variable-length character string. Max size is specified in parenthesis. Number value with a max number of column digits specified in parenthesis. Date value

Number value with a maximum number of digits of number(size,d) "size" total, with a maximum number of "d" digits to the right of the decimal.

What are constraints? When tables are created, it is common for one or more columns to have constraints associated with them. A constraint is basically a rule associated with a column that the data entered into that column must follow. For example, a "unique" constraint specifies that no two records can have the same value in a particular column. They must all be unique. The other two most popular constraints are "not null" which specifies that a column can't be left blank, and "primary key". A "primary key" constraint defines a unique identification of each record (or row) in a table. All of these and more will be covered in the future Advanced release of this Tutorial. Constraints can be entered in this SQL interpreter, however, they are not supported in this Intro to SQL tutorial & interpreter. They will be covered and supported in the future release of the Advanced SQL tutorial - that is, if "response" is good. It's now time for you to design and create your own table. You will use this table throughout the rest of the tutorial. If you decide to change or redesign the table, you can either drop it and recreate it or you can create a completely different one. The SQL statement drop will be covered later.
Page

Inserting into a Table

Page 5

The insert statement is used to insert or add a row of data into the table. To insert records into a table, enter the key words insert intofollowed by the table name, followed by an open parenthesis, followed by a list of column names separated by commas, followed by a closing parenthesis, followed by the keyword values, followed by the list of values enclosed in parenthesis. The values that you enter will be held in the rows and they will match up with the column names that you specify. Strings should be enclosed in single quotes, and numbers should not. insert into "tablename"(first_column,...last_column) values (first_value,...last_value); In the example below, the column name first will match up with the value 'Luke', and the column name state will match up with the value 'Georgia'. Example: insert into employee(first, last, age, address, city, state) values ('Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia'); Note: All strings should be enclosed between single quotes: 'string' Insert statement exercises It is time to insert data into your new employee table. Your first three employees are the following: Jonie Weber, Secretary, 28, 19500.00 Potsy Weber, Programmer, 32, 45300.00 Dirk Smith, Programmer II, 45, 75020.00 Enter these employees into your table first, and then insert at least 5 more of your own list of employees in the table. After they're inserted into the table, enter select statements to: 1. Select all columns for everyone in your employee table. 2. Select all columns for everyone with a salary over 30000.

Page 6

Page

3. Select first and last names for everyone that's under 30 years old. 4. Select first name, last name, and salary for anyone with "Programmer" in their title. 5. Select all columns for everyone whose last name contains "ebe". 6. Select the first name for everyone whose first name equals "Potsy". 7. Select all columns for everyone over 80 years old. 8. Select all columns for everyone whose last name ends in "ith". Selecting Data The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement: select "column1"[,"column2",etc] from "tablename" [where "condition"];[] = optional The column names that follow the select keyword determine which columns will be returned in the results. You can select as many column names that you'd like, or you can use a "*" to select all columns. The table name that follows the keyword from specifies the table that will be queried to retrieve the desired results. The where clause (optional) specifies which data values or rows will be returned or displayed, based on the criteria described after the keyword where. SQL WHERE Clause The WHERE Clause is used when you want to retrieve specific information from a table excluding other irrelevant data. For example, when you want to see the information about students in class 10th only then you do need the information about the students in other class. Retrieving information about all the students 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

Page 7

Page

see. WHERE clause can be used along with SELECT, DELETE, UPDATE statements. Syntax of SQL WHERE Clause: WHERE {column or expression} comparison-operator value Syntax for a WHERE clause with Select statement is:

SELECT column_list FROM table-name WHERE condition; column or expression - Is the column of a table or a expression y comparison-operator - operators like = < > etc. y value - Any user value or a column name for comparison For Example: To find the name of a student with id 100, the query would be like:
y

SELECT first_name, last_name FROM student_details WHERE id = 100; Comparison Operators and Logical Operators are used in WHERE Clause. These operators are discussed in the next chapter. 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 SELECT statement. be used in the WHERE clause of the

For example: Lets consider the employee table. If you want to display employee name, current salary, and a 20% increase in the salary for only those products where the percentage increase in salary is greater than 30000, the SELECT statement can be written as shown below
Page

Page 8

SELECT employee

name,

salary,

salary*1.2

AS

new_salary

FROM

WHERE salary*1.2 > 30000; Output: name ---Hrithik Harsha Priya salary ------35000 35000 30000 new_salary -------37000 37000 360000

NOTE: Aliases defined in the SELECT Statement can be used in WHERE Clause. Conditional selections used in the where clause: = > < Equal Greater than Less than

>= Greater than or equal <= Less than or equal <> Not equal to LIKE *See note below The LIKE pattern matching operator can also be used in the conditional selection of the where clause. Like is a very powerful operator that allows you to select only rows that are "like" what you specify. The percent sign "%" can be used as a wild card to match any possible character that might appear before or after the characters specified. For example:

Page 9

Page

select first, last, cityfrom empinfowhere first LIKE 'Er%'; This SQL statement will match any first names that start with 'Er'. Strings must be in single quotes. Or you can specify, select first, lastfrom empinfowhere last LIKE '%s'; This statement will match any last names that end in a 's'. select * from empinfowhere first = 'Eric'; This will only select rows where the first name equals 'Eric' exactly. Sample Table: empinfo first John Mary Eric Mary Ann Ginger Last Jones Jones Edwards Edwards Howell id age city Payson Payson San Diego Phoenix State Arizona Arizona California Arizona

99980 45 99982 25 88232 32 88233 32 98002 42 92001 23 22322 35 32326 52

Cottonwood Arizona Gila Bend Bagdad Tucson Show Low Pinetop Arizona Arizona Arizona Arizona

Sebastian Smith Gus Mary Ann Erica Leroy Gray May

Williams 32327 60 Brown 32380 22

Page 10

Page

10

Arizona

Elroy

Cleaver

32382 22

Globe

Arizona

Enter the following sample select statements in the SQL Interpreter Form at the bottom of this page. Before you press "submit", write down your expected results. Press "submit", and compare the results. select first, last, city from empinfo; select last, city, age from empinfo where age > 30; select first, last, city, state from empinfo where first LIKE 'J%'; select * from empinfo; select first, last, from empinfo where last LIKE '%s'; select first, last, age from empinfo where last LIKE '%illia%'; select * from empinfo where first = 'Eric'; Select statement exercises Enter select statements to: 1. Display the first name and age for everyone that's in the table. 2. Display the first name, last name, and city for everyone that's not from Payson. 3. Display all columns for everyone that is over 40 years old. 4. Display the first and last names for everyone whose last name ends in an "ay". 5. Display all columns for everyone whose first name equals "Mary". 6. Display all columns for everyone whose first name contains "Mary". SQL Comparison Keywords There are other comparison keywords available in sql which are used to enhance the search capabilities of a sql query. They are "IN", "BETWEEN...AND", "IS NULL", "LIKE". Comparision Description

Page 11

Page

11

Operators column value is similar to specified character(s). column value is equal to any one of a specified set of values.

LIKE

IN

column value is between two values, including BETWEEN...AND the end values specified in the range. IS NULL column value does not exist.

SQL LIKE Operator 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

------------- ------------Stephen Fleming

Page 12

Page

12

Shekar

Gowda

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%'; The output would be similar to: first_name last_name

------------- ------------Rahul Sharma

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;

Page 13

Page

13

The output would be similar to: first_name last_name Age

------------- ------------- -----Rahul Anajali Shekar Sharma Bhagwat Gowda 10 12 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

------------- ------------- ---------Anajali Shekar Rahul Stephen Bhagwat Gowda Sharma Fleming Maths Maths Science Science

NOTE:The data used to compare is case sensitive.

Page 14

Page

14

You can include more subjects in the list like ('maths','science','history')

SQL IS NULL Operator 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 Logical Operators There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition. Logical Operators Description For the row to be selected at least one of the conditions must be true. For a row to be selected all the specified conditions must be true. For a row to be selected the specified condition must be false.

OR

AND

Page 15

Page

15

NOT

"OR" Logical Operator: 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, first_name last_name subject

------------- ------------- ---------Anajali Shekar Rahul Stephen Bhagwat Gowda Sharma Fleming Maths Maths Science Science

The following table describes how logical "OR" operator selects a row. Column1 Satisfied? YES YES NO NO Column2 Satisfied? YES NO YES NO Row Selected YES YES YES NO

Page 16

Page

16

"AND" Logical Operator: 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 output would be something like, first_name last_name age

------------- ------------- -----Rahul Anajali Shekar Sharma Bhagwat Gowda 10 12 15

The following table describes how logical "AND" operator selects a row. Column1 Satisfied? YES YES NO NO Column2 Satisfied? YES NO YES NO Row Selected YES NO NO NO

"NOT" Logical Operator: 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.

Page 17

Page

17

For example: If you want to find out the names of the students who do not play football, the query would be like: SELECT first_name, last_name, games FROM student_details WHERE NOT games = 'Football'

The output would be something like, first_name last_name games

---------------- ---------------- ----------Rahul Stephen Shekar Priya Sharma Fleming Gowda Chandra Cricket Cricket Badminton Chess

The following table describes how logical "NOT" operator selects a row. Column1 Satisfied? YES NO NOT Column1 Satisfied? NO YES Row Selected NO YES

Nested Logical Operators: You can use multiple logical operators in an SQL statement. When you combine the logical operators in a SELECT statement, the order in which the statement is processed is 1) NOT 2) AND 3) OR

Page 18

Page

18

For example: If you want to select the names of the students who age is between 10 and 15 years, or those who do not play football, the SELECT statement would be SELECT first_name, last_name, age, games FROM student_details WHERE age >= 10 AND age <= 15 OR NOT games = 'Football' The output would be something like, first_name last_name age Games

------------- ------------- -------- -----------Rahul Priya Sharma Chandra 10 15 Cricket Chess

In this case, the filter works as follows: Condition 1: All the students you do not play football are selected. Condition 2: All the students whose are aged between 10 and 15 are selected. Condition 3: Finally the result is, the rows which satisfy atleast one of the above conditions is returned. NOTE:The order in which you phrase the condition is important, if the order changes you are likely to get a different result. SQL ORDER BY 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.

Page 19

Page

19

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 100 101 102 103 104 Ramesh Hrithik Harsha Soumya Priya Electrical Electronics Aeronautics Electronics InfoTech

age 24 28 28 22 25

Salary 25000 35000 35000 20000 30000

location Bangalore Bangalore Mysore Bangalore Mangalore

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 output would be like Name Salary

---------- ---------Soumya Ramesh Priya Hrithik Harsha 20000 25000 30000 35000 35000

Page 20

Page

The query first sorts the result according to name and then displays it.

20

You can also use more than one column in the ORDER BY clause. If you want to sort the employee salary, the query would be like, table by the name and

SELECT name, salary FROM employee ORDER BY name, salary; The output would be like: name Salary

------------- ------------Soumya Ramesh Priya Harsha Hrithik 20000 25000 30000 35000 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; 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 name, salary FROM employee

The above query sorts only the column 'salary' in descending order and the column 'name' by ascending order.
Page 21

Page

21

ORDER BY name, salary DESC;

If you want to select both name and salary in descending order, the query would be as given below. SELECT name, salary FROM employee ORDER BY name DESC, salary DESC; How to use expressions in the ORDER BY Clause? Expressions in the ORDER BY clause of a SELECT statement. For example: If you want to display employee name, current salary, and a 20% increase in the salary for only those employees for whom the percentage increase in salary is greater than 30000 and in descending order of the increased price, the SELECT statement can be written as shown below SELECT name, salary, salary*1.2 AS new_salary FROM employee WHERE salary*1.2 > 30000 ORDER BY new_salary DESC; The output for the above query is as follows. name salary new_salary

---------- ---------- ------------Hrithik Harsha Priya 35000 35000 30000 37000 37000 36000

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

Page 22

Page

22

SQL GROUP BY Clause

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; The output would be like: Dept ---------------Electrical salary -------------25000

Electronics 55000 Aeronautics 35000 InfoTech 30000 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; The output would be like: location Dept salary ------------- --------------- ----------Bangalore Electrical 25000 Bangalore Electronics 55000 Mysore Aeronautics 35000 Mangalore InfoTech 30000 SQL Integrity Constraints Integrity Constraints are used to apply business rules for the database tables. The constraints available in SQL are Foreign Key, Not Null, Unique, Check. Constraints can be defined in two ways 1) The constraints can be specified immediately after the column definition. This is called column-level definition.

Page 23

Page

23

2) The constraints can be specified after all the columns are defined. This is called table-level definition. 1) SQL Primary key: The primary key of a relational table uniquely identifies each record in the table. It can either be a normal attribute that is guaranteed to be unique (such as Social Security Number in a table with no more than one record per person) or it can be generated by the DBMS (such as a globally unique identifier, or GUID, in Microsoft SQL Server). Primary keys may consist of a single attribute or multiple attributes in combination. This constraint defines a column or combination of columns which uniquely identifies each row in the table. Syntax to define a Primary key at column level: column name datatype [CONSTRAINT constraint_name] PRIMARY KEY Syntax to define a Primary key at table level: [CONSTRAINT constraint_name] PRIMARY KEY (column_name1,column_name2,..) column_name1, column_name2 are the names of the columns which define the primary Key. y The syntax within the bracket i.e. [CONSTRAINT constraint_name] is optional. For Example: To create an employee table with Primary Key constraint, the query would be like. Primary Key at table level:
y

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10),

Page 24

Page

24

age number(2),

salary number(10), location char(10) ); or CREATE TABLE employee ( id number(5) CONSTRAINT emp_id_pk PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10)); Primary Key at table level: CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10), CONSTRAINT emp_id_pk PRIMARY KEY (id));

Page 25

Page

25

In order to know the primary keys of a table,we have a table called USER_CONSTRAINTS.

Example :

select * from user_constraints where table_name = 'EMP' and constraint_type = 'P'

In order to know the column name which is the primary key , we can use

USER_CONS_COLUMNS table.

Example:

SELECT COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = 'EMP_PRIMARY_KEY' 2) SQL Foreign key or Referential Integrity : A foreign key means that values in one table must also appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table. This constraint identifies any column referencing the PRIMARY KEY in another table. It establishes a relationship between two columns in the same table or between different tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One or more columns can be defined as Foreign key.
Page 26

Page

26

Syntax to define a Foreign key at column level: [CONSTRAINT constraint_name] REFERENCES Referenced_Table_name(column_name) Syntax to define a Foreign key at table level: [CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES referenced_table_name(column_name); For Example: 1) Lets use the "product" table and "order_items". Foreign Key at column level: CREATE TABLE product ( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY, product_name char(20), supplier_name char(20), unit_price number(10)); CREATE TABLE order_items ( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY, product_id number(5) CONSTRAINT pd_id_fk REFERENCES, product(product_id), product_name char(20), supplier_name char(20), unit_price number(10));

Page 27

Page

27

Foreign Key at table level:

CREATE TABLE order_items ( order_id number(5) , product_id number(5), product_name char(20), supplier_name char(20), unit_price number(10) CONSTRAINT od_id_pk PRIMARY KEY(order_id), CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES product(product_id)); 2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references primary key 'id' within the same table, the query would be like, CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), mgr_id number(5) REFERENCES employee(id), salary number(10), location char(10) ); 3) SQL Not Null Constraint : By default all columns in a table can contain null values. If you want to ensure that a column must always have a value,

Page 28

Page

28

i.e. it should not be left constraint on it.

blank, then define a NOT NULL

Always be careful in defining NOT NULL constraint on columns, for example in employee table some employees might have commission and some employees might not have any commission. If you put NOT NULL constraint on COMM column then you will not be able insert rows for those employees whose commission is null. Only put NOT NULL constraint on those column which are essential for example in EMP table ENAME column is a good candidate for NOT NULL constraint. This constraint ensures all rows in the table contain a definite value for the column which is specified as not null. Which means a null value is not allowed. Syntax to define a Not Null constraint: [CONSTRAINT constraint name] NOT NULL For Example: To create a employee table with Null value, the query would be like CREATE TABLE employee ( id number(5), name char(20) CONSTRAINT nm_nn NOT NULL, dept char(10), age number(2), salary number(10), location char(10) ); Understand with Example The Tutorial illustrates an example from 'SQL NOT NULL Constraint'. In this example, we create a table Stu_Class_10 with the help of create statement. When you create a table ,we define a field attribute, data type, null value etc. The

Page 29

Page

29

following SQL enforces the Columns "Stu_Id","Stu_Name" and "Stu_Class" column not to accept NULL values. The insert into adds the records value into table'Stu_Class_10'.The select statement show you the records from table 'Stu_Class_10'.When you do not insert any value to record ,the records shows you SQL NOT NULL Constraint. Create Table Stu_Class_10 CREATE TABLE Stu_Class_10( Stu_Id integer(2) NOT NULL, Stu_Name varchar(15) NOT NULL, Stu_Class varchar(10)) NOT NULL) Insert data into Stu_Class_10 table insert insert insert insert insert into into into into into Stu_Class_10 Stu_Class_10 Stu_Class_10 Stu_Class_10 Stu_Class_10 values(1,'Komal',10); values(2,'Ajay',10); values(3,'Rakesh',10); values(4,'Bhanu',10); values(5,'Santosh',10);

Stu_Class_10 Stu_Id 1 2 3 4 5 4) SQL Unique Key: This constraint ensures that a column or a group of columns in each row have a distinct value. A column(s) can have a null value but the values cannot be duplicated. Syntax to define a Unique key at column level: [CONSTRAINT constraint_name] UNIQUE Stu_Name Komal Ajay Rakesh Bhanu Santosh Stu_Class 10 10 10 10 10

Page 30

Page

30

Syntax to define a Unique key at table level: [CONSTRAINT constraint_name] UNIQUE(column_name) For Example: To create an employee table with Unique key, the query would be like, Unique Key at column level: CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10) UNIQUE ); or CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10) CONSTRAINT loc_un UNIQUE ); Unique Key at table level:

Page 31

Page

31

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10), CONSTRAINT loc_un UNIQUE(location) ); 5) SQL Check Constraint : This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint can be applied for a single column or a group of columns. Syntax to define a Check constraint: [CONSTRAINT constraint_name] CHECK (condition) For Example: In the employee table to select the gender of a person, the query would be like Check Constraint at column level: CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2),
Page

gender char(1) CHECK (gender in ('M','F')),

Page 32

32

salary number(10), location char(10) ); Check Constraint at table level: CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), gender char(1), salary number(10), location char(10), CONSTRAINT gender_ck CHECK (gender in ('M','F')) );

ABS

ABS returns the absolute value of n.

The following example returns the absolute value of -87: SELECT ABS(-87) "Absolute" FROM DUAL; Absolute ---------87 CIEL Returns the lowest integer above the given number. Example:

Page 33

Page

select ciel(3.456) Ciel from dual;

33

The following function return the lowest integer above 3.456;

Ciel --------4 FLOOR Example: The following function return the highest integer below 3.456; select floor(3.456) Floor from dual; Floor -----------3 LOG Example The following example returns the log of 100. select log(10,100) from dual; LOG --------2 ROUND Returns a decimal number rounded of to a given decimal positions. Example The following example returns the no. 3.4573 rounded to 2 decimals. select round(3.4573,2) Round from dual; Round -----------3.46 Returns the logarithm, base m, of n. Returns the highest integer below the given number.

Page 34

Page

34

SQRT

Returns

the square root of a given number.

Example The following example returns the square root of select SQRT --------4 GREATEST GREATEST(expr1, expr2, expr3,expr4...) Returns the greatest expr from a expr list. Example select greatest(10,20,50,20,30) from dual; GREATEST -------50 select greatest('SAMI','SCOTT','RAVI','SMITH','TANYA') from dual; GREATEST -------TANYA LEAST LEAST(expr1, expr2, expr3,expr4...) sqrt(16) from dual; 16.

It is simillar to greatest. It returns the least expr from the expression list. select least(10,20,50,20,30) from dual; LEAST

10

Page 35

Page

35

--------

select least('SAMI','SCOTT','RAVI','SMITH','TANYA') from dual; LEAST -------RAVI Aggregate Functions Aggregate functions return a single value based on groups of rows, rather than single value for each row. You can use Aggregate functions in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle divides the rows of a queried table or view into groups. The important Aggregate functions are : Avg AVG Sum Max Min expr) Count Stddev Variance

AVG( ALL /DISTINCT

Returns the average value of expr. Example The following query returns the average salary of all employees. select avg(sal) Average Salary from emp; Average Salary -----------------------2400.40 SUM SUM(ALL/DISTINCT expr)

Returns the sum value of expr. Example The following query returns the sum salary of all employees.

Total Salary

Page 36

Page

36

select sum(sal) Total Salary from emp;

-----------------------26500 MAX MAX(ALL/DISTINCT expr)

Returns maximum value of expr. Example The following query returns the max salary from the employees. select max(sal) Max Salary from emp; Maximum Salary -----------------------4500 MIN MIN(ALL/DISTINCT expr)

Returns minimum value of expr. Example The following query returns the minimum salary from the employees. select min(sal) Min Salary from emp; Minimum Salary -----------------------1200 COUNT COUNT(*) OR COUNT(ALL/DISTINCT expr)

Returns the number of rows in the query. If you specify expr then count ignore nulls. If you specify the asterisk (*), this function returns all rows, including duplicates and nulls. COUNT never returns null. Example The following query returns the number of Select count(*) from emp;
Page 37

employees.

Page

37

COUNT -----14 The following query counts the number of employees whose salary is not null. Select count(sal) from emp; COUNT -----12 Distinct Returns number of categories in given column SELECT DISTINCT "column_name "FROM "table_name" Example Select distinct (sal) from emp11 STDDEV STDDEV(ALL/DISTINCT expr)

STDDEV returns sample standard deviation of expr, a set of numbers. Example The following query returns the standard deviation of salaries. select stddev(sal) from emp; Stddev ------1430 VARIANCE VARIANCE(ALL/DISTINCT expr)

Variance returns the variance of expr.

Page 38

Page

The following query returns the variance of salaries.

38

Example

select variance(sal) from emp; Variance ------1430 String Functions Character functions operate on values of dataype VARCHAR. LOWER Returns a given string in lower case. CHAR or

select LOWER(SAMI) from dual; LOWER ------------sami UPPER Returns a given string in UPPER case.

select UPPER(Sami) from dual; UPPER -----------------SAMI INITCAP capital. Returns a given string with Initial letter in

select INITCAP(mohammed sami) from dual; INITCAP -----------------Mohammed Sami LENGTH Returns the length of a given string. select length(mohammed sami) from dual; LENGTH

Page 39

Page

39

-----------13 SUBSTR Returns a substring from a given string. Starting from position p to n characters. For example the following query returns sam from the string mohammed sami. select substr('mohammed sami',10,3) from dual; Substr -------sam RPAD Right pads a given string with a given character to n number of characters. Example The following query rights pad ename with '*' 10 characters. select rpad(ename,'*',10) from emp; Ename ---------Smith***** John****** Mohammed** Sami****** LPAD Left pads a given string with a given character upto n number of characters. Example The following query left pads ename with '*' 10 characters. until it becomes

Page 40

Page

40

until it becomes

select lpad(ename,'*',10) from emp; Ename ---------*****Smith ******John **Mohammed ******Sami LTRIM Example The following query returns string left trimmed. select ltrim(' Ltrim -------------Interface RTRIM Example The following query returns string right trimmed. select rtrim(' Rtrim -----------Interface TRIM Trims a given character from left or right or both from a given string. Example Interface Interface ') from dual; Trims blank spaces from a given string from Right. Interface Interface ') from dual; Trims blank spaces from a given string from left.

Page 41

Page

41

The following query removes zero from left and right of a given string. Select trim(0 from '00003443500') from dual; Trim ---------34435 Replaces a given set of characters in a string with REPLACE another set of characters. Example The following query replaces mohd with mohammed . select replace('ali mohd khan','mohd','mohammed') from dual; REPLACE --------ali mohammed khan This function is used to encrypt characters. For TRANSLATE example you can use this function to replace characters in a given string with your coded characters. Example The following query replaces characters A with B, B with C, C with D, D with E,...Z with A, and a with b,b with c,c with d, d with e ....z with a. select translate('interface','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno pqrstuvwxyz','BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxy za') Encrypt from dual; Encrypt ----------joufsgbdf
Page

Page 42

42

SOUNDEX This function is used to check pronounciation rather than exact characters. For example many people write names as smith or smyth or smythe but they are pronounced as smith only. Example The following example compare those names which are spelled differently but are pronouced as smith. Select ename from emp where soundex(ename)=soundex('smith'); ENAME --------Smith Smyth Smythe INSTR Tests whether a given character occurs in the given string or not. If the character occurs in the string then returns the first position of its occurrence otherwise returns 0. Example The following query tests whether the character a occurs in string mohammed sami select instr('mohammed sami','a') from dual; INSTR -------Joins Tables are joined in Oracle when data must be retrieved from more than one table. As a result of normalization the tables in a database are stored in their simplest forms with little or no redundancy. This results in separating data based on objects and still maintained relationships based on the values in the tables. Joining tables is an essential part of learning how to query the database, because most of the time all the data is not present in one table. Everytime you need to read information
Page 43

Page

43

that is stored in multiple table, you will need to perform a join operation. In the screenshot below, you are looking at two tables called COUNTRIES and REGIONS. The two countries are related based on the Region_ID column. For example the Region whose ID is 1, and name is Europe, is made up of the countries Belgium, Switzerland, Germany, Denmark, and France in the Countries table. All these countries have their REGION_ID column set to 1. If we want to see an output based on these two tables, displaying the Region_Name and Country_Name, you would need to join the two tables using the relationship created by the REGION_ID column.

There are different types of joins in Oracle, namely: y Cartesian Join


y y y

Page 44

Page

Equi Join Non-Equi Join Outer Join

44

Self Join Joins can be written in two ways in Oracle. One method is the Traditional method, that uses Oracle Proprietary syntax. The other method is called the SQL-1999 syntax. In this article we will discuss the Traditional method where the table are joined using a join condition in the WHERE clause. In a subsequent article, the joining of tables using the SQL-1999 syntax will be discussed.
y

Basic Syntax when joining tables using traditional syntax: SELECT column, column, [table1].column FROM table1 , table2 WHERE [table1].column=[table2].column; Observe the FROM clause, separated by commas. more than one table I mentioned,

Observe the WHERE clause, a join conditon is created that related a column of the first table, with a column of the second table. The query to retrieve the REGION_NAME and its COUNTRY_NAME would be: SELECT REGION_NAME, COUNTRY_NAME FROM COUNTRIES, REGIONS WHERE COUNTRIES.REGION_ID=REGIONS.REGION_ID; Note: Prefixing the table name before the column name becomes mandatory only when the column name is the same in both the tables. If we were to retrieve the REGION_ID column also, then the query would have been written as: SELECT REGION_NAME, COUNTRY_NAME, REGIONS.REGION_ID FROM COUNTRIES, REGIONS WHERE COUNTRIES.REGION_ID=REGIONS.REGION_ID; Sometimes you can even use table aliases in the from clause. This is useful when table names are long and appear many times in the statement. Table aliases are used to simplify queries, improve readability and improve performance. SELECT REGION_NAME, R.REGION_ID, COUNTRY_NAME FROM COUNTRIES C, REGIONS R WHERE C.REGION_ID=R.REGION_ID; In the example, the alias C is given for the COUNTRIES table, and the alias R is given for the REGIONS table. The aliases are defined in the FROM clause, beside the table name separated by a space. Note that once you have defined a table alias in a query the alias must be used in that query whereever the name of the table would appear. A basic important rule to remember when joining tables is:

Page 45

Page

45

Rule: When n tables are joined, a minimum of n-1 join conditions must be written for a correct output. If you do not create n-1 conditions to join the tables you will create a cartesian join, and the output might not be what you want.

In the image above, there are three tables being joined, LOCATIONS, COUNTRIES, REGIONS. Three tables, would require at least 2 valid join conditions. The join condition for the LOCATIONS (alias L) table and COUNTRIES (alias C) table is L.COUNTRY_ID=C.COUNTRY_ID. The join condition for the COUNTRIES (alias C) and the REGIONS (alias R) table is R.REGION_ID=C.REGION_ID. Cartesian Joins A cartesian join is formed when data is retrieved from multiple tables without writing necessary join conditions. In the example below there are 25 rows in the COUNTRIES table and 4 rows in the REGIONS table. The Cartesian join, will create a total of 100 rows. Every row in the COUNTRIES table will be matched with every row in the REGIONS table. SELECT COUNTRY_NAME, REGION_NAME FROM COUNTRIES, REGIONS;

Page 46

Page

46

Equi-Join This type of join (non-equi join) is performed when data to be retrieved is in more than one table, and the data is related based a condition of equality. The example query that we started with is an equi-join: SELECT REGION_NAME, COUNTRY_NAME FROM COUNTRIES, REGIONS WHERE COUNTRIES.REGION_ID=REGIONS.REGION_ID; The REGION_ID in the COUNTRIES table, being equal to the REGION_ID column in the REGIONS table creates an equi-join condition. Equi-joins are the most common type of join that is performed.

Non-Equi Join This type of join (non-equi join) is performed when data to be retrieved is in more than one table, but the data is not related based a condition of equality. The image below shows the grade details (SALGRADE table) and employee details (EMPLOYEES table). Employees are assigned grades based on their salary. Observe the data in the SALGRADE table. The grade A is assigned to employees whose salary is within the range of 1 and 10000. The grade B is assigned to employees whose salary is within the range of 10001

Page 47

Page

47

and 20000, etc. The query on the EMPLOYEES table displays the name, job_id and salary of the employees. If we have to retrieve the name of the employee and their grade, you will have to perform a join. But, the join will not be based on a condition of equality. It is based on a range, and is therefore called a Non-Equi Join.

The query to retrieve the first_name, and the grade would be: SELECT FIRST_NAME, GRADE FROM EMPLOYEES, SALGRADE WHERE EMPLOYEES.SALARY BETWEEN MINSAL AND MAXSAL; Outer Join An outer join is based on an equi-join when additional information from a table needs to be retrieved. Consider the image below, showing the DEPARTMENTS table:

Page 48

Page

48

Now consider a query that is written based on an equi-join that would display the DEPARTMENT_NAME and the FIRST_NAME of the manager of the department. The departments table has only the MANAGER_ID. A manager of the department is an employee of the company. The employee details are in the EMPLOYEES table, therefore to display the name of the department and the manager's name, the query to write would be: SELECT DEPARTMENT_NAME, FIRST_NAME FROM DEPARTMENTS D, EMPLOYEES E WHERE D. MANAGER_ID=E.EMPLOYEE_ID; This query will display all the departments who have manager's and will accurately display the department name and its manager's name. (See image below)

Page 49

Page

49

Page 50

Page

What if we not only wanted to see in this output, the department names that have managers and the departments that do not have managers. This would mean that in addition to the output that you see in the image above, there should be department names that should appear, without a corresponding first_name (for the manager's first_name). This type of query, which needs to display additional information over and above an equi-join is called an outer join. In the outer join type of query, the table without values to display must display nulls. Building on the example we are using, if we wish to see departments that do not have managers also, the DEPARTMENTS table will have data to display, but the EMPLOYEES table will have to display nulls (for first_names). To create an outer join type of query, we make use of an outer join operator. This operator is (+) and needs to be added to the query, in the join condition, against the table that has the null values to display. As per our discussion, the EMPLOYEES table had the nulls to display and therefore, if an outer join had to be created, the equi-join query would be rewritten as:

50

SELECT DEPARTMENT_NAME, FIRST_NAME FROM DEPARTMENTS D, EMPLOYEES E WHERE D. MANAGER_ID=E.EMPLOYEE_ID(+);

Self Join (Inner Join) A self join is a type of join where all the data to retreive is in one table, but not in a single row. Consider the image below and the query that is written.

Page 51

Page

51

Page 52

Page

The employee whose ID is 107, and first name is Diana, has a manager whose ID is 103. Based on the data, the employee whose ID is 103, has a firstname of Alexander. Therefore, we can conclude that Alexander is Diana's manager. If we had to write a query to display the firstname of the employee and the firstname of the manager then all the data we want to retrieve is in one table, however not in a single row of this table. The data to retrieve is based on the two rows, one row which corresponds to the employee, and the second row which corresponds to the manager. This is an example where we would need to perform a self join or an inner join. When performing a self join, we must imagine that we have two versions of the same table. That is we write the same table name twice in the FROM clause, but because we want to interpret them as separate, we must give them two different table aliases. The FROM clause would look like: FROM EMPLOYEES E, EMPLOYEES R

52

One version of the EMPLOYEES table is called E. The second version of the EMPLOYEES table is called R. Now, with the two separate versions, we can create a relationship between them, just as we did an equi-join. The relationship is based on the MANAGER_ID value for the Employee row, being equal to the EMPLOYEE_ID in the Manager row.

Page 53

Page

The relationship can be written as: E.MANAGER_ID=R.EMPLOYEE_ID Therefore, to write out a query that will display the employee's firstname and their manager's firstname we would write: SELECT E.FIRST_NAME, M.FIRST_NAME FROM EMPLOYEES E, EMPLOYEES M WHERE E.MANAGER_ID=R.MANAGER_ID; So far we have discussed what a join in Oracle is, and the different types of joins that are available. To conclude we must note that a query may require additional restrictions to be performed. You may add additional restrictions on the data returned by a join by adding the condition to the WHERE clause using the AND operator. In the example below, we want to see all

53

countries whose name begins with the letter B, along with the region name and region ID. SELECT REGION_NAME, R.REGION_ID, COUNTRY_NAME FROM COUNTRIES C, REGIONS R WHERE C.REGION_ID=R.REGION_ID AND COUNTRY_NAME LIKE 'B%'; Subquery A subquery is a type of SQL query, where a query is embedded within another query. Sub-queries are very powerful. To help you understand a subquery consider the following SELECT statement to retrieve the details of employees who belong to department 30. SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID=30; In the above query, the department ID value has been provided, and is used on the right hand side of the WHERE condition. However, such constant values might not also be provided or known. For example, consider the query re-phrased as - retrieve the details of employees who belong to the same department as 'Alexander Khoo'. Here the department number has not been provided. Instead the name of an employee is given. Using this name, you would need to first find out - to which department does Alexander Khoo belong. Let say this is some value 'X'. You would have to proceed further to find out all the other employees who belong to the department X. If you notice this is a 2-step process involving: 1) Which department does Alexander Khoo belong to. 2) Who are the others who belong to the department number returned by the first step. Subquery Syntax: SELECT select_list FROM table_name WHERE column_name operator (SELECT select_listFROM table_name) In the syntax, observe a second SELECT statement written in the WHERE clause, on the right hand side of the WHERE condition. This SELECT statement is enclosed in parantheses. This subquery is called the inner query and is executed once to return a value that is used by the main (outer) query. Subqueries can be
Page 54

Page

54

different in different places in a SELECT statement, such as the WHERE clause, HAVING clause, FROM clause, SELECT column list etc. The query to retrieve the details of employees who belong to the same department as Alexander Khoo is : SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = (SELECTDEPARTMENT_ID FROM EMPLOYEES WHERE FIRST_NAME='Alexander' AND LAST_NAME='Khoo')

Page 55

Page

55

Example of Subquery Some guidelines related to subqueries are:


y y y y

Page 56

Page

Enclose subqueries in parentheses. Place subqueries on the right side of the comparison condition. Use single-row operators with single-row subqueries. Use multiple-row operators with multiple-row subqueries.

56

A single-row subquery is one where the subquery returns only one value. In such a subquery you must use a single-row operator such as: Operator = <> > >= < <= Equal To Not Equal To Greater Than Greater Than Equal To Less Than Less Than Equal To Description

The single-row operators are used to write single-row subqueries. The table below demonstrates the use of the singlerow operators in writing single-row subqueries.

Operator Query = Retreive the details of employees who get the same salary as the employee whose ID is 101.

Example SELECT * FROM EMPLOYEES WHERE SALARY=(SELECT SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID=101); SELECT * FROM DEPARTMENTS WHERE LOCATION_ID <>(SELECT LOCATION_ID FROM DEPARTMENTS WHERE DEPARTMENT_ID=10); SELECT * FROM EMPLOYEES WHERE SALARY > (SELECT MIN(SALARY) FROM EMPLOYEES);

<>

Retreive the details of departments that are not located in the same location ID as department 10.

>

Page 57

Page

Retrieve the details of employees whose salary is greater than the minimum salary.

57

>=

Retrieve the details of employees who were hired on or after the same date that employee 201 was hired.

SELECT * FROM EMPLOYEES WHERE HIRE_DATE >=(SELECT HIRE_DATE FROM EMPLOYEES WHERE EMPLOYEE_ID=201);

<

Retrieve the details of employees whose salary is less than the maximum salary of employees in department 20.

SELECT * FROM EMPLOYEES WHERE SALARY < (SELECT MAX(SALARY) FROM EMPLOYEES WHERE DEPARTMENT_ID=20);

<=

Retrieve the details of employees who were hired on or before the same date that employee 201 was hired.

SELECT * FROM EMPLOYEES WHERE HIRE_DATE <=(SELECT HIRE_DATE FROM EMPLOYEES WHERE EMPLOYEE_ID=201);

A multiple row subquery is one where the subquery may return more than one value. In such type of subquery, it is necessary to use a multiple-row operator. If not you might get the ORA01427 error: single-row subquery returns more than requested number of rows. The table below describes the multiple-row operators that can be used when writing multiple-row subqueries: Operator Meaning IN ANY ALL Equal to any value returned by the subquery

Page 58

Page

Compare value to every value returned by the subquery

58

Compare value to each value returned by the subquery

The multiple-row operators are used to write multiple-row subqueries. The table below demonstrates the use of the multiple-row operators in writing multiple-row subqueries.

Operator

Query

Example

IN

Retreive the department ID, department name and location ID of departments that are located in the same location ID as a location in the UK.

SELECT DEPARTMENT_ID, DEPARTMENT_NAME, LOCATION_ID FROM DEPARTMENTS WHERE LOCATION_ID IN (SELECT LOCATION_ID FROM LOCATIONS WHERE COUNTRY_ID='UK')

>ALL (Greater than the maximum returned by the subquery)

Retrieve the first name of employees whose salary is greater than the all the salaries of employees belonging to department 20.

SELECT FIRST_NAME FROM EMPLOYEES WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID=20)

<ALL

Retrieve the first name of employees whose salary (Less than the is less than all the least value salaries of employees belonging to department returned by the subquery) 20. >ANY Retrieve the first name of employees whose salary (Greater than is greater than the the minimum minimum salary of value returned employees in department by the 60. subquery)

SELECT FIRST_NAME FROM EMPLOYEES WHERE SALARY < ALL (SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID=20)

SELECT FIRST_NAME FROM EMPLOYEES WHERE SALARY > ANY (SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID=60)

Page 59

Page

59

Retrieve the first name of employees whose salary (Less than the is less than the maximum maximum value salary of employees in returned by department 60. the subquery)

<ANY

SELECT FIRST_NAME FROM EMPLOYEES WHERE SALARY < ANY (SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID=10)

Page 60

Page

60

You might also like